Salome HOME
untabify
[modules/kernel.git] / src / SALOMEDSImpl / SALOMEDSImpl_StudyManager.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //  File   : SALOMEDSImpl_StudyManager.cxx
23 //  Author : Sergey RUIN
24 //  Module : SALOME
25 //
26 #include "SALOMEDSImpl_StudyManager.hxx"
27
28 #include "DF_ChildIterator.hxx"
29 #include "HDFexplorer.hxx"
30
31 #include "SALOMEDSImpl_Attributes.hxx"
32 #include "SALOMEDSImpl_Tool.hxx"
33 #include "SALOMEDSImpl_SComponent.hxx"
34 #include "SALOMEDSImpl_GenericAttribute.hxx"
35 #include "SALOMEDSImpl_ScalarVariable.hxx"
36 #include <map>
37
38 #include "HDFOI.hxx"
39 #include <iostream>
40 #include <stdlib.h>
41 #include <string.h>
42
43 #ifdef WIN32
44 #include <Windows.h>
45 #endif
46
47 //Warning undef of Ascii Winwows define
48 #ifdef WIN32
49 # undef GetUserName
50 #endif
51
52 using namespace std;
53
54 #define USE_CASE_LABEL_ID                       "0:2"
55
56 static void SaveAttributes(const SALOMEDSImpl_SObject& SO, HDFgroup *hdf_group_sobject);
57 static void ReadAttributes(SALOMEDSImpl_Study*, const SALOMEDSImpl_SObject&, HDFdataset* );
58 static void BuildTree (SALOMEDSImpl_Study*, HDFgroup*);
59 static void Translate_IOR_to_persistentID (const SALOMEDSImpl_SObject&,
60                                            SALOMEDSImpl_Driver*, bool isMultiFile, bool isASCII);
61 static void ReadNoteBookVariables(SALOMEDSImpl_Study* theStudy, HDFgroup* theGroup);
62
63 //============================================================================
64 /*! Function : SALOMEDSImpl_StudyManager
65  *  Purpose  : SALOMEDSImpl_StudyManager constructor
66  */
67 //============================================================================
68 SALOMEDSImpl_StudyManager::SALOMEDSImpl_StudyManager()
69 {
70   _errorCode = "";
71   _appli = new DF_Application();
72   _IDcounter = 0;
73   _clipboard = _appli->NewDocument("SALOME_STUDY");
74 }
75
76 //============================================================================
77 /*! Function : ~SALOMEDSImpl_StudyManager
78  *  Purpose  : SALOMEDSImpl_StudyManager destructor
79  */
80 //============================================================================
81 SALOMEDSImpl_StudyManager::~SALOMEDSImpl_StudyManager()
82 {
83   _appli->Close(_clipboard);
84   // Destroy application
85   delete _appli;    
86 }
87
88
89 //============================================================================
90 /*! Function : NewStudy
91  *  Purpose  : Create a New Study of name study_name
92  */
93 //==================================================T==========================
94 SALOMEDSImpl_Study* SALOMEDSImpl_StudyManager::NewStudy(const string& study_name)
95 {
96   _errorCode = "";
97
98   DF_Document* Doc = _appli->NewDocument("SALOME_STUDY");
99
100   SALOMEDSImpl_Study* Study = new SALOMEDSImpl_Study(Doc, study_name);
101
102   _IDcounter++;
103   Study->StudyId( _IDcounter );
104
105   // set Study properties
106   SALOMEDSImpl_AttributeStudyProperties* aProp = Study->GetProperties();
107   
108   int month=0,day=0,year=0,hh=0,mn=0,ss=0;
109   SALOMEDSImpl_Tool::GetSystemDate(year, month, day, hh, mn, ss);
110   aProp->SetModification(SALOMEDSImpl_Tool::GetUserName(),
111                          mn, hh, day, month, year);
112   aProp->SetCreationMode(1);  //"from scratch"
113
114   return Study;
115 }
116
117 //============================================================================
118 /*! Function : Open
119  *  Purpose  : Open a Study from it's persistent reference
120  */
121 //============================================================================
122 SALOMEDSImpl_Study* SALOMEDSImpl_StudyManager::Open(const string& aUrl)
123 {
124   _errorCode = "";
125
126   // open the HDFFile
127   HDFfile *hdf_file =0;
128   HDFgroup *hdf_group_study_structure =0;
129   HDFgroup *hdf_notebook_vars = 0; 
130
131   char* aC_HDFUrl;
132   string aHDFUrl;
133   bool isASCII = false;
134   if (HDFascii::isASCII(aUrl.c_str())) {
135     isASCII = true;
136     char* aResultPath = HDFascii::ConvertFromASCIIToHDF(aUrl.c_str());
137     aC_HDFUrl = new char[strlen(aResultPath) + 19];
138     sprintf(aC_HDFUrl, "%shdf_from_ascii.hdf", aResultPath);
139     delete [] (aResultPath);
140     aHDFUrl = aC_HDFUrl;
141     delete [] aC_HDFUrl;
142   } else {
143     aHDFUrl = aUrl;
144   }
145
146   
147   hdf_file = new HDFfile((char*)aHDFUrl.c_str());
148   try {
149     hdf_file->OpenOnDisk(HDF_RDONLY);// mpv: was RDWR, but opened file can be write-protected too
150   }
151   catch (HDFexception)
152     {
153         char *eStr;
154         eStr = new char[strlen(aUrl.c_str())+17];
155         sprintf(eStr,"Can't open file %s",aUrl.c_str());
156          delete [] eStr;
157         _errorCode = string(eStr);
158         return NULL;
159     }
160
161   // Temporary aStudyUrl in place of study name
162   DF_Document* Doc = _appli->NewDocument("SALOME_STUDY");
163
164   SALOMEDSImpl_Study* Study = new SALOMEDSImpl_Study(Doc, aUrl);
165
166   _IDcounter++;
167   Study->StudyId( _IDcounter );
168
169   // Assign the value of the URL in the study object
170   Study->URL (aUrl);
171
172   SALOMEDSImpl_AttributePersistentRef::Set(Doc->Main(), aUrl);
173
174   if (!hdf_file->ExistInternalObject("STUDY_STRUCTURE")) {
175      _errorCode = "Study is empty";
176     return Study;
177   }
178
179   //Create  the Structure of the Document
180   hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
181
182   try {
183     BuildTree (Study, hdf_group_study_structure);
184   }
185   catch (HDFexception)
186     {
187       char *eStr = new char [strlen(aUrl.c_str())+17];
188       sprintf(eStr,"Can't open file %s", aUrl.c_str());
189       _errorCode = string(eStr);
190       return NULL;
191     }
192
193   //Read and create notebook variables 
194   if(hdf_file->ExistInternalObject("NOTEBOOK_VARIABLES")) {
195     hdf_notebook_vars  = new HDFgroup("NOTEBOOK_VARIABLES",hdf_file);
196     ReadNoteBookVariables(Study,hdf_notebook_vars);
197     hdf_notebook_vars =0; //will be deleted by hdf_sco_group destructor
198   }
199
200   hdf_file->CloseOnDisk();
201   hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
202   
203   if (isASCII) {
204     vector<string> aFilesToRemove;
205     aFilesToRemove.push_back("hdf_from_ascii.hdf");
206     SALOMEDSImpl_Tool::RemoveTemporaryFiles(SALOMEDSImpl_Tool::GetDirFromPath(aHDFUrl), aFilesToRemove, true);
207   }
208
209   delete hdf_file; // all related hdf objects will be deleted
210
211   return Study;
212 }
213
214
215
216 //============================================================================
217 /*! Function : Close
218  *  Purpose  : Close a study.
219  *             If the study hasn't been saved, ask the user to confirm the
220  *             close action without saving
221  */
222
223 //============================================================================
224 void  SALOMEDSImpl_StudyManager::Close(SALOMEDSImpl_Study* aStudy)
225 {
226   _errorCode = "";
227
228   if(!aStudy) {
229     _errorCode = "Study is null";
230     return;
231   }
232
233   aStudy->Close();
234   DF_Document* doc=aStudy->GetDocument();
235   _appli->Close(doc);
236 }
237
238 //============================================================================
239 /*! Function : Save
240  *  Purpose  : Save a Study to it's persistent reference
241  */
242 //============================================================================
243 bool SALOMEDSImpl_StudyManager::Save(SALOMEDSImpl_Study* aStudy,
244                                      SALOMEDSImpl_DriverFactory* aFactory,
245                                      bool theMultiFile)
246 {
247   _errorCode = "";
248
249   string url = aStudy->URL();
250   if (url.empty()) {
251     _errorCode = "No path specified to save the study. Nothing done";
252     return false;
253   }
254   else {
255     return Impl_SaveAs(url,aStudy, aFactory, theMultiFile, false);
256   }
257
258   return false;
259 }
260
261 bool SALOMEDSImpl_StudyManager::SaveASCII(SALOMEDSImpl_Study* aStudy,
262                                           SALOMEDSImpl_DriverFactory* aFactory,
263                                           bool theMultiFile)
264 {
265   _errorCode = "";
266
267   string url = aStudy->URL();
268   if (url.empty()) {
269     _errorCode = "No path specified to save the study. Nothing done";
270     return false;
271   }
272   else {
273     return Impl_SaveAs(url,aStudy, aFactory, theMultiFile, true);
274   }
275
276   return false;
277 }
278
279 //=============================================================================
280 /*! Function : SaveAs
281  *  Purpose  : Save a study to the persistent reference aUrl
282  */
283 //============================================================================
284 bool SALOMEDSImpl_StudyManager::SaveAs(const string& aUrl,
285                                        SALOMEDSImpl_Study* aStudy,
286                                        SALOMEDSImpl_DriverFactory* aFactory,
287                                        bool theMultiFile)
288 {
289   _errorCode = "";
290   return Impl_SaveAs(aUrl,aStudy, aFactory, theMultiFile, false);
291 }
292
293 bool SALOMEDSImpl_StudyManager::SaveAsASCII(const string& aUrl,
294                                             SALOMEDSImpl_Study* aStudy,
295                                             SALOMEDSImpl_DriverFactory* aFactory,
296                                             bool theMultiFile)
297 {
298   _errorCode = "";
299   return Impl_SaveAs(aUrl,aStudy, aFactory, theMultiFile, true);
300 }
301
302 //============================================================================
303 /*! Function : GetOpenStudies
304  *  Purpose  : Get name list of open studies in the session
305  */
306 //============================================================================
307 vector<SALOMEDSImpl_Study*> SALOMEDSImpl_StudyManager::GetOpenStudies()
308 {
309   _errorCode = "";
310   vector<SALOMEDSImpl_Study*> aList;
311
312   int nbDocs = _appli->NbDocuments();
313
314   if(nbDocs == 0) {
315     _errorCode = "No active study in this session";
316     return aList;
317   }
318   else {
319     SALOMEDSImpl_Study* aStudy;
320     vector<int> ids = _appli->GetDocumentIDs();
321     for (int i = 0, len = ids.size(); i<len; i++) {
322       DF_Document* D = _appli->GetDocument(ids[i]);
323       if(D == _clipboard) continue;
324       aStudy = SALOMEDSImpl_Study::GetStudy(D->Main());
325       if(!aStudy) continue;
326       aList.push_back(aStudy);
327     }
328   }
329
330   return aList;
331 }
332
333 //============================================================================
334 /*! Function : GetStudyByName
335  *  Purpose  : Get a study from its name
336  */
337 //============================================================================
338 SALOMEDSImpl_Study* SALOMEDSImpl_StudyManager::GetStudyByName
339                                    (const string& aStudyName)
340 {
341   _errorCode = "";
342   int nbDocs = _appli->NbDocuments();
343
344   if (nbDocs == 0) {
345     _errorCode = "No active study in this session";
346     return NULL;
347   }
348   else {
349     vector<SALOMEDSImpl_Study*> studies = GetOpenStudies();
350     for (int i = 0, len = studies.size(); i<len; i++) {
351       if (studies[i]->Name() == aStudyName) return studies[i];
352     }
353   }
354
355   _errorCode = string("Found no study with the name ") + aStudyName;
356   return NULL;
357 }
358
359 //============================================================================
360 /*! Function : GetStudyByID
361  *  Purpose  : Get a study from its ID
362  */
363 //============================================================================
364 SALOMEDSImpl_Study* SALOMEDSImpl_StudyManager::GetStudyByID(int aStudyID)
365 {
366   _errorCode = "";
367   int nbDocs = _appli->NbDocuments();
368
369   if (nbDocs == 0) {
370     _errorCode = "No active study in this session";
371     return NULL;
372   }
373   else {
374     vector<SALOMEDSImpl_Study*> studies = GetOpenStudies();
375     for (int i = 0, len = studies.size(); i<len; i++) {
376       if (studies[i]->StudyId() == aStudyID) return studies[i];
377     }
378   }
379
380   _errorCode = "Found no study with the given ID";
381   return NULL;
382 }
383
384 //=============================================================================
385 /*! Function : _SaveProperties
386  *  Purpose  : save the study properties in HDF file
387  */
388 //============================================================================
389 bool SALOMEDSImpl_StudyManager::Impl_SaveProperties(SALOMEDSImpl_Study* aStudy,
390                                                     HDFgroup *hdf_group)
391 {
392   _errorCode = "";
393
394   HDFdataset *hdf_dataset = 0;
395   hdf_size size[1];
396   hdf_int32 name_len;
397
398   // add modifications list (user and date of save)
399   SALOMEDSImpl_AttributeStudyProperties* aProp = aStudy->GetProperties();
400   int aLocked = aProp->IsLocked();
401   if (aLocked) aProp->SetLocked(false);
402
403   int month=0,day=0,year=0,hh=0,mn=0,ss=0;
404   SALOMEDSImpl_Tool::GetSystemDate(year, month, day, hh, mn, ss);
405   aProp->SetModification(SALOMEDSImpl_Tool::GetUserName(),
406                          mn, hh, day, month, year);
407
408   if (aLocked) aProp->SetLocked(true);
409
410   vector<string> aNames;
411   vector<int> aMinutes, aHours, aDays, aMonths, aYears;
412
413   aProp->GetModifications(aNames, aMinutes, aHours, aDays, aMonths, aYears);
414
415   int aLength = 0, anIndex, i;
416   for(i=1; i<=aNames.size(); i++)
417     aLength += aNames[i-1].size() + 1;
418
419   //string length: 1 byte = locked flag, 1 byte = modified flag, (12 + name length + 1) for each name and date, "zero" byte
420   char* aProperty = new char[3 + aLength + 12 * aNames.size()];
421
422
423   sprintf(aProperty,"%c%c", (char)aProp->GetCreationMode(),  (aProp->IsLocked())?'l':'u');
424
425   aLength = aNames.size();
426   int a = 2;
427   for(anIndex = 0; anIndex<aLength; anIndex++) {
428     sprintf(&(aProperty[a]),"%2d%2d%2d%2d%4d%s",
429             (int)(aMinutes[anIndex]),
430             (int)(aHours[anIndex]),
431             (int)(aDays[anIndex]),
432             (int)(aMonths[anIndex]),
433             (int)(aYears[anIndex]),
434             aNames[anIndex].c_str());
435     a = strlen(aProperty);
436     aProperty[a++] = 1;
437   }
438   aProperty[a] = 0;
439
440   name_len = (hdf_int32) a;
441   size[0] = name_len + 1 ;
442   hdf_dataset = new HDFdataset("AttributeStudyProperties",hdf_group,HDF_STRING,size,1);
443   hdf_dataset->CreateOnDisk();
444   hdf_dataset->WriteOnDisk(aProperty);
445   hdf_dataset->CloseOnDisk();
446   hdf_dataset=0; //will be deleted by hdf_sco_group destructor
447   delete [] aProperty;
448
449   aProp->SetModified(0);
450   return true;
451 }
452
453 //=============================================================================
454 /*! Function : _SaveAs
455  *  Purpose  : save the study in HDF file
456  */
457 //============================================================================
458 bool SALOMEDSImpl_StudyManager::Impl_SaveAs(const string& aStudyUrl,
459                                             SALOMEDSImpl_Study* aStudy,
460                                             SALOMEDSImpl_DriverFactory* aFactory,
461                                             bool theMultiFile,
462                                             bool theASCII)
463 {
464   // HDF File will be composed of differents part :
465   // * For each ComponentDataType, all data created by the component
466   //   Informations in data group hdf_group_datacomponent
467   // * Study Structure -> Exactly what is contained in Document
468   //   Informations in data group hdf_group_study_structure
469
470   _errorCode = "";
471
472   HDFfile *hdf_file=0;
473   HDFgroup *hdf_group_study_structure =0;
474   HDFgroup *hdf_sco_group =0;
475   HDFgroup *hdf_sco_group2 =0;
476   HDFgroup *hdf_notebook_vars =0; 
477   HDFgroup *hdf_notebook_var  = 0;
478
479   HDFgroup *hdf_group_datacomponent =0;
480   HDFdataset *hdf_dataset =0;
481   hdf_size size[1];
482   hdf_int32 name_len = 0;
483   string component_name;
484
485   if(!aStudy) {
486     _errorCode = "Study is null";
487     return false;
488   }
489
490   //Create a temporary url to which the study is saved 
491   string aUrl = SALOMEDSImpl_Tool::GetTmpDir() + SALOMEDSImpl_Tool::GetNameFromPath(aStudyUrl);
492
493   int aLocked = aStudy->GetProperties()->IsLocked();
494   if (aLocked) aStudy->GetProperties()->SetLocked(false);
495
496   SALOMEDSImpl_StudyBuilder* SB= aStudy->NewBuilder();
497   map<string, SALOMEDSImpl_Driver*> aMapTypeDriver;
498
499   try
500     {
501       // mpv 15.12.2003: for saving components we have to load all data from all modules
502       SALOMEDSImpl_SComponentIterator itcomponent1 = aStudy->NewComponentIterator();
503       for (; itcomponent1.More(); itcomponent1.Next())
504         {
505           SALOMEDSImpl_SComponent sco = itcomponent1.Value();
506           // if there is an associated Engine call its method for saving
507           string IOREngine;
508           try {
509             if (!sco.ComponentIOR(IOREngine)) {
510               string aCompType = sco.GetComment();
511               if (!aCompType.empty()) {
512
513                 SALOMEDSImpl_Driver* aDriver = aFactory->GetDriverByType(aCompType);
514                 aMapTypeDriver[aCompType] = aDriver;
515
516                 if (aDriver != NULL) {
517                   if(!SB->LoadWith(sco, aDriver)) {
518                     _errorCode = SB->GetErrorCode();
519                     return false;
520                   }
521                 }
522               }
523             }
524           } catch(...) {
525             _errorCode = "Can not restore information to resave it";
526             return false;
527           }
528         }
529
530       string anOldName = aStudy->Name();
531       aStudy->URL(aStudyUrl);
532
533       // To change for Save
534       // Do not have to do a new file but just a Open??? Rewrite all informations after erasing evrything??
535       hdf_file = new HDFfile((char*)aUrl.c_str());
536       hdf_file->CreateOnDisk();
537
538       //-----------------------------------------------------------------------
539       // 1 - Create a groupe for each SComponent and Update the PersistanceRef
540       //-----------------------------------------------------------------------
541       hdf_group_datacomponent = new HDFgroup("DATACOMPONENT",hdf_file);
542       hdf_group_datacomponent->CreateOnDisk();
543
544       SALOMEDSImpl_SComponentIterator itcomponent = aStudy->NewComponentIterator();
545
546       for (; itcomponent.More(); itcomponent.Next())
547         {
548           SALOMEDSImpl_SComponent sco = itcomponent.Value();
549
550           string scoid = sco.GetID();
551           hdf_sco_group = new HDFgroup((char*)scoid.c_str(), hdf_group_datacomponent);
552           hdf_sco_group->CreateOnDisk();
553
554           string componentDataType = sco.ComponentDataType();
555           string IOREngine;
556           if (sco.ComponentIOR(IOREngine))
557             {
558               SALOMEDSImpl_Driver* Engine = NULL;
559               if(aMapTypeDriver.find(componentDataType) != aMapTypeDriver.end()) {
560                 // we have found the associated engine to write the data
561                 Engine = aMapTypeDriver[componentDataType];
562               }
563               else {
564                 Engine = aFactory->GetDriverByIOR(IOREngine);
565               }
566
567               if (Engine != NULL)
568                 {
569                   SALOMEDSImpl_TMPFile* aStream = NULL;
570                   long length = 0;
571
572                   if (theASCII) aStream = Engine->SaveASCII(sco,
573                                                             SALOMEDSImpl_Tool::GetDirFromPath(aUrl),
574                                                             length,
575                                                             theMultiFile);
576                   else aStream = Engine->Save(sco,
577                                               SALOMEDSImpl_Tool::GetDirFromPath(aUrl),
578                                               length,
579                                               theMultiFile);
580                   HDFdataset *hdf_dataset;
581                   hdf_size aHDFSize[1]; 
582                   if(length > 0) {  //The component saved some auxiliary files, then put them into HDF file
583
584                     aHDFSize[0] = length;
585
586                     HDFdataset *hdf_dataset = new HDFdataset("FILE_STREAM", hdf_sco_group, HDF_STRING, aHDFSize, 1);
587                     hdf_dataset->CreateOnDisk();
588                     hdf_dataset->WriteOnDisk(aStream->Data());  //Save the stream in the HDF file
589                     hdf_dataset->CloseOnDisk();
590                   }
591
592                   if(aStream) delete aStream;
593
594                   // store multifile state
595                   aHDFSize[0] = 2;
596                   hdf_dataset = new HDFdataset("MULTIFILE_STATE", hdf_sco_group, HDF_STRING, aHDFSize, 1);
597                   hdf_dataset->CreateOnDisk();
598                   hdf_dataset->WriteOnDisk((void*)(theMultiFile?"M":"S")); // save: multi or single
599                   hdf_dataset->CloseOnDisk();
600                   hdf_dataset=0; //will be deleted by hdf_sco_AuxFiles destructor
601                   // store ASCII state
602                   aHDFSize[0] = 2;
603                   hdf_dataset = new HDFdataset("ASCII_STATE", hdf_sco_group, HDF_STRING, aHDFSize, 1);
604                   hdf_dataset->CreateOnDisk();
605                   hdf_dataset->WriteOnDisk((void*)(theASCII?"A":"B")); // save: ASCII or BINARY
606                   hdf_dataset->CloseOnDisk();
607                   hdf_dataset=0; //will be deleted by hdf_sco_AuxFiles destructor
608                   // Creation of the persistance reference  attribute
609                   Translate_IOR_to_persistentID (sco, Engine, theMultiFile, theASCII);
610                 }
611             }
612           hdf_sco_group->CloseOnDisk();
613           hdf_sco_group=0; // will be deleted by hdf_group_datacomponent destructor
614         }
615       hdf_group_datacomponent->CloseOnDisk();
616       hdf_group_datacomponent =0;  // will be deleted by hdf_file destructor
617
618       //-----------------------------------------------------------------------
619       //3 - Write the Study Structure
620       //-----------------------------------------------------------------------
621       hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
622       hdf_group_study_structure->CreateOnDisk();
623       // save component attributes
624       SALOMEDSImpl_SComponentIterator itcomp = aStudy->NewComponentIterator();
625       for (; itcomp.More(); itcomp.Next())
626         {
627           SALOMEDSImpl_SComponent SC = itcomp.Value();
628           string scid = SC.GetID();
629           hdf_sco_group2 = new HDFgroup((char*)scid.c_str(), hdf_group_study_structure);
630           hdf_sco_group2->CreateOnDisk();
631           SaveAttributes(SC, hdf_sco_group2);
632           // ComponentDataType treatment
633           component_name = SC.ComponentDataType();
634           name_len = (hdf_int32)component_name.length();
635           size[0] = name_len +1 ;
636           hdf_dataset = new HDFdataset("COMPONENTDATATYPE",hdf_sco_group2,HDF_STRING,size,1);
637           hdf_dataset->CreateOnDisk();
638           hdf_dataset->WriteOnDisk((char*)component_name.c_str());
639           hdf_dataset->CloseOnDisk();
640           hdf_dataset=0; //will be deleted by hdf_sco_group destructor
641           Impl_SaveObject(SC, hdf_sco_group2);
642           hdf_sco_group2->CloseOnDisk();
643           hdf_sco_group2=0; // will be deleted by hdf_group_study_structure destructor
644         }
645       //-----------------------------------------------------------------------
646       //4 - Write the Study UseCases Structure
647       //-----------------------------------------------------------------------
648       SALOMEDSImpl_SObject aSO = aStudy->FindObjectID(USE_CASE_LABEL_ID);
649       if (aSO) {
650         HDFgroup *hdf_soo_group = new HDFgroup(USE_CASE_LABEL_ID,hdf_group_study_structure);
651         hdf_soo_group->CreateOnDisk();
652         SaveAttributes(aSO, hdf_soo_group);
653         Impl_SaveObject(aSO, hdf_soo_group);
654         hdf_soo_group->CloseOnDisk();
655         hdf_soo_group=0; // will be deleted by hdf_group_study_structure destructor
656       }
657       //-----------------------------------------------------------------------
658       //5 - Write the NoteBook Variables
659       //-----------------------------------------------------------------------
660
661       //5.1 Create group to store all note book variables
662       hdf_notebook_vars = new HDFgroup("NOTEBOOK_VARIABLES",hdf_file);
663       hdf_notebook_vars->CreateOnDisk();
664       
665       string varValue;
666       string varType;
667       string varIndex;
668
669       for(int i=0 ;i < aStudy->myNoteBookVars.size(); i++ ){
670         // For each variable create HDF group
671         hdf_notebook_var = new HDFgroup((char*)aStudy->myNoteBookVars[i]->Name().c_str(),hdf_notebook_vars);
672         hdf_notebook_var->CreateOnDisk();
673
674         // Save Variable type
675         varType = aStudy->myNoteBookVars[i]->SaveType();
676         name_len = (hdf_int32) varType.length();
677         size[0] = name_len +1 ;
678         hdf_dataset = new HDFdataset("VARIABLE_TYPE",hdf_notebook_var,HDF_STRING,size,1);
679         hdf_dataset->CreateOnDisk();
680         hdf_dataset->WriteOnDisk((char*)varType.c_str());
681         hdf_dataset->CloseOnDisk();
682         hdf_dataset=0; //will be deleted by hdf_sco_group destructor
683         
684         char buffer[256];
685         sprintf(buffer,"%d",i);
686         varIndex= string(buffer);
687         name_len = (hdf_int32) varIndex.length();
688         size[0] = name_len +1 ;
689         hdf_dataset = new HDFdataset("VARIABLE_INDEX",hdf_notebook_var,HDF_STRING,size,1);
690         hdf_dataset->CreateOnDisk();
691         hdf_dataset->WriteOnDisk((char*)varIndex.c_str());
692         hdf_dataset->CloseOnDisk();
693         hdf_dataset=0; //will be deleted by hdf_sco_group destructor
694         
695         
696         // Save Variable value
697         varValue = aStudy->myNoteBookVars[i]->Save();
698         name_len = (hdf_int32) varValue.length();
699         size[0] = name_len +1 ;
700         hdf_dataset = new HDFdataset("VARIABLE_VALUE",hdf_notebook_var,HDF_STRING,size,1);
701         hdf_dataset->CreateOnDisk();
702         hdf_dataset->WriteOnDisk((char*)varValue.c_str());
703         hdf_dataset->CloseOnDisk();
704         hdf_dataset=0; //will be deleted by hdf_sco_group destructor
705         hdf_notebook_var->CloseOnDisk();
706         hdf_notebook_var = 0; //will be deleted by hdf_sco_group destructor
707       }
708       hdf_notebook_vars->CloseOnDisk();
709       hdf_notebook_vars = 0; //will be deleted by hdf_sco_group destructor
710         
711       if (aLocked) aStudy->GetProperties()->SetLocked(true);
712       //-----------------------------------------------------------------------
713       //6 - Write the Study Properties
714       //-----------------------------------------------------------------------
715       string study_name = aStudy->Name();
716       name_len = (hdf_int32) study_name.size();
717       size[0] = name_len +1 ;
718       hdf_dataset = new HDFdataset("STUDY_NAME",hdf_group_study_structure,HDF_STRING,size,1);
719       hdf_dataset->CreateOnDisk();
720       hdf_dataset->WriteOnDisk((char*)study_name.c_str());
721       hdf_dataset->CloseOnDisk();
722       hdf_dataset=0; // will be deleted by hdf_group_study_structure destructor
723
724       Impl_SaveProperties(aStudy, hdf_group_study_structure);
725       hdf_group_study_structure->CloseOnDisk();
726       hdf_file->CloseOnDisk();
727
728       aStudy->IsSaved(true);
729       hdf_group_study_structure =0; // will be deleted by hdf_file destructor
730       delete hdf_file; // recursively deletes all hdf objects...
731     }
732   catch (HDFexception)
733     {
734       _errorCode = "HDFexception ! ";
735       return false;
736     }
737   catch(std::exception& exc)
738     {
739       _errorCode = const_cast<char*>(exc.what());
740       return false;
741     }
742   catch(...)
743     {
744       _errorCode = "Unknown exception ! ";
745       return false;
746     }
747   if (theASCII) { // save file in ASCII format
748     HDFascii::ConvertFromHDFToASCII(aUrl.c_str(), true);
749   }
750   
751   //Now it's necessary to copy files from the temporary directory to the user defined directory.
752
753   //      The easiest way to get a list of file in the temporary directory
754
755   string aCmd, aTmpFileDir = SALOMEDSImpl_Tool::GetTmpDir();
756   string aTmpFile = aTmpFileDir +"files";
757   string aStudyTmpDir = SALOMEDSImpl_Tool::GetDirFromPath(aUrl);
758
759 #ifdef WIN32
760   aCmd = "dir /B \"" + aStudyTmpDir +"\" > " + aTmpFile;
761 #else
762   aCmd ="ls -1 \"" + aStudyTmpDir +"\" > " + aTmpFile;
763 #endif
764   system(aCmd.c_str());
765
766   //       Iterate and move files in the temporary directory
767   FILE* fp = fopen(aTmpFile.c_str(), "r");
768   if(!fp) return false;
769   char* buffer = new char[2047];
770   while(!feof(fp)) {
771     if((fgets(buffer, 2046, fp)) == NULL) break;
772     size_t aLen = strlen(buffer);
773     if(buffer[aLen-1] == '\n') buffer[aLen-1] = char(0);
774 #ifdef WIN32
775     aCmd = "move /Y \"" + aStudyTmpDir + string(buffer) + "\" \"" + SALOMEDSImpl_Tool::GetDirFromPath(aStudyUrl) +"\"";
776 #else 
777     aCmd = "mv -f \"" + aStudyTmpDir + string(buffer) + "\" \"" + SALOMEDSImpl_Tool::GetDirFromPath(aStudyUrl)+"\"";
778 #endif
779     system(aCmd.c_str());    
780   }
781
782   delete []buffer;
783   fclose(fp);
784
785   //       Perform cleanup
786 #ifdef WIN32
787   DeleteFileA(aTmpFile.c_str());
788 #else 
789   unlink(aTmpFile.c_str());
790 #endif
791
792 #ifdef WIN32
793   RemoveDirectoryA(aTmpFileDir.c_str());
794   RemoveDirectoryA(aStudyTmpDir.c_str());
795 #else
796   rmdir(aTmpFileDir.c_str());
797   rmdir(aStudyTmpDir.c_str());
798 #endif
799
800   return true;
801 }
802
803 //============================================================================
804 /*! Function : Impl_SaveObject
805  *  Purpose  :
806  */
807 //============================================================================
808 bool SALOMEDSImpl_StudyManager::Impl_SaveObject(const SALOMEDSImpl_SObject& SC,
809                                                 HDFgroup *hdf_group_datatype)
810 {
811   _errorCode = "";
812
813   // Write in group hdf_group_datatype all informations of SObject SC
814   // Iterative function to parse all SObjects under a SComponent
815
816   HDFgroup *hdf_group_sobject = 0;
817
818   DF_ChildIterator itchild(SC.GetLabel());
819   for (; itchild.More(); itchild.Next())
820     {
821
822       // mpv: don't save empty labels
823       vector<DF_Attribute*> attr = itchild.Value().GetAttributes();
824       if (attr.size() == 0) {  //No attributes on the label
825         DF_ChildIterator subchild(itchild.Value());
826         if (!subchild.More()) {
827           continue;
828         }
829         subchild.Init(itchild.Value(), true);
830         bool anEmpty = true;
831         for (; subchild.More() && anEmpty; subchild.Next()) {
832           vector<DF_Attribute*> attr2 = subchild.Value().GetAttributes();
833           if (attr2.size()) {
834             anEmpty = false;  //There are attributes on the child label
835             break;
836           }
837         }
838         if (anEmpty) continue;
839       }
840
841       SALOMEDSImpl_SObject SO = SALOMEDSImpl_Study::SObject(itchild.Value());
842
843       string scoid = SO.GetID();
844       hdf_group_sobject = new HDFgroup(scoid.c_str(), hdf_group_datatype);
845       hdf_group_sobject->CreateOnDisk();
846       SaveAttributes(SO, hdf_group_sobject);
847       Impl_SaveObject(SO, hdf_group_sobject);
848       hdf_group_sobject->CloseOnDisk();
849       hdf_group_sobject =0; // will be deleted by father hdf object destructor
850     }
851
852   return true;
853 }
854
855 //============================================================================
856 /*! Function : Impl_SubstituteSlash
857  *  Purpose  :
858  */
859 //============================================================================
860 string SALOMEDSImpl_StudyManager::Impl_SubstituteSlash(const string& aUrl)
861 {
862   _errorCode = "";
863
864   std::string theUrl(aUrl);
865   for(int i = 0; i<theUrl.size(); i++)
866     if(theUrl[i] == '/') theUrl[i] = ':';
867   return theUrl;
868 }
869
870 //============================================================================
871 /*! Function : GetDocumentOfStudy
872  *  Purpose  :
873  */
874 //============================================================================
875 DF_Document* SALOMEDSImpl_StudyManager::GetDocumentOfStudy(SALOMEDSImpl_Study* theStudy)
876 {
877   _errorCode = "";
878   return theStudy->_doc;
879 }
880
881 //============================================================================
882 /*! Function : CanCopy
883  *  Purpose  :
884  */
885 //============================================================================
886 bool SALOMEDSImpl_StudyManager::CanCopy(const SALOMEDSImpl_SObject& theObject,
887                                         SALOMEDSImpl_Driver* theEngine)
888 {
889   _errorCode = "";
890   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
891   if (!aComponent) return false;
892   if (aComponent.GetLabel() == theObject.GetLabel()) return false;
893   string IOREngine;
894   if (!aComponent.ComponentIOR(IOREngine)) return false;
895   if (theEngine == NULL) return false;
896   return theEngine->CanCopy(theObject);
897 }
898
899 //============================================================================
900 /*! Function : CopyLabel
901  *  Purpose  :
902  */
903 //============================================================================
904 bool SALOMEDSImpl_StudyManager::CopyLabel(SALOMEDSImpl_Study* theSourceStudy,
905                                           SALOMEDSImpl_Driver* theEngine,
906                                           const int theSourceStartDepth,
907                                           const DF_Label& theSource,
908                                           const DF_Label& theDestinationMain)
909 {
910   _errorCode = "";
911
912   int a;
913   DF_Label aTargetLabel = theDestinationMain;
914   DF_Label aAuxTargetLabel = theDestinationMain.Father().FindChild(2);
915   for(a = theSource.Depth() - theSourceStartDepth; a > 0 ; a--) {
916     DF_Label aSourceLabel = theSource;
917     for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
918     aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
919     aAuxTargetLabel = aAuxTargetLabel.FindChild(aSourceLabel.Tag());
920   }
921   // iterate attributes
922   vector<DF_Attribute*> attrList = theSource.GetAttributes();
923   for(int i = 0, len = attrList.size(); i<len; i++) {
924     DF_Attribute* anAttr = attrList[i];
925     string type = SALOMEDSImpl_GenericAttribute::Impl_GetType(anAttr);
926     if (type.substr(0, 17) == string("AttributeTreeNode")) continue; // never copy tree node attribute
927     if (type == string("AttributeTarget")) continue; // and target attribute
928
929     if (type == string("AttributeReference")) { // reference copied as Comment in aux tree
930       DF_Label aReferenced = dynamic_cast<SALOMEDSImpl_AttributeReference*>(anAttr)->Get();
931       string anEntry = aReferenced.Entry();
932       // store the value of name attribute of referenced label
933       SALOMEDSImpl_AttributeName* aNameAttribute;
934       if ((aNameAttribute=(SALOMEDSImpl_AttributeName*)aReferenced.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
935         anEntry += " ";
936         anEntry += aNameAttribute->Value();
937       }
938       SALOMEDSImpl_AttributeComment::Set(aAuxTargetLabel, anEntry);
939       continue;
940     }
941
942     if (type == string("AttributeIOR")) { // IOR => ID and TMPFile of Engine
943       string anEntry = theSource.Entry();
944       SALOMEDSImpl_SObject aSO = theSourceStudy->FindObjectID(anEntry);
945       int anObjID;
946       long aLen;
947       SALOMEDSImpl_TMPFile* aStream = theEngine->CopyFrom(aSO, anObjID, aLen);
948       string aResStr("");
949       for(a = 0; a < aLen; a++) {
950         aResStr += (char)(aStream->Get(a));
951       }
952
953       if(aStream) delete aStream;
954
955       SALOMEDSImpl_AttributeInteger::Set(aAuxTargetLabel, anObjID);
956       SALOMEDSImpl_AttributeName::Set(aAuxTargetLabel, aResStr);
957       continue;
958     }
959     DF_Attribute* aNewAttribute = anAttr->NewEmpty();
960     aTargetLabel.AddAttribute(aNewAttribute);
961     anAttr->Paste(aNewAttribute);
962   }
963
964   return true;
965 }
966
967 //============================================================================
968 /*! Function : Copy
969  *  Purpose  :
970  */
971 //============================================================================
972 bool SALOMEDSImpl_StudyManager::Copy(const SALOMEDSImpl_SObject& theObject,
973                                      SALOMEDSImpl_Driver* theEngine)
974 {
975   _errorCode = "";
976
977   // adoptation for alliances datamodel copy: without IOR attributes !!!
978   bool aStructureOnly; // copy only SObjects and attributes without component help
979   aStructureOnly = !theObject.GetLabel().IsAttribute(SALOMEDSImpl_AttributeIOR::GetID());
980
981   // get component-engine
982   SALOMEDSImpl_Study* aStudy = theObject.GetStudy();
983
984   // CAF document of current study usage
985   DF_Document* aDocument = GetDocumentOfStudy(aStudy);
986   if (!aDocument) {
987     _errorCode = "Document is null";
988     return false;
989   }
990
991   //Clear the clipboard
992   _clipboard->Main().Root().ForgetAllAttributes(true);
993   _appli->Close(_clipboard);
994   _clipboard = _appli->NewDocument("SALOME_STUDY");
995
996   // set component data type to the name attribute of root label
997   if (!aStructureOnly) {
998     SALOMEDSImpl_AttributeComment::Set(_clipboard->Main().Root(),
999                                        theEngine->ComponentDataType());
1000   }
1001   // set to the Root label integer attribute: study id
1002   SALOMEDSImpl_AttributeInteger::Set(_clipboard->Main().Root(), aStudy->StudyId());
1003   // iterate all theObject's label children
1004   DF_Label aStartLabel = theObject.GetLabel();
1005   int aSourceStartDepth = aStartLabel.Depth();
1006
1007   // copy main source label
1008   CopyLabel(aStudy, theEngine, aSourceStartDepth, aStartLabel, _clipboard->Main());
1009
1010   // copy all subchildren of the main source label (all levels)
1011   DF_ChildIterator anIterator(aStartLabel, true);
1012   for(; anIterator.More(); anIterator.Next()) {
1013     CopyLabel(aStudy, theEngine, aSourceStartDepth, anIterator.Value(), _clipboard->Main());
1014   }
1015
1016   return true;
1017 }
1018 //============================================================================
1019 /*! Function : CanPaste
1020  *  Purpose  :
1021  */
1022 //============================================================================
1023 bool SALOMEDSImpl_StudyManager::CanPaste(const SALOMEDSImpl_SObject& theObject,
1024                                          SALOMEDSImpl_Driver* theEngine)
1025 {
1026   _errorCode = "";
1027
1028   if (!_clipboard) {
1029     _errorCode = "Clipboard is null";
1030     return false;
1031   }
1032
1033   SALOMEDSImpl_AttributeComment* aCompName = NULL;
1034   if (!(aCompName=(SALOMEDSImpl_AttributeComment*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID()))) {
1035     _errorCode = "Clipboard has no component type";
1036     return false;
1037   }
1038   SALOMEDSImpl_AttributeInteger* anObjID;
1039   if (!(anObjID=(SALOMEDSImpl_AttributeInteger*)_clipboard->Main().Father().FindChild(2).FindAttribute(SALOMEDSImpl_AttributeInteger::GetID()))) {
1040     _errorCode = "Clipboard has no object id";
1041     return false;
1042   }
1043   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
1044   if (!aComponent) {
1045     _errorCode = "Object doesn't belong to component";
1046     return false;
1047   }
1048
1049   string IOREngine;
1050   if (!aComponent.ComponentIOR(IOREngine)) {
1051     _errorCode = "component has no IOR";
1052     return false;
1053   }
1054   return theEngine->CanPaste(aCompName->Value(), anObjID->Value());
1055 }
1056
1057 //============================================================================
1058 /*! Function : PasteLabel
1059  *  Purpose  :
1060  */
1061 //============================================================================
1062 DF_Label SALOMEDSImpl_StudyManager::PasteLabel(SALOMEDSImpl_Study* theDestinationStudy,
1063                                                SALOMEDSImpl_Driver* theEngine,
1064                                                const DF_Label& theSource,
1065                                                const DF_Label& theDestinationStart,
1066                                                const int theCopiedStudyID,
1067                                                const bool isFirstElement)
1068 {
1069   _errorCode = "";
1070
1071   // get corresponding source, target and auxiliary labels
1072   DF_Label aTargetLabel = theDestinationStart;
1073
1074   DF_Label aAuxSourceLabel = theSource.Root().FindChild(2);
1075   int a;
1076   if (!isFirstElement) {
1077     for(a = theSource.Depth() - 1; a > 0 ; a--) {
1078       DF_Label aSourceLabel = theSource;
1079       for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
1080       aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
1081       aAuxSourceLabel = aAuxSourceLabel.FindChild(aSourceLabel.Tag());
1082     }
1083   }
1084
1085   // check auxiliary label for TMPFile => IOR
1086   SALOMEDSImpl_AttributeName* aNameAttribute = NULL;
1087   if ((aNameAttribute=(SALOMEDSImpl_AttributeName*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
1088     SALOMEDSImpl_AttributeInteger* anObjID = (SALOMEDSImpl_AttributeInteger*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeInteger::GetID());
1089     SALOMEDSImpl_AttributeComment* aComponentName = (SALOMEDSImpl_AttributeComment*)theSource.Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID());
1090     string aCompName = aComponentName->Value();
1091
1092     if (theEngine->CanPaste(aCompName, anObjID->Value())) {
1093       std::string aTMPStr = aNameAttribute->Value();
1094       int aLen = aTMPStr.size();
1095       unsigned char* aStream = NULL;
1096       if(aLen > 0) {
1097         aStream = new unsigned char[aLen+10];
1098         for(a = 0; a < aLen; a++) {
1099           aStream[a] = aTMPStr[a];
1100         }
1101       }
1102
1103       string anEntry = aTargetLabel.Entry();
1104       SALOMEDSImpl_SObject aPastedSO = theDestinationStudy->FindObjectID(anEntry);
1105
1106       if (isFirstElement) {
1107         string aDestEntry = theEngine->PasteInto(aStream,
1108                                                  aLen,
1109                                                  anObjID->Value(),
1110                                                  aPastedSO.GetFatherComponent());
1111         aTargetLabel = DF_Label::Label(theDestinationStart, aDestEntry);
1112       } else
1113         theEngine->PasteInto(aStream, aLen, anObjID->Value(), aPastedSO);
1114
1115       if(aStream != NULL) delete []aStream;
1116     }
1117   }
1118
1119   // iterate attributes
1120   vector<DF_Attribute*> attrList = theSource.GetAttributes();
1121   for(int i = 0, len = attrList.size(); i<len; i++) {
1122     DF_Attribute* anAttr = attrList[i];
1123     if (aTargetLabel.FindAttribute(anAttr->ID())) {
1124       aTargetLabel.ForgetAttribute(anAttr->ID());
1125     }
1126     DF_Attribute* aNewAttribute = anAttr->NewEmpty();
1127     aTargetLabel.AddAttribute(aNewAttribute);
1128     anAttr->Paste(aNewAttribute);
1129   }
1130
1131   // check auxiliary label for Comment => reference or name attribute of the referenced object
1132   SALOMEDSImpl_AttributeComment* aCommentAttribute = NULL;
1133   if ((aCommentAttribute=(SALOMEDSImpl_AttributeComment*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeComment::GetID()))) {
1134     char * anEntry = new char[aCommentAttribute->Value().size() + 1];
1135     strcpy(anEntry, string(aCommentAttribute->Value()).c_str());
1136     char* aNameStart = strchr(anEntry, ' ');
1137     if (aNameStart) {
1138       *aNameStart = '\0';
1139       aNameStart++;
1140     }
1141     if (theCopiedStudyID == theDestinationStudy->StudyId()) { // if copy to the same study, reanimate reference
1142       DF_Label aRefLabel = DF_Label::Label(aTargetLabel, anEntry);
1143       SALOMEDSImpl_AttributeReference::Set(aTargetLabel, aRefLabel);
1144       // target attributes structure support
1145       SALOMEDSImpl_AttributeTarget::Set(aRefLabel)->Add(SALOMEDSImpl_Study::SObject(aTargetLabel));
1146     } else {
1147       if (aNameStart) SALOMEDSImpl_AttributeName::Set(aTargetLabel, aNameStart);
1148       else SALOMEDSImpl_AttributeName::Set(aTargetLabel, std::string("Reference to:")+anEntry);
1149     }
1150     delete [] anEntry;
1151   }
1152
1153   return aTargetLabel;
1154 }
1155
1156 //============================================================================
1157 /*! Function : Paste
1158  *  Purpose  :
1159  */
1160 //============================================================================
1161 SALOMEDSImpl_SObject SALOMEDSImpl_StudyManager::Paste(const SALOMEDSImpl_SObject& theObject,
1162                                                SALOMEDSImpl_Driver* theEngine)
1163 {
1164   _errorCode = "";
1165
1166   SALOMEDSImpl_SObject so;
1167   SALOMEDSImpl_Study* aStudy = theObject.GetStudy();
1168
1169   // if study is locked, then paste can't be done
1170   if (aStudy->GetProperties()->IsLocked()) {
1171     _errorCode = "LockProtection";
1172     throw LockProtection("LockProtection");
1173   }
1174
1175   // if there is no component name, then paste only SObjects and attributes: without component help
1176   SALOMEDSImpl_AttributeComment* aComponentName = NULL;
1177   bool aStructureOnly = !(aComponentName=(SALOMEDSImpl_AttributeComment*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID()));
1178
1179   // get copied study ID
1180   SALOMEDSImpl_AttributeInteger* aStudyIDAttribute = NULL;
1181   if (!(aStudyIDAttribute=(SALOMEDSImpl_AttributeInteger*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeInteger::GetID()))) {
1182     _errorCode = "No study ID was found";
1183     return so;
1184   }
1185   int aCStudyID = aStudyIDAttribute->Value();
1186
1187   // CAF document of current study usage
1188   DF_Document* aDocument = GetDocumentOfStudy(aStudy);
1189   if (!aDocument) {
1190     _errorCode = "Document is null";
1191     return so;
1192   }
1193
1194   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
1195
1196   // fill root inserted SObject
1197   DF_Label aStartLabel;
1198   if (aStructureOnly) {
1199     DF_Label anObjectLabel = DF_Label::Label(aDocument->Main(), theObject.GetID());
1200     aStartLabel = PasteLabel(aStudy, theEngine, _clipboard->Main(), anObjectLabel, aCStudyID, false);
1201   } else {
1202     DF_Label aComponentLabel = DF_Label::Label(aDocument->Main(), aComponent.GetID());
1203     aStartLabel = PasteLabel(aStudy, theEngine, _clipboard->Main(), aComponentLabel, aCStudyID, true);
1204   }
1205
1206   // paste all sublebels
1207   DF_ChildIterator anIterator(_clipboard->Main(), true);
1208   for(; anIterator.More(); anIterator.Next()) {
1209     PasteLabel(aStudy, theEngine, anIterator.Value(), aStartLabel, aCStudyID, false);
1210   }
1211
1212   return SALOMEDSImpl_Study::SObject(aStartLabel);
1213 }
1214
1215 //#######################################################################################################
1216 //#                                     STATIC PRIVATE FUNCTIONS
1217 //#######################################################################################################
1218
1219 //============================================================================
1220 /*! Function : SaveAttributes
1221  *  Purpose  : Save attributes for object
1222  */
1223 //============================================================================
1224 static void SaveAttributes(const SALOMEDSImpl_SObject& aSO, HDFgroup *hdf_group_sobject)
1225 {
1226   hdf_size size[1];
1227   vector<DF_Attribute*> attrList = aSO.GetLabel().GetAttributes();
1228   DF_Attribute* anAttr = NULL;
1229   for(int i = 0, len = attrList.size(); i<len; i++) {
1230     anAttr = attrList[i];
1231     //The following attributes are not supposed to be written to the file
1232     string type = SALOMEDSImpl_GenericAttribute::Impl_GetType(anAttr);
1233     if(type == string("AttributeIOR")) continue; //IOR attribute is not saved
1234     string aSaveStr =anAttr->Save();
1235     //cout << "Saving: " << aSO.GetID() << " type: "<< type<<"|" << endl;
1236     size[0] = (hdf_int32) strlen(aSaveStr.c_str()) + 1;
1237     HDFdataset *hdf_dataset = new HDFdataset((char*)type.c_str(), hdf_group_sobject, HDF_STRING,size, 1);
1238     hdf_dataset->CreateOnDisk();
1239     hdf_dataset->WriteOnDisk((char*)aSaveStr.c_str());
1240     hdf_dataset->CloseOnDisk();
1241     hdf_dataset=0; //will be deleted by hdf_sco_group destructor
1242   }
1243 }
1244
1245 //===========================================================================
1246 //Function : ReadAttributes
1247 //===========================================================================
1248 static void ReadAttributes(SALOMEDSImpl_Study* theStudy,
1249                            const SALOMEDSImpl_SObject& aSO,
1250                            HDFdataset* hdf_dataset)
1251 {
1252   hdf_dataset->OpenOnDisk();
1253
1254   DF_Attribute* anAttr = NULL;
1255   char* current_string = new char[hdf_dataset->GetSize()+1];
1256   hdf_dataset->ReadFromDisk(current_string);
1257   //cout << "Reading attr type = " << hdf_dataset->GetName() << "  SO = " << aSO.GetID() << endl;
1258   if (!strcmp(hdf_dataset->GetName(),"COMPONENTDATATYPE")) {
1259     anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, "AttributeComment");
1260   } else if (!strcmp(hdf_dataset->GetName(),"AttributeReference") ||
1261              !strcmp(hdf_dataset->GetName(),"Reference")) { // Old format maintainance
1262     theStudy->NewBuilder()->Addreference(aSO, theStudy->CreateObjectID(current_string));
1263     delete [] (current_string);
1264     hdf_dataset->CloseOnDisk();
1265     return;
1266   } else {
1267     anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, hdf_dataset->GetName());
1268   }
1269   
1270   if (anAttr) {
1271     anAttr->Load(current_string);
1272   }
1273   
1274   delete [] (current_string);
1275   hdf_dataset->CloseOnDisk();
1276 }
1277
1278 //============================================================================
1279 //Function : BuildlTree
1280 //============================================================================
1281 static void BuildTree (SALOMEDSImpl_Study* theStudy, HDFgroup* hdf_current_group)
1282 {
1283   hdf_current_group->OpenOnDisk();
1284   SALOMEDSImpl_SObject aSO;
1285   char* Entry = hdf_current_group->GetName();
1286   if (strcmp(Entry,"STUDY_STRUCTURE") == 0) {
1287     aSO = theStudy->CreateObjectID("0:1");
1288   }
1289   else {
1290     aSO = theStudy->CreateObjectID(Entry);
1291   }
1292
1293   char name[HDF_NAME_MAX_LEN+1];
1294   int nbsons = hdf_current_group->nInternalObjects();
1295   for (int i=0; i<nbsons; i++) {
1296     hdf_current_group->InternalObjectIndentify(i,name);
1297     if (strncmp(name, "INTERNAL_COMPLEX",16) == 0) continue;
1298     hdf_object_type type = hdf_current_group->InternalObjectType(name);
1299
1300     if  (type == HDF_DATASET) {
1301       HDFdataset* new_dataset = new HDFdataset(name,hdf_current_group);
1302       ReadAttributes(theStudy,aSO,new_dataset);
1303       new_dataset = 0; // will be deleted by father destructor
1304
1305     }
1306     else if (type == HDF_GROUP)   {
1307       HDFgroup* new_group = new HDFgroup(name,hdf_current_group);
1308       BuildTree (theStudy, new_group);
1309       new_group = 0; // will be deleted by father destructor
1310     }
1311   }
1312   hdf_current_group->CloseOnDisk();
1313 }
1314
1315
1316 //============================================================================
1317 //Function : Translate_IOR_to_persistentID
1318 //============================================================================
1319 static void Translate_IOR_to_persistentID (const SALOMEDSImpl_SObject& so,
1320                                            SALOMEDSImpl_Driver*                engine,
1321                                            bool                                isMultiFile,
1322                                            bool                                isASCII)
1323 {
1324   DF_ChildIterator itchild(so.GetLabel());
1325   string ior_string,  persistent_string, curid;
1326
1327   for (; itchild.More(); itchild.Next()) {
1328     SALOMEDSImpl_SObject current = SALOMEDSImpl_Study::SObject(itchild.Value());
1329     SALOMEDSImpl_AttributeIOR* IOR = NULL;
1330     if ((IOR=(SALOMEDSImpl_AttributeIOR*)current.GetLabel().FindAttribute(SALOMEDSImpl_AttributeIOR::GetID()))) {
1331       ior_string = IOR->Value();
1332
1333       persistent_string = engine->IORToLocalPersistentID (current, ior_string, isMultiFile, isASCII);
1334       SALOMEDSImpl_AttributePersistentRef::Set(current.GetLabel(), persistent_string);
1335     }
1336     Translate_IOR_to_persistentID (current, engine, isMultiFile, isASCII);
1337   }
1338 }
1339
1340 void ReadNoteBookVariables(SALOMEDSImpl_Study* theStudy, HDFgroup* theGroup)
1341 {
1342   if(!theGroup)
1343     return;
1344
1345   HDFgroup* new_group =0;
1346   HDFdataset* new_dataset =0;
1347   
1348   char aVarName[HDF_NAME_MAX_LEN+1];
1349   char *currentVarType = 0;
1350   char *currentVarValue = 0;
1351   char *currentVarIndex = 0;
1352   int order = 0;
1353   //Open HDF group with notebook variables
1354   theGroup->OpenOnDisk();
1355
1356   //Get Nb of variables
1357   int aNbVars = theGroup->nInternalObjects();
1358
1359   map<int,SALOMEDSImpl_GenericVariable*> aVarsMap;
1360
1361   for( int iVar=0;iVar < aNbVars;iVar++ ) {
1362     theGroup->InternalObjectIndentify(iVar,aVarName);
1363     hdf_object_type type = theGroup->InternalObjectType(aVarName);
1364     if(type == HDF_GROUP) {
1365
1366       //Read Variable
1367       new_group = new HDFgroup(aVarName,theGroup);
1368       new_group->OpenOnDisk();
1369
1370       //Read Type
1371       new_dataset = new HDFdataset("VARIABLE_TYPE",new_group);
1372       new_dataset->OpenOnDisk();
1373       currentVarType = new char[new_dataset->GetSize()+1];
1374       new_dataset->ReadFromDisk(currentVarType);
1375       new_dataset->CloseOnDisk();
1376       new_dataset = 0; //will be deleted by hdf_sco_group destructor
1377
1378       //Read Order
1379       if(new_group->ExistInternalObject("VARIABLE_INDEX")) {
1380         new_dataset = new HDFdataset("VARIABLE_INDEX",new_group);
1381         new_dataset->OpenOnDisk();
1382         currentVarIndex = new char[new_dataset->GetSize()+1];
1383         new_dataset->ReadFromDisk(currentVarIndex);
1384         new_dataset->CloseOnDisk();
1385         new_dataset = 0; //will be deleted by hdf_sco_group destructor
1386         order = atoi(currentVarIndex);
1387         delete [] currentVarIndex;
1388       }
1389       else
1390         order = iVar;
1391       
1392       //Read Value
1393       new_dataset = new HDFdataset("VARIABLE_VALUE",new_group);
1394       new_dataset->OpenOnDisk();
1395       currentVarValue = new char[new_dataset->GetSize()+1];
1396       new_dataset->ReadFromDisk(currentVarValue);
1397       new_dataset->CloseOnDisk();
1398       new_dataset = 0; //will be deleted by hdf_sco_group destructor
1399
1400       new_group->CloseOnDisk();
1401       new_group = 0;  //will be deleted by hdf_sco_group destructor
1402       
1403       SALOMEDSImpl_GenericVariable::VariableTypes aVarType =
1404         SALOMEDSImpl_GenericVariable::String2VariableType(string(currentVarType));
1405       delete [] currentVarType;
1406
1407       //Create variable and add it in the study
1408       SALOMEDSImpl_GenericVariable* aVariable = 
1409         new SALOMEDSImpl_ScalarVariable(aVarType,string(aVarName));
1410       aVariable->Load(string(currentVarValue));
1411       aVarsMap.insert(make_pair<int,SALOMEDSImpl_GenericVariable*>(order,aVariable));
1412       delete [] currentVarValue;
1413     }
1414   }
1415   
1416   map<int,SALOMEDSImpl_GenericVariable*>::const_iterator it= aVarsMap.begin();
1417   for(;it!=aVarsMap.end();it++)
1418     theStudy->AddVariable((*it).second);
1419   
1420   theGroup->CloseOnDisk();
1421 }