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