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