Salome HOME
Issue #16922 [CEA 16749] SALOME_MODULES_ORDER not set in SALOME 9.3.0 Windows archive
[modules/kernel.git] / src / SALOMEDSImpl / SALOMEDSImpl_Study.cxx
1 // Copyright (C) 2007-2019  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, or (at your option) any later version.
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
23 //  File   : SALOMEDSImpl_Study.cxx
24 //  Author : Sergey RUIN
25 //  Module : SALOME
26 //
27 #include "SALOMEDSImpl_Study.hxx"
28 #include <string.h>
29
30 #include <KERNEL_version.h>
31 #include <Basics_Utils.hxx>
32 #include <Basics_DirUtils.hxx>
33
34 #include "HDFexplorer.hxx"
35
36 #include "DF_Application.hxx"
37 #include "DF_ChildIterator.hxx"
38
39 #include "SALOMEDSImpl_ChildNodeIterator.hxx"
40 #include "SALOMEDSImpl_Attributes.hxx"
41 #include "SALOMEDSImpl_UseCaseIterator.hxx"
42 #include "SALOMEDSImpl_AttributeReference.hxx"
43 #include "SALOMEDSImpl_StudyHandle.hxx"
44 #include "SALOMEDSImpl_Tool.hxx"
45 #include "SALOMEDSImpl_IParameters.hxx"
46 #include "SALOMEDSImpl_ScalarVariable.hxx"
47 #include "SALOMEDSImpl_SComponent.hxx"
48
49 #include "HDFOI.hxx"
50 #include <fstream>
51 #include <sstream>
52 #include <algorithm>
53
54 // comment out the following define to enable \t symbols in in the python dump files
55 #define WITHOUT_TABS
56
57 #define DIRECTORYID       16661
58 #define FILELOCALID       26662
59 #define FILEID            "FILE: "
60 #define VARIABLE_SEPARATOR  ':'
61 #define OPERATION_SEPARATOR '|'
62 #define USE_CASE_LABEL_ID "0:2"
63
64 static void SaveAttributes(const SALOMEDSImpl_SObject& SO, HDFgroup *hdf_group_sobject);
65 static void ReadAttributes(SALOMEDSImpl_Study*, const SALOMEDSImpl_SObject&, HDFdataset* );
66 static void BuildTree (SALOMEDSImpl_Study*, HDFgroup*);
67 static void Translate_IOR_to_persistentID (const SALOMEDSImpl_SObject&,
68                                            SALOMEDSImpl_Driver*, bool isMultiFile, bool isASCII);
69 static void ReadNoteBookVariables(SALOMEDSImpl_Study* theStudy, HDFgroup* theGroup);
70
71 namespace {
72   class StudyUnlocker
73   {
74   public:
75     StudyUnlocker( SALOMEDSImpl_Study* study ): myStudy( study ), myLocked( false )
76     {
77       myPrevLocked = myStudy->GetProperties()->IsLocked();
78       resume();
79     }
80     ~StudyUnlocker()
81     {
82       suspend();
83     }
84     void suspend()
85     {
86       if (myLocked) {
87         myStudy->GetProperties()->SetLocked(true);
88         myPrevLocked = myLocked;
89         myLocked = false;
90       }
91     }
92     void resume()
93     {
94       if (myPrevLocked) {
95         myStudy->GetProperties()->SetLocked(false);
96         myLocked = myPrevLocked;
97         myPrevLocked = false;
98       }
99     }
100   private:
101     SALOMEDSImpl_Study* myStudy;
102     bool myLocked;
103     bool myPrevLocked;
104   };
105 }
106
107 //============================================================================
108 /*! Function : SALOMEDSImpl_Study
109  *  Purpose  : SALOMEDSImpl_Study constructor
110  */
111 //============================================================================
112 SALOMEDSImpl_Study::SALOMEDSImpl_Study() : _doc(NULL)
113 {
114   _appli = new DF_Application();
115   _clipboard = _appli->NewDocument("SALOME_STUDY");
116
117   Init();
118 }
119
120 //============================================================================
121 /*! Function : ~SALOMEDSImpl_Study
122  *  Purpose  : SALOMEDSImpl_Study destructor
123  */
124 //============================================================================
125 SALOMEDSImpl_Study::~SALOMEDSImpl_Study()
126 {
127   Clear();
128   _appli->Close(_clipboard);
129   // Destroy application
130   delete _appli;
131 }
132
133 //============================================================================
134 /*! Function : Init
135  *  Purpose  : Initialize study components
136  */
137 //============================================================================
138 void SALOMEDSImpl_Study::Init()
139 {
140   if (_doc)
141     return; // noop: already initialized
142
143   static int _id = 0;
144   std::stringstream sstrm;
145   sstrm << ++_id;
146   _name = "Study" + std::string(sstrm.str());
147   _doc = _appli->NewDocument("SALOME_STUDY");
148   _Saved = false;
149   _URL = "";
150   _autoFill = false;
151   _errorCode = "";
152   _useCaseBuilder = new SALOMEDSImpl_UseCaseBuilder(_doc);
153   _builder = new SALOMEDSImpl_StudyBuilder(this);
154   _cb = new SALOMEDSImpl_Callback(_useCaseBuilder);
155   _notifier=0;
156   _genObjRegister=0;
157   //Put on the root label a StudyHandle attribute to store the address of this object
158   //It will be used to retrieve the study object by DF_Label that belongs to the study
159   SALOMEDSImpl_StudyHandle::Set(_doc->Main().Root(), this);
160
161   // set Study properties
162   SALOMEDSImpl_AttributeStudyProperties* aProp = GetProperties();
163
164   int month=0,day=0,year=0,hh=0,mn=0,ss=0;
165   SALOMEDSImpl_Tool::GetSystemDate(year, month, day, hh, mn, ss);
166   aProp->SetModification(SALOMEDSImpl_Tool::GetUserName(),
167                          mn, hh, day, month, year);
168   aProp->SetCreationMode(1);  //"from scratch"
169 }
170
171 //============================================================================
172 /*! Function : Clear
173  *  Purpose  : Clear study components
174  */
175 //============================================================================
176 void SALOMEDSImpl_Study::Clear()
177 {
178   if (_builder) delete _builder;
179   _builder = NULL;
180   if (_cb) delete _cb;
181   _cb = NULL;
182   if (_useCaseBuilder) delete _useCaseBuilder;
183   _useCaseBuilder = NULL;
184   URL("");
185   _appli->Close(_doc);
186   _doc = NULL;
187   _mapOfSO.clear();
188   _mapOfSCO.clear();
189 }
190
191 //============================================================================
192 /*! Function : Open
193  *  Purpose  : Open a Study from it's persistent reference
194  */
195 //============================================================================
196 bool SALOMEDSImpl_Study::Open(const std::string& aUrl)
197 {
198   // Set "C" locale temporarily to avoid possible localization problems
199   Kernel_Utils::Localizer loc;
200
201   _errorCode = "";
202
203   // open the HDFFile
204   HDFfile *hdf_file =0;
205   HDFgroup *hdf_group_study_structure =0;
206   HDFgroup *hdf_notebook_vars = 0;
207
208   char* aC_HDFUrl;
209   std::string aHDFUrl;
210   bool isASCII = false;
211   if (HDFascii::isASCII(aUrl.c_str())) {
212     isASCII = true;
213     char* aResultPath = HDFascii::ConvertFromASCIIToHDF(aUrl.c_str());
214     if ( !aResultPath )
215       return NULL;
216     aC_HDFUrl = new char[strlen(aResultPath) + 19];
217     sprintf(aC_HDFUrl, "%shdf_from_ascii.hdf", aResultPath);
218     delete [] (aResultPath);
219     aHDFUrl = aC_HDFUrl;
220     delete [] aC_HDFUrl;
221   }
222   else {
223     aHDFUrl = aUrl;
224   }
225
226   hdf_file = new HDFfile((char*)aHDFUrl.c_str());
227   try {
228     hdf_file->OpenOnDisk(HDF_RDONLY);// mpv: was RDWR, but opened file can be write-protected too
229   }
230   catch (HDFexception)
231   {
232     char *eStr;
233     eStr = new char[strlen(aUrl.c_str())+17];
234     sprintf(eStr,"Can't open file %s",aUrl.c_str());
235     delete [] eStr;
236     _errorCode = std::string(eStr);
237     return NULL;
238   }
239
240   // Assign the value of the URL in the study object
241   URL(aUrl);
242
243   SALOMEDSImpl_AttributePersistentRef::Set(_doc->Main(), aUrl);
244
245   if (!hdf_file->ExistInternalObject("STUDY_STRUCTURE")) {
246      _errorCode = "Study is empty";
247     return false;
248   }
249
250   //Create  the Structure of the Document
251   hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
252
253   try {
254     BuildTree (this, hdf_group_study_structure);
255   }
256   catch (HDFexception)
257   {
258     char *eStr = new char [strlen(aUrl.c_str())+17];
259     sprintf(eStr,"Can't open file %s", aUrl.c_str());
260     _errorCode = std::string(eStr);
261     return false;
262   }
263
264   //Read and create notebook variables
265   if(hdf_file->ExistInternalObject("NOTEBOOK_VARIABLES")) {
266     hdf_notebook_vars  = new HDFgroup("NOTEBOOK_VARIABLES",hdf_file);
267     ReadNoteBookVariables(this, hdf_notebook_vars);
268     hdf_notebook_vars =0; //will be deleted by hdf_sco_group destructor
269   }
270
271   hdf_file->CloseOnDisk();
272   hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
273
274   if (isASCII) {
275     std::vector<std::string> aFilesToRemove;
276     aFilesToRemove.push_back("hdf_from_ascii.hdf");
277     SALOMEDSImpl_Tool::RemoveTemporaryFiles(SALOMEDSImpl_Tool::GetDirFromPath(aHDFUrl), aFilesToRemove, true);
278   }
279
280   delete hdf_file; // all related hdf objects will be deleted
281
282   // unlock study if it is locked, to set components versions
283   StudyUnlocker unlock(this);
284
285   //For old studies we have to add "unknown" version tag for all stored components
286   SALOMEDSImpl_SComponentIterator itcomponent = NewComponentIterator();
287   for (; itcomponent.More(); itcomponent.Next())
288   {
289     SALOMEDSImpl_SComponent sco = itcomponent.Value();
290     std::string aCompType = sco.GetComment();
291     if ( aCompType == SALOMEDSImpl_IParameters::getDefaultVisualComponent() ) continue;
292     if ( GetProperties()->GetComponentVersions( aCompType ).empty() )
293       GetProperties()->SetComponentVersion( aCompType, "" ); // empty version means "unknown"
294   }
295
296   return true;
297 }
298
299 //============================================================================
300 /*! Function : Save
301  *  Purpose  : Save a Study to it's persistent reference
302  */
303 //============================================================================
304 bool SALOMEDSImpl_Study::Save(SALOMEDSImpl_DriverFactory* aFactory,
305                               bool theMultiFile,
306                               bool theASCII)
307 {
308   _errorCode = "";
309
310   std::string url = URL();
311   if (url.empty()) {
312     _errorCode = "No path specified to save the study. Nothing done";
313     return false;
314   }
315   else {
316     return Impl_SaveAs(url, aFactory, theMultiFile, theASCII);
317   }
318
319   return false;
320 }
321
322 //=============================================================================
323 /*! Function : SaveAs
324  *  Purpose  : Save a study to the persistent reference aUrl
325  */
326 //============================================================================
327 bool SALOMEDSImpl_Study::SaveAs(const std::string& aUrl,
328                                 SALOMEDSImpl_DriverFactory* aFactory,
329                                 bool theMultiFile,
330                                 bool theASCII)
331 {
332   _errorCode = "";
333   return Impl_SaveAs(aUrl, aFactory, theMultiFile, theASCII);
334 }
335
336 //=============================================================================
337 /*! Function : _SaveProperties
338  *  Purpose  : save the study properties in HDF file
339  */
340 //============================================================================
341 bool SALOMEDSImpl_Study::Impl_SaveProperties(HDFgroup *hdf_group)
342 {
343   _errorCode = "";
344
345   HDFdataset *hdf_dataset = 0;
346   hdf_size size[1];
347   hdf_int32 name_len;
348
349   // add modifications list (user and date of save)
350   SALOMEDSImpl_AttributeStudyProperties* aProp = GetProperties();
351
352   // unlock study if it is locked, to set modification date
353   StudyUnlocker unlock(this);
354
355   int month=0,day=0,year=0,hh=0,mn=0,ss=0;
356   SALOMEDSImpl_Tool::GetSystemDate(year, month, day, hh, mn, ss);
357   aProp->SetModification(SALOMEDSImpl_Tool::GetUserName(),
358                          mn, hh, day, month, year);
359
360   // lock study back if it was locked initially, to write correct value of Locked flag
361   unlock.suspend();
362
363   std::vector<std::string> aNames;
364   std::vector<int> aMinutes, aHours, aDays, aMonths, aYears;
365
366   aProp->GetModifications(aNames, aMinutes, aHours, aDays, aMonths, aYears);
367
368   std::string units = aProp->GetUnits();
369   std::string comment = aProp->GetComment();
370
371   std::map< std::string, std::vector<std::string> > allVersions = aProp->GetComponentsVersions();
372   std::map<std::string, std::string> versions;
373
374   int aLength = 0, aLength1 = 0, anIndex, i, unitsSize = 0, commentSize = 0;
375
376   for(i=1; i<=aNames.size(); i++)
377     aLength += aNames[i-1].size() + 1;
378
379   std::map< std::string, std::vector<std::string> >::const_iterator it;
380   for (it = allVersions.begin(); it != allVersions.end(); ++it ) {
381     std::string vlist = "";
382     std::vector<std::string> vl = it->second;
383     std::vector<std::string>::const_iterator vlit;
384     for ( vlit = vl.begin(); vlit != vl.end(); ++vlit ) {
385       if ( vlist != "" ) vlist += ";";
386       vlist += *vlit;
387     }
388     versions[ it->first ] = vlist;
389     aLength1 += it->first.size() + vlist.size() + 2;
390   }
391
392   unitsSize = units.size();
393   commentSize = comment.size();
394
395   //string format:
396   //locked flag, modified flag,
397   //minutes, hours, day, months, year, user name, char(1),
398   //minutes, hours, day, months, year, user name, char(1),
399   //.....................................................,
400   //.....................................................,
401   //.....................................................,
402   //minutes, hours, day, months, year, user name, char(1), char(30) <- !!!! used to define end of section with modifications !!!!
403   //units, char(1), comment, char(30) <- !!!! used to define start of section with components' versions !!!!
404   //component=versions, char(1),
405   //component=versions, char(1),
406   //...........................,
407   //component=versions, char(1), char(0)
408
409   //string length: 1 byte = locked flag, 1 byte = modified flag, (12 + name length + 1) for each name and date, 1 byte (char(30) section delimiter)
410   // unit length + 1, comment length, "zero" byte
411
412   char* aProperty = new char[3 + aLength + 12 * aNames.size() + 1 + unitsSize + 1 + commentSize + 1 + aLength1 ];
413
414   sprintf(aProperty,"%c%c", (char)aProp->GetCreationMode(),  (aProp->IsLocked())?'l':'u');
415
416   aLength = aNames.size();
417   int a = 2;
418   for(anIndex = 0; anIndex<aLength; anIndex++) {
419     sprintf(&(aProperty[a]),"%2d%2d%2d%2d%4d%s",
420             (int)(aMinutes[anIndex]),
421             (int)(aHours[anIndex]),
422             (int)(aDays[anIndex]),
423             (int)(aMonths[anIndex]),
424             (int)(aYears[anIndex]),
425             aNames[anIndex].c_str());
426     a = strlen(aProperty);
427     aProperty[a++] = 1;
428   }
429
430   //Write delimiter of the section to define end of the modifications section
431   aProperty[a++] = 30;
432
433   //Write units if need
434   if(units.size() > 0) {
435     sprintf(&(aProperty[a]),"%s",units.c_str());
436     a = strlen(aProperty);
437   }
438
439   aProperty[a++] = 1;
440
441   //Write comments if need
442   if(comment.size() > 0) {
443     sprintf(&(aProperty[a]),"%s",comment.c_str());
444     a = strlen(aProperty);
445   }
446
447   aProperty[a++] = 30; //delimiter of the component versions
448
449   std::map<std::string, std::string>::const_iterator versionsIt;
450   for ( versionsIt = versions.begin(); versionsIt != versions.end(); ++versionsIt ) {
451     sprintf(&(aProperty[a]),"%s=%s",
452             (char*)(versionsIt->first.c_str()),
453             (char*)(versionsIt->second.c_str()));
454     a = a + versionsIt->first.size() + versionsIt->second.size() + 1;
455     aProperty[a++] = 1;
456   }
457
458   aProperty[a] = 0;
459
460   name_len = (hdf_int32) a;
461   size[0] = name_len + 1 ;
462   hdf_dataset = new HDFdataset("AttributeStudyProperties",hdf_group,HDF_STRING,size,1);
463   hdf_dataset->CreateOnDisk();
464   hdf_dataset->WriteOnDisk(aProperty);
465   hdf_dataset->CloseOnDisk();
466   hdf_dataset=0; //will be deleted by hdf_sco_group destructor
467   delete [] aProperty;
468
469   aProp->SetModified(0);
470   return true;
471 }
472
473 //=============================================================================
474 /*! Function : _SaveAs
475  *  Purpose  : save the study in HDF file
476  */
477 //============================================================================
478 bool SALOMEDSImpl_Study::Impl_SaveAs(const std::string& aStudyUrl,
479                                      SALOMEDSImpl_DriverFactory* aFactory,
480                                      bool theMultiFile,
481                                      bool theASCII)
482 {
483   // Set "C" locale temporarily to avoid possible localization problems
484   Kernel_Utils::Localizer loc;
485
486   // HDF File will be composed of different part :
487   // * For each ComponentDataType, all data created by the component
488   //   Information in data group hdf_group_datacomponent
489   // * Study Structure -> Exactly what is contained in Document
490   //   Information in data group hdf_group_study_structure
491
492   _errorCode = "";
493
494   HDFfile *hdf_file=0;
495   HDFgroup *hdf_group_study_structure =0;
496   HDFgroup *hdf_sco_group =0;
497   HDFgroup *hdf_sco_group2 =0;
498   HDFgroup *hdf_notebook_vars =0;
499   HDFgroup *hdf_notebook_var  = 0;
500
501   HDFgroup *hdf_group_datacomponent =0;
502   HDFdataset *hdf_dataset =0;
503   hdf_size size[1];
504   hdf_int32 name_len = 0;
505   std::string component_name;
506
507   // Store previous URL
508   std::string anOldName = URL();
509
510   // Map to store components' versions
511   std::map<std::string, std::string> componentVersions;
512
513   //Create a temporary url to which the study is saved
514   std::string aUrl = SALOMEDSImpl_Tool::GetTmpDir() + SALOMEDSImpl_Tool::GetNameFromPath(aStudyUrl);
515
516   // unlock study if it is locked, as some attributes need to be modified
517   StudyUnlocker unlock(this);
518
519   SALOMEDSImpl_StudyBuilder* SB= NewBuilder();
520   std::map<std::string, SALOMEDSImpl_Driver*> aMapTypeDriver;
521
522   try {
523     // mpv 15.12.2003: for saving components we have to load all data from all modules
524     SALOMEDSImpl_SComponentIterator itcomponent = NewComponentIterator();
525     for (; itcomponent.More(); itcomponent.Next()) {
526       SALOMEDSImpl_SComponent sco = itcomponent.Value();
527       // if there is an associated Engine call its method for saving
528       std::string IOREngine;
529       try {
530         SALOMEDSImpl_Driver* aDriver = NULL;
531         std::string aCompType = sco.GetComment();
532         if (!sco.ComponentIOR(IOREngine)) {
533           if (!aCompType.empty()) {
534             aDriver = aFactory->GetDriverByType(aCompType);
535             if (aDriver != NULL) {
536               if (!SB->LoadWith(sco, aDriver)) {
537                 _errorCode = SB->GetErrorCode();
538                 return false;
539               }
540             }
541           }
542         }
543         else {
544           aDriver = aFactory->GetDriverByIOR(IOREngine);
545         }
546         aMapTypeDriver[aCompType] = aDriver;
547       }
548       catch(...) {
549         _errorCode = "Can not restore information to resave it";
550         return false;
551       }
552     }
553
554     // VSR: set URL to new file name
555     // VSR: remember to set previous name if save operation fails
556     URL(aStudyUrl);
557
558     // To change for Save
559     // Do not have to do a new file but just a Open??? Rewrite all information after erasing everything??
560     hdf_file = new HDFfile((char*)aUrl.c_str());
561     hdf_file->CreateOnDisk();
562
563     //-----------------------------------------------------------------------
564     // 1 - Create a groupe for each SComponent and Update the PersistanceRef
565     //-----------------------------------------------------------------------
566     hdf_group_datacomponent = new HDFgroup("DATACOMPONENT",hdf_file);
567     hdf_group_datacomponent->CreateOnDisk();
568
569     for (itcomponent.Init(); itcomponent.More(); itcomponent.Next()) {
570       SALOMEDSImpl_SComponent sco = itcomponent.Value();
571
572       std::string scoid = sco.GetID();
573       hdf_sco_group = new HDFgroup((char*)scoid.c_str(), hdf_group_datacomponent);
574       hdf_sco_group->CreateOnDisk();
575
576       std::string componentDataType = sco.ComponentDataType();
577       std::string IOREngine;
578       if (sco.ComponentIOR(IOREngine)) {
579         // Engine should be already in the map as it was to added before
580         SALOMEDSImpl_Driver* Engine = aMapTypeDriver[componentDataType];
581         if (Engine != NULL) {
582           SALOMEDSImpl_TMPFile* aStream = NULL;
583           long length = 0;
584
585           componentVersions[ componentDataType ] = Engine->Version();
586
587           if (theASCII) aStream = Engine->SaveASCII(sco,
588                                                     SALOMEDSImpl_Tool::GetDirFromPath(aUrl),
589                                                     length,
590                                                     theMultiFile);
591           else aStream = Engine->Save(sco,
592                                       SALOMEDSImpl_Tool::GetDirFromPath(aUrl),
593                                       length,
594                                       theMultiFile);
595           HDFdataset *hdf_dataset;
596           hdf_size aHDFSize[1];
597           if (length > 0) {  //The component saved some auxiliary files, then put them into HDF file
598             aHDFSize[0] = length;
599
600             HDFdataset *hdf_dataset = new HDFdataset("FILE_STREAM", hdf_sco_group, HDF_STRING, aHDFSize, 1);
601             hdf_dataset->CreateOnDisk();
602             hdf_dataset->WriteOnDisk(aStream->Data());  //Save the stream in the HDF file
603             hdf_dataset->CloseOnDisk();
604           }
605
606           if (aStream) delete aStream;
607
608           // store multifile state
609           aHDFSize[0] = 2;
610           hdf_dataset = new HDFdataset("MULTIFILE_STATE", hdf_sco_group, HDF_STRING, aHDFSize, 1);
611           hdf_dataset->CreateOnDisk();
612           hdf_dataset->WriteOnDisk((void*)(theMultiFile?"M":"S")); // save: multi or single
613           hdf_dataset->CloseOnDisk();
614           hdf_dataset=0; //will be deleted by hdf_sco_AuxFiles destructor
615           // store ASCII state
616           aHDFSize[0] = 2;
617           hdf_dataset = new HDFdataset("ASCII_STATE", hdf_sco_group, HDF_STRING, aHDFSize, 1);
618           hdf_dataset->CreateOnDisk();
619           hdf_dataset->WriteOnDisk((void*)(theASCII?"A":"B")); // save: ASCII or BINARY
620           hdf_dataset->CloseOnDisk();
621           hdf_dataset=0; //will be deleted by hdf_sco_AuxFiles destructor
622           // Creation of the persistence reference  attribute
623           Translate_IOR_to_persistentID (sco, Engine, theMultiFile, theASCII);
624         }
625       }
626       hdf_sco_group->CloseOnDisk();
627       hdf_sco_group=0; // will be deleted by hdf_group_datacomponent destructor
628     }
629     hdf_group_datacomponent->CloseOnDisk();
630     hdf_group_datacomponent =0;  // will be deleted by hdf_file destructor
631
632     //-----------------------------------------------------------------------
633     //3 - Write the Study Structure
634     //-----------------------------------------------------------------------
635     hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
636     hdf_group_study_structure->CreateOnDisk();
637     // save component attributes
638     for (itcomponent.Init(); itcomponent.More(); itcomponent.Next()) {
639       SALOMEDSImpl_SComponent SC = itcomponent.Value();
640       std::string scid = SC.GetID();
641       hdf_sco_group2 = new HDFgroup((char*)scid.c_str(), hdf_group_study_structure);
642       hdf_sco_group2->CreateOnDisk();
643       SaveAttributes(SC, hdf_sco_group2);
644       // ComponentDataType treatment
645       component_name = SC.ComponentDataType();
646       name_len = (hdf_int32)component_name.length();
647       size[0] = name_len +1 ;
648       hdf_dataset = new HDFdataset("COMPONENTDATATYPE",hdf_sco_group2,HDF_STRING,size,1);
649       hdf_dataset->CreateOnDisk();
650       hdf_dataset->WriteOnDisk((char*)component_name.c_str());
651       hdf_dataset->CloseOnDisk();
652       hdf_dataset=0; //will be deleted by hdf_sco_group destructor
653       Impl_SaveObject(SC, hdf_sco_group2);
654       hdf_sco_group2->CloseOnDisk();
655       hdf_sco_group2=0; // will be deleted by hdf_group_study_structure destructor
656     }
657     //-----------------------------------------------------------------------
658     //4 - Write the Study UseCases Structure
659     //-----------------------------------------------------------------------
660     SALOMEDSImpl_SObject aSO = FindObjectID(USE_CASE_LABEL_ID);
661     if (aSO) {
662       HDFgroup *hdf_soo_group = new HDFgroup(USE_CASE_LABEL_ID,hdf_group_study_structure);
663       hdf_soo_group->CreateOnDisk();
664       SaveAttributes(aSO, hdf_soo_group);
665       Impl_SaveObject(aSO, hdf_soo_group);
666       hdf_soo_group->CloseOnDisk();
667       hdf_soo_group=0; // will be deleted by hdf_group_study_structure destructor
668     }
669     //-----------------------------------------------------------------------
670     //5 - Write the NoteBook Variables
671     //-----------------------------------------------------------------------
672
673     //5.1 Create group to store all note book variables
674     hdf_notebook_vars = new HDFgroup("NOTEBOOK_VARIABLES",hdf_file);
675     hdf_notebook_vars->CreateOnDisk();
676
677     std::string varValue;
678     std::string varType;
679     std::string varIndex;
680
681     for (int i=0 ;i < myNoteBookVars.size(); i++ ) {
682       // For each variable create HDF group
683       hdf_notebook_var = new HDFgroup((char*)myNoteBookVars[i]->Name().c_str(),hdf_notebook_vars);
684       hdf_notebook_var->CreateOnDisk();
685
686       // Save Variable type
687       varType = myNoteBookVars[i]->SaveType();
688       name_len = (hdf_int32) varType.length();
689       size[0] = name_len +1 ;
690       hdf_dataset = new HDFdataset("VARIABLE_TYPE",hdf_notebook_var,HDF_STRING,size,1);
691       hdf_dataset->CreateOnDisk();
692       hdf_dataset->WriteOnDisk((char*)varType.c_str());
693       hdf_dataset->CloseOnDisk();
694       hdf_dataset=0; //will be deleted by hdf_sco_group destructor
695
696       char buffer[256];
697       sprintf(buffer,"%d",i);
698       varIndex= std::string(buffer);
699       name_len = (hdf_int32) varIndex.length();
700       size[0] = name_len +1 ;
701       hdf_dataset = new HDFdataset("VARIABLE_INDEX",hdf_notebook_var,HDF_STRING,size,1);
702       hdf_dataset->CreateOnDisk();
703       hdf_dataset->WriteOnDisk((char*)varIndex.c_str());
704       hdf_dataset->CloseOnDisk();
705       hdf_dataset=0; //will be deleted by hdf_sco_group destructor
706
707       // Save Variable value
708       varValue = myNoteBookVars[i]->Save();
709       name_len = (hdf_int32) varValue.length();
710       size[0] = name_len +1 ;
711       hdf_dataset = new HDFdataset("VARIABLE_VALUE",hdf_notebook_var,HDF_STRING,size,1);
712       hdf_dataset->CreateOnDisk();
713       hdf_dataset->WriteOnDisk((char*)varValue.c_str());
714       hdf_dataset->CloseOnDisk();
715       hdf_dataset=0; //will be deleted by hdf_sco_group destructor
716       hdf_notebook_var->CloseOnDisk();
717       hdf_notebook_var = 0; //will be deleted by hdf_sco_group destructor
718     }
719     hdf_notebook_vars->CloseOnDisk();
720     hdf_notebook_vars = 0; //will be deleted by hdf_sco_group destructor
721
722     // record component versions
723     std::map<std::string, std::string>::const_iterator itVersions;
724     for ( itVersions = componentVersions.begin(); itVersions != componentVersions.end(); ++itVersions )
725       GetProperties()->SetComponentVersion( itVersions->first, itVersions->second );
726
727     // lock study back if it was locked initially, to write correct value of Locked flag
728     unlock.suspend();
729
730     //-----------------------------------------------------------------------
731     //6 - Write the Study Properties
732     //-----------------------------------------------------------------------
733     std::string study_name = Name();
734     name_len = (hdf_int32) study_name.size();
735     size[0] = name_len +1 ;
736     hdf_dataset = new HDFdataset("STUDY_NAME",hdf_group_study_structure,HDF_STRING,size,1);
737     hdf_dataset->CreateOnDisk();
738     hdf_dataset->WriteOnDisk((char*)study_name.c_str());
739     hdf_dataset->CloseOnDisk();
740     hdf_dataset=0; // will be deleted by hdf_group_study_structure destructor
741
742     Impl_SaveProperties(hdf_group_study_structure);
743     hdf_group_study_structure->CloseOnDisk();
744     hdf_file->CloseOnDisk();
745
746     hdf_group_study_structure =0; // will be deleted by hdf_file destructor
747     delete hdf_file; // recursively deletes all hdf objects...
748   }
749   catch (HDFexception) {
750     _errorCode = "HDFexception ! ";
751     URL( anOldName ); // VSR: restore previous url if operation is failed
752     return false;
753   }
754   catch (std::exception& exc) {
755     _errorCode = const_cast<char*>(exc.what());
756     URL( anOldName ); // VSR: restore previous url if operation is failed
757     return false;
758   }
759   catch (...) {
760     _errorCode = "Unknown exception ! ";
761     URL( anOldName ); // VSR: restore previous url if operation is failed
762     return false;
763   }
764   if (theASCII) { // save file in ASCII format
765     HDFascii::ConvertFromHDFToASCII(aUrl.c_str(), true);
766   }
767
768   // Now it's necessary to copy files from the temporary directory to the user defined directory.
769   // The easiest way to get a list of file in the temporary directory
770
771   std::string aCmd, aTmpFileDir = SALOMEDSImpl_Tool::GetTmpDir();
772   std::string aTmpFile = aTmpFileDir +"files";
773   std::string aStudyTmpDir = SALOMEDSImpl_Tool::GetDirFromPath(aUrl);
774
775 #ifdef WIN32
776   aCmd = "dir /B \"" + aStudyTmpDir +"\" > \"" + aTmpFile + "\"";
777 #else
778   aCmd ="ls -1 \"" + aStudyTmpDir +"\" > " + aTmpFile;
779 #endif
780 #if defined(WIN32) && defined(UNICODE)
781   std::wstring awCmd = Kernel_Utils::utf8_decode_s(aCmd);
782   _wsystem( awCmd.c_str() );
783 #else  
784   system(aCmd.c_str());
785 #endif
786
787   // Iterate and move files in the temporary directory
788 #if defined(WIN32) && defined(UNICODE)
789   std::wstring awTmpFile = Kernel_Utils::utf8_decode_s(aTmpFile);
790   FILE* fp = _wfopen(awTmpFile.c_str(), L"rb");
791 #else
792   FILE* fp = fopen(aTmpFile.c_str(), "rb");
793 #endif
794   if (!fp) {
795     URL( anOldName ); // VSR: restore previous url if operation is failed
796     return false;
797   }
798   char* buffer = new char[2047];
799   int errors = 0;
800   while (!feof(fp) && !errors) {
801     if ((fgets(buffer, 2046, fp)) == NULL) break;
802     size_t aLen = strlen(buffer);
803     if (buffer[aLen-1] == '\n') buffer[aLen-1] = char(0);
804 #ifdef WIN32
805     aCmd = "move /Y \"" + aStudyTmpDir + std::string(buffer) + "\" \"" + SALOMEDSImpl_Tool::GetDirFromPath(aStudyUrl) +"\" 2>NUL";
806 #else
807     aCmd = "mv -f \"" + aStudyTmpDir + std::string(buffer) + "\" \"" + SALOMEDSImpl_Tool::GetDirFromPath(aStudyUrl)+"\"";
808 #endif
809 #if defined(WIN32) && defined(UNICODE)
810         std::wstring awCmd = Kernel_Utils::utf8_decode_s(aCmd);
811     errors = _wsystem(awCmd.c_str());
812 #else  
813     errors = system(aCmd.c_str());
814 #endif
815   }
816
817   delete []buffer;
818   fclose(fp);
819
820   // Perform cleanup
821 #ifdef WIN32
822 #ifdef UNICODE
823   std::wstring aTmpFileToDelete = Kernel_Utils::utf8_decode_s(aTmpFile);
824  
825 #else
826   std::string aTmpFileToDelete = aTmpFile;
827 #endif
828   DeleteFile(aTmpFileToDelete.c_str());
829 #else
830   unlink(aTmpFile.c_str());
831 #endif
832
833 #ifdef WIN32
834 #ifdef UNICODE
835   std::wstring aTmpFileDirToDelete = Kernel_Utils::utf8_decode_s( aTmpFileDir );
836   std::wstring aStudyTmpDirToDelete = Kernel_Utils::utf8_decode_s( aStudyTmpDir );
837 #else
838   std::string aTmpFileDirToDelete = aTmpFileDir;
839   std::string aStudyTmpDirToDelete = aStudyTmpDir;
840 #endif  
841   RemoveDirectory( aTmpFileDirToDelete.c_str() );
842   RemoveDirectory( aStudyTmpDirToDelete.c_str() );
843 #else
844   rmdir(aTmpFileDir.c_str());
845   rmdir(aStudyTmpDir.c_str());
846 #endif
847
848   if ( !errors ) {
849     // VSR: finally, if all is done without errors, mark study as Saved
850     IsSaved(true);
851   }
852
853   std::map<std::string, SALOMEDSImpl_Driver*>::iterator n2dr = aMapTypeDriver.begin();
854   for ( ; n2dr != aMapTypeDriver.end(); ++n2dr )
855     delete n2dr->second;
856
857   return !errors;
858 }
859
860 //============================================================================
861 /*! Function : Impl_SaveObject
862  *  Purpose  :
863  */
864 //============================================================================
865 bool SALOMEDSImpl_Study::Impl_SaveObject(const SALOMEDSImpl_SObject& SC,
866                                          HDFgroup *hdf_group_datatype)
867 {
868   _errorCode = "";
869
870   // Write in group hdf_group_datatype all information of SObject SC
871   // Iterative function to parse all SObjects under a SComponent
872
873   HDFgroup *hdf_group_sobject = 0;
874
875   DF_ChildIterator itchild(SC.GetLabel());
876   for (; itchild.More(); itchild.Next()) {
877     // mpv: don't save empty labels
878     std::vector<DF_Attribute*> attr = itchild.Value().GetAttributes();
879     if (attr.size() == 0) {  //No attributes on the label
880       DF_ChildIterator subchild(itchild.Value());
881       if (!subchild.More()) {
882         continue;
883       }
884       subchild.Init(itchild.Value(), true);
885       bool anEmpty = true;
886       for (; subchild.More() && anEmpty; subchild.Next()) {
887         std::vector<DF_Attribute*> attr2 = subchild.Value().GetAttributes();
888         if (attr2.size()) {
889           anEmpty = false;  //There are attributes on the child label
890           break;
891         }
892       }
893       if (anEmpty) continue;
894     }
895
896     SALOMEDSImpl_SObject SO = SALOMEDSImpl_Study::SObject(itchild.Value());
897
898     std::string scoid = SO.GetID();
899     hdf_group_sobject = new HDFgroup(scoid.c_str(), hdf_group_datatype);
900     hdf_group_sobject->CreateOnDisk();
901     SaveAttributes(SO, hdf_group_sobject);
902     Impl_SaveObject(SO, hdf_group_sobject);
903     hdf_group_sobject->CloseOnDisk();
904     hdf_group_sobject =0; // will be deleted by father hdf object destructor
905   }
906   return true;
907 }
908
909 //============================================================================
910 /*! Function : CanCopy
911  *  Purpose  :
912  */
913 //============================================================================
914 bool SALOMEDSImpl_Study::CanCopy(const SALOMEDSImpl_SObject& theObject,
915                                  SALOMEDSImpl_Driver* theEngine)
916 {
917   _errorCode = "";
918   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
919   if (!aComponent) return false;
920   if (aComponent.GetLabel() == theObject.GetLabel()) return false;
921   std::string IOREngine;
922   if (!aComponent.ComponentIOR(IOREngine)) return false;
923   if (theEngine == NULL) return false;
924   return theEngine->CanCopy(theObject);
925 }
926
927 //============================================================================
928 /*! Function : CopyLabel
929  *  Purpose  :
930  */
931 //============================================================================
932 bool SALOMEDSImpl_Study::CopyLabel(SALOMEDSImpl_Driver* theEngine,
933                                    const int theSourceStartDepth,
934                                    const DF_Label& theSource,
935                                    const DF_Label& theDestinationMain)
936 {
937   _errorCode = "";
938
939   int a;
940   DF_Label aTargetLabel = theDestinationMain;
941   DF_Label aAuxTargetLabel = theDestinationMain.Father().FindChild(2);
942   for(a = theSource.Depth() - theSourceStartDepth; a > 0 ; a--) {
943     DF_Label aSourceLabel = theSource;
944     for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
945     aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
946     aAuxTargetLabel = aAuxTargetLabel.FindChild(aSourceLabel.Tag());
947   }
948   // iterate attributes
949   std::vector<DF_Attribute*> attrList = theSource.GetAttributes();
950   for(int i = 0, len = attrList.size(); i<len; i++) {
951     DF_Attribute* anAttr = attrList[i];
952     std::string type = SALOMEDSImpl_GenericAttribute::Impl_GetType(anAttr);
953     if (type.substr(0, 17) == std::string("AttributeTreeNode")) continue; // never copy tree node attribute
954     if (type == std::string("AttributeTarget")) continue; // and target attribute
955
956     if (type == std::string("AttributeReference")) { // reference copied as Comment in aux tree
957       DF_Label aReferenced = dynamic_cast<SALOMEDSImpl_AttributeReference*>(anAttr)->Get();
958       std::string anEntry = aReferenced.Entry();
959       // store the value of name attribute of referenced label
960       SALOMEDSImpl_AttributeName* aNameAttribute;
961       if ((aNameAttribute=(SALOMEDSImpl_AttributeName*)aReferenced.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
962         anEntry += " ";
963         anEntry += aNameAttribute->Value();
964       }
965       SALOMEDSImpl_AttributeComment::Set(aAuxTargetLabel, anEntry);
966       continue;
967     }
968
969     if (type == std::string("AttributeIOR")) { // IOR => ID and TMPFile of Engine
970       std::string anEntry = theSource.Entry();
971       SALOMEDSImpl_SObject aSO = FindObjectID(anEntry);
972       int anObjID;
973       long aLen;
974       SALOMEDSImpl_TMPFile* aStream = theEngine->CopyFrom(aSO, anObjID, aLen);
975       std::string aResStr("");
976       for(a = 0; a < aLen; a++) {
977         aResStr += (char)(aStream->Get(a));
978       }
979
980       if(aStream) delete aStream;
981
982       SALOMEDSImpl_AttributeInteger::Set(aAuxTargetLabel, anObjID);
983       SALOMEDSImpl_AttributeName::Set(aAuxTargetLabel, aResStr);
984       continue;
985     }
986     DF_Attribute* aNewAttribute = anAttr->NewEmpty();
987     aTargetLabel.AddAttribute(aNewAttribute);
988     anAttr->Paste(aNewAttribute);
989   }
990
991   return true;
992 }
993
994 //============================================================================
995 /*! Function : Copy
996  *  Purpose  :
997  */
998 //============================================================================
999 bool SALOMEDSImpl_Study::Copy(const SALOMEDSImpl_SObject& theObject,
1000                                     SALOMEDSImpl_Driver* theEngine)
1001 {
1002   _errorCode = "";
1003
1004   // adoptation for alliances datamodel copy: without IOR attributes !!!
1005   bool aStructureOnly; // copy only SObjects and attributes without component help
1006   aStructureOnly = !theObject.GetLabel().IsAttribute(SALOMEDSImpl_AttributeIOR::GetID());
1007
1008   if (!_doc) {
1009     _errorCode = "Document is null";
1010     return false;
1011   }
1012
1013   //Clear the clipboard
1014   _clipboard->Main().Root().ForgetAllAttributes(true);
1015   _appli->Close(_clipboard);
1016   _clipboard = _appli->NewDocument("SALOME_STUDY");
1017
1018   // set component data type to the name attribute of root label
1019   if (!aStructureOnly) {
1020     SALOMEDSImpl_AttributeComment::Set(_clipboard->Main().Root(),
1021                                        theEngine->ComponentDataType());
1022   }
1023   // iterate all theObject's label children
1024   DF_Label aStartLabel = theObject.GetLabel();
1025   int aSourceStartDepth = aStartLabel.Depth();
1026
1027   // copy main source label
1028   CopyLabel(theEngine, aSourceStartDepth, aStartLabel, _clipboard->Main());
1029
1030   // copy all subchildren of the main source label (all levels)
1031   DF_ChildIterator anIterator(aStartLabel, true);
1032   for(; anIterator.More(); anIterator.Next()) {
1033     CopyLabel(theEngine, aSourceStartDepth, anIterator.Value(), _clipboard->Main());
1034   }
1035
1036   return true;
1037 }
1038
1039 //============================================================================
1040 /*! Function : CanPaste
1041  *  Purpose  :
1042  */
1043 //============================================================================
1044 bool SALOMEDSImpl_Study::CanPaste(const SALOMEDSImpl_SObject& theObject,
1045                                          SALOMEDSImpl_Driver* theEngine)
1046 {
1047   _errorCode = "";
1048
1049   if (!_clipboard) {
1050     _errorCode = "Clipboard is null";
1051     return false;
1052   }
1053
1054   SALOMEDSImpl_AttributeComment* aCompName = NULL;
1055   if (!(aCompName=(SALOMEDSImpl_AttributeComment*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID()))) {
1056     _errorCode = "Clipboard has no component type";
1057     return false;
1058   }
1059   SALOMEDSImpl_AttributeInteger* anObjID;
1060   if (!(anObjID=(SALOMEDSImpl_AttributeInteger*)_clipboard->Main().Father().FindChild(2).FindAttribute(SALOMEDSImpl_AttributeInteger::GetID()))) {
1061     _errorCode = "Clipboard has no object id";
1062     return false;
1063   }
1064   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
1065   if (!aComponent) {
1066     _errorCode = "Object doesn't belong to component";
1067     return false;
1068   }
1069
1070   std::string IOREngine;
1071   if (!aComponent.ComponentIOR(IOREngine)) {
1072     _errorCode = "component has no IOR";
1073     return false;
1074   }
1075   return theEngine->CanPaste(aCompName->Value(), anObjID->Value());
1076 }
1077
1078 //============================================================================
1079 /*! Function : PasteLabel
1080  *  Purpose  :
1081  */
1082 //============================================================================
1083 DF_Label SALOMEDSImpl_Study::PasteLabel(SALOMEDSImpl_Driver* theEngine,
1084                                         const DF_Label& theSource,
1085                                         const DF_Label& theDestinationStart,
1086                                         const bool isFirstElement)
1087 {
1088   _errorCode = "";
1089
1090   // get corresponding source, target and auxiliary labels
1091   DF_Label aTargetLabel = theDestinationStart;
1092
1093   DF_Label aAuxSourceLabel = theSource.Root().FindChild(2);
1094   int a;
1095   if (!isFirstElement) {
1096     for(a = theSource.Depth() - 1; a > 0 ; a--) {
1097       DF_Label aSourceLabel = theSource;
1098       for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
1099       aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
1100       aAuxSourceLabel = aAuxSourceLabel.FindChild(aSourceLabel.Tag());
1101     }
1102     SALOMEDSImpl_SObject so = GetSObject(aTargetLabel);
1103     addSO_Notification(so);
1104   }
1105
1106   // check auxiliary label for TMPFile => IOR
1107   SALOMEDSImpl_AttributeName* aNameAttribute = NULL;
1108   if ((aNameAttribute=(SALOMEDSImpl_AttributeName*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
1109     SALOMEDSImpl_AttributeInteger* anObjID = (SALOMEDSImpl_AttributeInteger*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeInteger::GetID());
1110     SALOMEDSImpl_AttributeComment* aComponentName = (SALOMEDSImpl_AttributeComment*)theSource.Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID());
1111     std::string aCompName = aComponentName->Value();
1112
1113     if (theEngine->CanPaste(aCompName, anObjID->Value())) {
1114       std::string aTMPStr = aNameAttribute->Value();
1115       int aLen = aTMPStr.size();
1116       unsigned char* aStream = NULL;
1117       if(aLen > 0) {
1118         aStream = new unsigned char[aLen+10];
1119         for(a = 0; a < aLen; a++) {
1120           aStream[a] = aTMPStr[a];
1121         }
1122       }
1123
1124       std::string anEntry = aTargetLabel.Entry();
1125       SALOMEDSImpl_SObject aPastedSO = FindObjectID(anEntry);
1126
1127       if (isFirstElement) {
1128         std::string aDestEntry = theEngine->PasteInto(aStream,
1129                                                       aLen,
1130                                                       anObjID->Value(),
1131                                                       aPastedSO.GetFatherComponent());
1132         aTargetLabel = DF_Label::Label(theDestinationStart, aDestEntry);
1133       } else
1134         theEngine->PasteInto(aStream, aLen, anObjID->Value(), aPastedSO);
1135
1136       if(aStream != NULL) delete []aStream;
1137     }
1138   }
1139
1140   // iterate attributes
1141   std::vector<DF_Attribute*> attrList = theSource.GetAttributes();
1142   for(int i = 0, len = attrList.size(); i<len; i++) {
1143     DF_Attribute* anAttr = attrList[i];
1144     if (aTargetLabel.FindAttribute(anAttr->ID())) {
1145       aTargetLabel.ForgetAttribute(anAttr->ID());
1146     }
1147     DF_Attribute* aNewAttribute = anAttr->NewEmpty();
1148     aTargetLabel.AddAttribute(aNewAttribute);
1149     anAttr->Paste(aNewAttribute);
1150   }
1151
1152   // check auxiliary label for Comment => reference or name attribute of the referenced object
1153   SALOMEDSImpl_AttributeComment* aCommentAttribute = NULL;
1154   if ((aCommentAttribute=(SALOMEDSImpl_AttributeComment*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeComment::GetID()))) {
1155     char * anEntry = new char[aCommentAttribute->Value().size() + 1];
1156     strcpy(anEntry, std::string(aCommentAttribute->Value()).c_str());
1157     char* aNameStart = strchr(anEntry, ' ');
1158     if (aNameStart) {
1159       *aNameStart = '\0';
1160       aNameStart++;
1161     }
1162     // copy to the same study, reanimate reference
1163     DF_Label aRefLabel = DF_Label::Label(aTargetLabel, anEntry);
1164     SALOMEDSImpl_AttributeReference::Set(aTargetLabel, aRefLabel);
1165     // target attributes structure support
1166     SALOMEDSImpl_AttributeTarget::Set(aRefLabel)->Add(SALOMEDSImpl_Study::SObject(aTargetLabel));
1167
1168     delete [] anEntry;
1169   }
1170
1171   return aTargetLabel;
1172 }
1173
1174 //============================================================================
1175 /*! Function : Paste
1176  *  Purpose  :
1177  */
1178 //============================================================================
1179 SALOMEDSImpl_SObject SALOMEDSImpl_Study::Paste(const SALOMEDSImpl_SObject& theObject,
1180                                                SALOMEDSImpl_Driver* theEngine)
1181 {
1182   _errorCode = "";
1183
1184   SALOMEDSImpl_SObject so;
1185
1186   // if study is locked, then paste can't be done
1187   if (GetProperties()->IsLocked()) {
1188     _errorCode = "LockProtection";
1189     throw LockProtection("LockProtection");
1190   }
1191
1192   // if there is no component name, then paste only SObjects and attributes: without component help
1193   SALOMEDSImpl_AttributeComment* aComponentName = NULL;
1194   bool aStructureOnly = !(aComponentName=(SALOMEDSImpl_AttributeComment*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID()));
1195
1196   // CAF document of current study usage
1197   if (!_doc) {
1198     _errorCode = "Document is null";
1199     return so;
1200   }
1201
1202   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
1203
1204   // fill root inserted SObject
1205   DF_Label aStartLabel;
1206   if (aStructureOnly) {
1207     DF_Label anObjectLabel = DF_Label::Label(_doc->Main(), theObject.GetID());
1208     aStartLabel = PasteLabel(theEngine, _clipboard->Main(), anObjectLabel, false);
1209   } else {
1210     DF_Label aComponentLabel = DF_Label::Label(_doc->Main(), aComponent.GetID());
1211     aStartLabel = PasteLabel(theEngine, _clipboard->Main(), aComponentLabel, true);
1212   }
1213
1214   // paste all sublebels
1215   DF_ChildIterator anIterator(_clipboard->Main(), true);
1216   for(; anIterator.More(); anIterator.Next()) {
1217     PasteLabel(theEngine, anIterator.Value(), aStartLabel, false);
1218   }
1219
1220   return SALOMEDSImpl_Study::SObject(aStartLabel);
1221 }
1222
1223 //============================================================================
1224 /*! Function : GetPersistentReference
1225  *  Purpose  : Get persistent reference of study (idem URL())
1226  */
1227 //============================================================================
1228 std::string SALOMEDSImpl_Study::GetPersistentReference()
1229 {
1230   _errorCode = "";
1231   return URL();
1232 }
1233
1234 //============================================================================
1235 /*! Function : IsEmpty
1236  *  Purpose  : Detect if study is empty
1237  */
1238 //============================================================================
1239 bool SALOMEDSImpl_Study::IsEmpty()
1240 {
1241   _errorCode = "";
1242   if (!_doc) return true;
1243   return _doc->IsEmpty();
1244 }
1245
1246 //============================================================================
1247 /*! Function : FindComponent
1248  *  Purpose  : Find a Component with ComponentDataType = aComponentName
1249  */
1250 //============================================================================
1251 SALOMEDSImpl_SComponent SALOMEDSImpl_Study::FindComponent (const std::string& aComponentName)
1252 {
1253   _errorCode = "";
1254   bool _find = false;
1255   std::string name;
1256   SALOMEDSImpl_SComponentIterator itcomp = NewComponentIterator();
1257   SALOMEDSImpl_SComponent compo;
1258
1259   for (; itcomp.More(); itcomp.Next()) {
1260     SALOMEDSImpl_SComponent SC = itcomp.Value();
1261     name = SC.ComponentDataType();
1262     if(aComponentName == name) {
1263       _find = true;
1264       return SC;
1265     }
1266   }
1267
1268   if(!_find)
1269     {
1270       _errorCode = "No component was found";
1271       return compo;
1272     }
1273   return compo;
1274 }
1275
1276 //============================================================================
1277 /*! Function : FindComponentID
1278  *  Purpose  : Find a Component from it's ID
1279  */
1280 //============================================================================
1281 SALOMEDSImpl_SComponent SALOMEDSImpl_Study::FindComponentID(const std::string& aComponentID)
1282 {
1283   _errorCode = "";
1284
1285   // Iterate on each components defined in the study
1286   // Get the component ID and compare with aComponentID
1287   bool _find = false;
1288   std::string ID;
1289   SALOMEDSImpl_SComponent compo;
1290
1291   SALOMEDSImpl_SComponentIterator itcomp = NewComponentIterator();
1292   for (; itcomp.More(); itcomp.Next()) {
1293     SALOMEDSImpl_SComponent SC = itcomp.Value();
1294     ID = SC.GetID();
1295     if(aComponentID == ID)
1296       {
1297         // ComponentID found
1298         _find = true;
1299         compo = SC;
1300       }
1301   }
1302   if(!_find)
1303     {
1304       _errorCode = "No component was found";
1305       compo = compo;
1306     }
1307
1308   return compo;
1309 }
1310
1311 //============================================================================
1312 /*! Function : FindObject
1313  *  Purpose  : Find an Object with SALOMEDSImpl_Name = anObjectName
1314  */
1315 //============================================================================
1316 SALOMEDSImpl_SObject SALOMEDSImpl_Study::FindObject(const std::string& anObjectName)
1317 {
1318   _errorCode = "";
1319
1320   // Iterate to all components defined in the study
1321   // After testing the component name, iterate in all objects defined under
1322   // components (function _FindObject)
1323   bool _find = false;
1324   SALOMEDSImpl_SObject RefSO;
1325
1326   SALOMEDSImpl_SComponentIterator it = NewComponentIterator();
1327   for (; it.More();it.Next()){
1328     if(!_find)
1329       {
1330         SALOMEDSImpl_SComponent SC = it.Value();
1331         if (SC.GetName() == anObjectName)
1332         {
1333             _find = true;
1334             RefSO = SC;
1335
1336         }
1337         if (!_find) RefSO =  _FindObject(SC, anObjectName, _find);
1338       }
1339   }
1340   if(!RefSO) _errorCode = "No object was found";
1341   return RefSO;
1342 }
1343
1344 //============================================================================
1345 /*! Function : FindObjectID
1346  *  Purpose  : Find an Object with ID = anObjectID
1347  */
1348 //============================================================================
1349 SALOMEDSImpl_SObject SALOMEDSImpl_Study::FindObjectID(const std::string& anObjectID)
1350 {
1351   _errorCode = "";
1352   SALOMEDSImpl_SObject so;
1353
1354   // Convert aSO->GetID in DF_Label.
1355   DF_Label Lab = DF_Label::Label(_doc->Main(), anObjectID, false);
1356
1357   if (Lab.IsNull()) {
1358     _errorCode = "No label was found by ID";
1359     return so;
1360   }
1361   return GetSObject(Lab);
1362
1363 }
1364
1365 //============================================================================
1366 /*! Function : CreateObjectID
1367  *  Purpose  : Creates an Object with ID = anObjectID
1368  */
1369 //============================================================================
1370 SALOMEDSImpl_SObject SALOMEDSImpl_Study::CreateObjectID(const std::string& anObjectID)
1371 {
1372   _errorCode = "";
1373   SALOMEDSImpl_SObject so;
1374
1375   // Convert aSO->GetID in DF_Label.
1376   DF_Label Lab = DF_Label::Label(_doc->Main(), anObjectID, true);
1377
1378   if (Lab.IsNull()) {
1379     _errorCode = "Can not create a label";
1380     return so;
1381   }
1382   return GetSObject(Lab);
1383
1384 }
1385
1386 //============================================================================
1387 /*! Function : FindObjectByName
1388  *  Purpose  : Find Objects with SALOMEDSImpl_Name = anObjectName in a Component
1389  *           : with ComponentDataType = aComponentName
1390  */
1391 //============================================================================
1392 std::vector<SALOMEDSImpl_SObject> SALOMEDSImpl_Study::FindObjectByName(const std::string& anObjectName,
1393                                                                        const std::string& aComponentName)
1394 {
1395   _errorCode = "";
1396
1397   std::vector<SALOMEDSImpl_SObject> listSO;
1398
1399   SALOMEDSImpl_SComponent compo = FindComponent(aComponentName) ;
1400   if ( !compo ) {
1401     _errorCode = "Can not find the component";
1402     return listSO;
1403   }
1404
1405   // Iterate on each object and subobject of the component
1406   // If objectName is found add it to the list of SObjects
1407   std::string childName ;
1408
1409   std::string compoId = compo.GetID();
1410   SALOMEDSImpl_ChildIterator it = NewChildIterator(compo);
1411   for ( ; it.More(); it.Next() ) {
1412
1413     SALOMEDSImpl_SObject CSO = it.Value();
1414     if ( CSO.GetName() == anObjectName ) {
1415         /* add to list */
1416         listSO.push_back(CSO) ;
1417     }
1418
1419     /* looks also for eventual children */
1420     bool found = false ;
1421     CSO = _FindObject( CSO, anObjectName, found ) ;
1422     if( found) {
1423       listSO.push_back(CSO) ;
1424     }
1425   }
1426
1427   return listSO;
1428 }
1429
1430
1431
1432 //============================================================================
1433 /*! Function : FindObjectIOR
1434  *  Purpose  : Find an Object with IOR = anObjectIOR
1435  */
1436 //============================================================================
1437 SALOMEDSImpl_SObject SALOMEDSImpl_Study::FindObjectIOR(const std::string& anObjectIOR)
1438 {
1439   _errorCode = "";
1440
1441   SALOMEDSImpl_SObject aResult ;
1442
1443   // searching in the datamap for optimization
1444   std::map<std::string, DF_Label>::iterator it=myIORLabels.find(anObjectIOR);
1445   if (it != myIORLabels.end()) {
1446     aResult = GetSObject(it->second);
1447     // 11 oct 2002: forbidden attributes must be checked here
1448     if (!aResult.GetLabel().IsAttribute(SALOMEDSImpl_AttributeIOR::GetID())) {
1449       myIORLabels.erase(anObjectIOR);
1450       aResult = SALOMEDSImpl_SObject();
1451     }
1452   }
1453
1454   if(!aResult) _errorCode = "No object was found";
1455   return aResult;
1456 }
1457
1458 //============================================================================
1459 /*! Function : FindObjectByPath
1460  *  Purpose  : Find an Object by its path = thePath
1461  */
1462 //============================================================================
1463 SALOMEDSImpl_SObject SALOMEDSImpl_Study::FindObjectByPath(const std::string& thePath)
1464 {
1465   _errorCode = "";
1466
1467   std::string aPath(thePath), aToken;
1468   SALOMEDSImpl_SObject aSO;
1469   int aLength = aPath.size();
1470   bool isRelative = false;
1471
1472   if(aLength == 0) {  //Empty path - return the current context
1473     return aSO;
1474   }
1475
1476   if(aPath[0] != '/')  //Relative path
1477     isRelative = true;
1478
1479   DF_ChildIterator anIterator;
1480   DF_Label aLabel;
1481   SALOMEDSImpl_AttributeName* anAttr;
1482
1483   if(isRelative) {
1484     return aSO;
1485   }
1486   else {
1487     if(aPath.size() == 1 && aPath[0] == '/') {    //Root
1488       return GetSObject(_doc->Main());
1489     }
1490     anIterator.Init(_doc->Main(), false);
1491   }
1492
1493   std::vector<std::string> vs = SALOMEDSImpl_Tool::splitString(aPath, '/');
1494   for(int i = 0, len = vs.size(); i<len; i++) {
1495
1496     aToken = vs[i];
1497     if(aToken.size() == 0) break;
1498
1499     for ( ; anIterator.More(); anIterator.Next() ) {
1500       aLabel = anIterator.Value();
1501       if((anAttr=(SALOMEDSImpl_AttributeName*)aLabel.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
1502         if(anAttr->Value() == aToken) {
1503           if(i == (len-1)) {  //The searched label is found (no part of the path is left)
1504               return GetSObject(aLabel);
1505           }
1506
1507           anIterator.Init(aLabel, false);
1508           break;
1509         }
1510       }
1511     }
1512
1513   }
1514
1515   if(!aSO) _errorCode = "No object was found";
1516   return aSO;
1517 }
1518
1519 //============================================================================
1520 /*! Function : GetObjectPath
1521  *  Purpose  :
1522  */
1523 //============================================================================
1524 std::string SALOMEDSImpl_Study::GetObjectPath(const SALOMEDSImpl_SObject& theObject)
1525 {
1526   _errorCode = "";
1527
1528   std::string aPath("");
1529   if(!theObject) {
1530     _errorCode = "Null object";
1531     return aPath;
1532   }
1533
1534   std::string aName = theObject.GetName();
1535   if(!aName.empty() && aName != "" ) {
1536     std::string aValue("/");
1537     aValue+=aName;
1538     aValue += aPath;
1539     aPath = aValue;
1540     SALOMEDSImpl_SObject aFather = theObject.GetFather();
1541     if(aFather) {
1542        aName = aFather.GetName();
1543        if(!aName.empty() && aName != "") {
1544            aValue = GetObjectPath(aFather);
1545           aPath = aValue + aPath;
1546        }
1547     }
1548   }
1549
1550   return aPath;
1551 }
1552
1553
1554 //============================================================================
1555 /*! Function : GetObjectPathByIOR
1556  *  Purpose  :
1557  */
1558 //============================================================================
1559 std::string SALOMEDSImpl_Study::GetObjectPathByIOR(const std::string& theIOR)
1560 {
1561   _errorCode = "";
1562
1563   std::string aPath;
1564   SALOMEDSImpl_SObject so = FindObjectIOR(theIOR);
1565   if(!so) {
1566     _errorCode = "No SObject was found by IOR";
1567     return aPath;
1568   }
1569
1570   return GetObjectPath(so);
1571 }
1572
1573 //============================================================================
1574 /*! Function : NewChildIterator
1575  *  Purpose  : Create a ChildIterator from an SObject
1576  */
1577 //============================================================================
1578 SALOMEDSImpl_ChildIterator SALOMEDSImpl_Study::NewChildIterator(const SALOMEDSImpl_SObject& aSO)
1579 {
1580   _errorCode = "";
1581   return SALOMEDSImpl_ChildIterator(aSO);
1582 }
1583
1584
1585 //============================================================================
1586 /*! Function : NewComponentIterator
1587  *  Purpose  : Create a SComponentIterator
1588  */
1589 //============================================================================
1590 SALOMEDSImpl_SComponentIterator SALOMEDSImpl_Study::NewComponentIterator()
1591 {
1592   _errorCode = "";
1593   return SALOMEDSImpl_SComponentIterator(_doc);
1594 }
1595
1596
1597 //============================================================================
1598 /*! Function : NewBuilder
1599  *  Purpose  : Create a StudyBuilder
1600  */
1601 //============================================================================
1602 SALOMEDSImpl_StudyBuilder* SALOMEDSImpl_Study::NewBuilder()
1603 {
1604   _errorCode = "";
1605   if(_autoFill) {
1606     _builder->SetOnAddSObject(_cb);
1607     _builder->SetOnRemoveSObject(_cb);
1608   }
1609   return _builder;
1610
1611 }
1612
1613 //============================================================================
1614 /*! Function : Name
1615  *  Purpose  : get study name
1616  */
1617 //============================================================================
1618 std::string SALOMEDSImpl_Study::Name()
1619 {
1620   _errorCode = "";
1621   return Kernel_Utils::GetBaseName( _name, false );
1622 }
1623
1624 //============================================================================
1625 /*! Function : Name
1626  *  Purpose  : set study name
1627  */
1628 //============================================================================
1629 void SALOMEDSImpl_Study::Name(const std::string& name)
1630 {
1631   _errorCode = "";
1632   _name = name;
1633 }
1634
1635 //============================================================================
1636 /*! Function : IsSaved
1637  *  Purpose  : get if study has been saved
1638  */
1639 //============================================================================
1640 bool SALOMEDSImpl_Study::IsSaved()
1641 {
1642   _errorCode = "";
1643   return _Saved;
1644 }
1645
1646 //============================================================================
1647 /*! Function : IsSaved
1648  *  Purpose  : set if study has been saved
1649  */
1650 //============================================================================
1651 void SALOMEDSImpl_Study::IsSaved(bool save)
1652 {
1653   _errorCode = "";
1654   _Saved = save;
1655   if(save) _doc->SetModified(false);
1656 }
1657
1658 //============================================================================
1659 /*! Function : IsModified
1660  *  Purpose  : Detect if a Study has been modified since it has been saved
1661  */
1662 //============================================================================
1663 bool SALOMEDSImpl_Study::IsModified()
1664 {
1665   _errorCode = "";
1666
1667   // True if is modified
1668   if (_doc && _doc->IsModified()) return true;
1669
1670   return false;
1671 }
1672
1673 //============================================================================
1674 /*! Function : URL
1675  *  Purpose  : get URL of the study (persistent reference of the study)
1676  */
1677 //============================================================================
1678 std::string SALOMEDSImpl_Study::URL()
1679 {
1680   _errorCode = "";
1681   return _URL;
1682 }
1683
1684 //============================================================================
1685 /*! Function : URL
1686  *  Purpose  : set URL of the study (persistent reference of the study)
1687  */
1688 //============================================================================
1689 void SALOMEDSImpl_Study::URL(const std::string& url)
1690 {
1691   _errorCode = "";
1692   _URL = url;
1693   _name = url;
1694
1695   /*jfa: Now name of SALOMEDS study will correspond to name of SalomeApp study
1696   std::string tmp(_URL);
1697
1698   char *aName = (char*)tmp.ToCString();
1699   char *adr = strtok(aName, "/");
1700   while (adr)
1701     {
1702       aName = adr;
1703       adr = strtok(NULL, "/");
1704     }
1705   Name(aName);*/
1706 }
1707
1708
1709 //============================================================================
1710 /*! Function : _FindObject
1711  *  Purpose  : Find an Object with SALOMEDSImpl_Name = anObjectName
1712  */
1713 //============================================================================
1714 SALOMEDSImpl_SObject SALOMEDSImpl_Study::_FindObject(const SALOMEDSImpl_SObject& SO,
1715                                                      const std::string& theObjectName,
1716                                                      bool& _find)
1717 {
1718   SALOMEDSImpl_SObject RefSO;
1719   if(!SO) return RefSO;
1720
1721   // Iterate on each objects and subobjects of the component
1722   // If objectName find, stop the loop and get the object reference
1723   SALOMEDSImpl_AttributeName* anAttr;
1724
1725   std::string soid = SO.GetID();
1726   DF_ChildIterator it(SO.GetLabel());
1727   for (; it.More(); it.Next()){
1728     if(!_find)
1729       {
1730         if ((anAttr=(SALOMEDSImpl_AttributeName*)it.Value().FindAttribute(SALOMEDSImpl_AttributeName::GetID())))
1731         {
1732           std::string Val(anAttr->Value());
1733           if (Val == theObjectName)
1734             {
1735               RefSO = GetSObject(it.Value());
1736               _find = true;
1737             }
1738         }
1739         if (!_find) RefSO = _FindObject(GetSObject(it.Value()), theObjectName, _find);
1740       }
1741   }
1742   return RefSO;
1743 }
1744
1745 //============================================================================
1746 /*! Function : _FindObjectIOR
1747  *  Purpose  : Find an Object with SALOMEDSImpl_IOR = anObjectIOR
1748  */
1749 //============================================================================
1750 SALOMEDSImpl_SObject
1751 SALOMEDSImpl_Study::_FindObjectIOR(const SALOMEDSImpl_SObject& SO,
1752                                    const std::string& theObjectIOR,
1753                                    bool& _find)
1754 {
1755   SALOMEDSImpl_SObject RefSO, aSO;
1756   if(!SO) return RefSO;
1757
1758   // Iterate on each objects and subobjects of the component
1759   // If objectName find, stop the loop and get the object reference
1760   SALOMEDSImpl_AttributeIOR* anAttr;
1761
1762   DF_ChildIterator it(SO.GetLabel());
1763   for (; it.More();it.Next()){
1764     if(!_find)
1765       {
1766         if ((anAttr=(SALOMEDSImpl_AttributeIOR*)it.Value().FindAttribute(SALOMEDSImpl_AttributeIOR::GetID())))
1767         {
1768           std::string Val(anAttr->Value());
1769           if (Val == theObjectIOR)
1770             {
1771               RefSO = GetSObject(it.Value());
1772               _find = true;
1773             }
1774         }
1775         aSO = GetSObject(it.Value());
1776         if (!_find) RefSO =  _FindObjectIOR(aSO, theObjectIOR, _find);
1777       }
1778   }
1779   return RefSO;
1780 }
1781
1782 //============================================================================
1783 /*! Function : _GetNoteBookAccessor
1784  *  Purpose  : Find an Object with SALOMEDSImpl_IOR = anObjectIOR
1785  */
1786 //============================================================================
1787 std::string SALOMEDSImpl_Study::_GetNoteBookAccessor(){
1788   return std::string("notebook");
1789 }
1790
1791 //============================================================================
1792 /*! Function : _GetStudyVariablesScript
1793  *  Purpose  :
1794  */
1795 //============================================================================
1796 std::string SALOMEDSImpl_Study::_GetStudyVariablesScript()
1797 {
1798   std::string dump("");
1799
1800   if(myNoteBookVars.empty())
1801     return dump;
1802
1803   Kernel_Utils::Localizer loc;
1804
1805   dump += "####################################################\n";
1806   dump += "##       Begin of NoteBook variables section      ##\n";
1807   dump += "####################################################\n";
1808
1809   std::string set_method = _GetNoteBookAccessor()+".set(";
1810   std::string varName;
1811   std::string varValue;
1812   for(int i = 0 ; i < myNoteBookVars.size();i++ ) {
1813     varName = myNoteBookVars[i]->Name();
1814     varValue = myNoteBookVars[i]->SaveToScript();
1815     dump+=set_method+"\""+varName+"\", "+varValue+")\n";
1816   }
1817
1818   dump += "####################################################\n";
1819   dump += "##        End of NoteBook variables section       ##\n";
1820   dump += "####################################################\n";
1821
1822   return dump;
1823 }
1824
1825 //============================================================================
1826 /*! Function : _GetNoteBookAccess
1827  *  Purpose  :
1828  */
1829 //============================================================================
1830 std::string SALOMEDSImpl_Study::_GetNoteBookAccess()
1831 {
1832   std::string notebook = "import salome_notebook\n";
1833   notebook += _GetNoteBookAccessor() + " = salome_notebook.NoteBook()" ;
1834   return notebook;
1835 }
1836
1837 bool SALOMEDSImpl_Study::IsLocked()
1838 {
1839   _errorCode = "";
1840   return GetProperties()->IsLocked();
1841 }
1842
1843 void SALOMEDSImpl_Study::UpdateIORLabelMap(const std::string& anIOR,const std::string& anEntry)
1844 {
1845   _errorCode = "";
1846   DF_Label aLabel = DF_Label::Label(_doc->Main(), anEntry, true);
1847   std::map<std::string, DF_Label>::iterator it=myIORLabels.find(anIOR);
1848   if (it != myIORLabels.end()) myIORLabels.erase(it);
1849   myIORLabels[anIOR] = aLabel;
1850 }
1851
1852 void SALOMEDSImpl_Study::DeleteIORLabelMapItem(const std::string& anIOR)
1853 {
1854   std::map<std::string, DF_Label>::iterator it=myIORLabels.find(anIOR);
1855   if (it != myIORLabels.end())
1856     {
1857       //remove the ior entry and decref the genericobj (if it's one)
1858       myIORLabels.erase(it);
1859     }
1860 }
1861
1862 SALOMEDSImpl_Study* SALOMEDSImpl_Study::GetStudyImpl(const DF_Label& theLabel)
1863 {
1864   SALOMEDSImpl_StudyHandle* Att;
1865   if ((Att=(SALOMEDSImpl_StudyHandle*)theLabel.Root().FindAttribute(SALOMEDSImpl_StudyHandle::GetID()))) {
1866     return Att->Get();
1867   }
1868   return NULL;
1869 }
1870
1871 SALOMEDSImpl_SObject SALOMEDSImpl_Study::SObject(const DF_Label& theLabel)
1872 {
1873   return GetStudyImpl(theLabel)->GetSObject(theLabel);
1874 }
1875
1876 SALOMEDSImpl_SComponent SALOMEDSImpl_Study::SComponent(const DF_Label& theLabel)
1877 {
1878   return GetStudyImpl(theLabel)->GetSComponent(theLabel);
1879 }
1880
1881
1882 void SALOMEDSImpl_Study::IORUpdated(const SALOMEDSImpl_AttributeIOR* theAttribute)
1883 {
1884   std::string aString = theAttribute->Label().Entry();
1885   GetStudyImpl(theAttribute->Label())->UpdateIORLabelMap(theAttribute->Value(), aString);
1886 }
1887
1888 std::vector<SALOMEDSImpl_SObject> SALOMEDSImpl_Study::FindDependances(const SALOMEDSImpl_SObject& anObject)
1889 {
1890   _errorCode = "";
1891   std::vector<SALOMEDSImpl_SObject> aSeq;
1892
1893   SALOMEDSImpl_AttributeTarget* aTarget;
1894   if ((aTarget=(SALOMEDSImpl_AttributeTarget*)anObject.GetLabel().FindAttribute(SALOMEDSImpl_AttributeTarget::GetID()))) {
1895     return aTarget->Get();
1896   }
1897
1898   return aSeq;
1899 }
1900
1901
1902 SALOMEDSImpl_AttributeStudyProperties* SALOMEDSImpl_Study::GetProperties()
1903 {
1904   _errorCode = "";
1905   return SALOMEDSImpl_AttributeStudyProperties::Set(_doc->Main());
1906 }
1907
1908 std::string SALOMEDSImpl_Study::GetLastModificationDate()
1909 {
1910   _errorCode = "";
1911   SALOMEDSImpl_AttributeStudyProperties* aProp = GetProperties();
1912
1913   std::vector<std::string> aNames;
1914   std::vector<int> aMinutes, aHours, aDays, aMonths, aYears;
1915   aProp->GetModifications(aNames, aMinutes, aHours, aDays, aMonths, aYears);
1916
1917   int aLastIndex = aNames.size()-1;
1918   char aResult[20];
1919   sprintf(aResult, "%2.2d/%2.2d/%4.4d %2.2d:%2.2d",
1920           (int)(aDays[aLastIndex]),(int)(aMonths[aLastIndex]), (int)(aYears[aLastIndex]),
1921           (int)(aHours[aLastIndex]), (int)(aMinutes[aLastIndex]));
1922   std::string aResStr (aResult);
1923   return aResStr;
1924 }
1925
1926 std::vector<std::string> SALOMEDSImpl_Study::GetModificationsDate()
1927 {
1928   _errorCode = "";
1929   SALOMEDSImpl_AttributeStudyProperties* aProp = GetProperties();
1930
1931   std::vector<std::string> aNames;
1932   std::vector<int> aMinutes, aHours, aDays, aMonths, aYears;
1933   aProp->GetModifications(aNames, aMinutes, aHours, aDays, aMonths, aYears);
1934
1935   int anIndex, aLength = aNames.size();
1936   std::vector<std::string> aDates;
1937
1938   for (anIndex = 1; anIndex < aLength; anIndex++) {
1939     char aDate[20];
1940     sprintf(aDate, "%2.2d/%2.2d/%4.4d %2.2d:%2.2d",
1941             (int)(aDays[anIndex]), (int)(aMonths[anIndex]), (int)(aYears[anIndex]),
1942             (int)(aHours[anIndex]), (int)(aMinutes[anIndex]));
1943     aDates.push_back(aDate);
1944   }
1945   return aDates;
1946 }
1947
1948
1949
1950 //============================================================================
1951 /*! Function : GetUseCaseBuilder
1952  *  Purpose  : Returns a UseCase builder
1953  */
1954 //============================================================================
1955 SALOMEDSImpl_UseCaseBuilder* SALOMEDSImpl_Study::GetUseCaseBuilder()
1956 {
1957   _errorCode = "";
1958   return _useCaseBuilder;
1959 }
1960
1961 //============================================================================
1962 /*! Function : GetSComponent
1963  *  Purpose  :
1964  */
1965 //============================================================================
1966 SALOMEDSImpl_SComponent SALOMEDSImpl_Study::GetSComponent(const std::string& theEntry)
1967 {
1968   SALOMEDSImpl_SComponent aSCO;
1969   if(_mapOfSCO.find(theEntry) != _mapOfSCO.end())
1970     aSCO = _mapOfSCO[theEntry];
1971   else {
1972     DF_Label aLabel = DF_Label::Label(_doc->Main(), theEntry);
1973     aSCO = SALOMEDSImpl_SComponent(aLabel);
1974     _mapOfSCO[theEntry] = aSCO;
1975   }
1976
1977   return aSCO;
1978 }
1979
1980 //============================================================================
1981 /*! Function : GetSComponent
1982  *  Purpose  :
1983  */
1984 //============================================================================
1985 SALOMEDSImpl_SComponent SALOMEDSImpl_Study::GetSComponent(const DF_Label& theLabel)
1986 {
1987   return SALOMEDSImpl_SComponent(theLabel);
1988 }
1989
1990 //============================================================================
1991 /*! Function : GetSObject
1992  *  Purpose  :
1993  */
1994 //============================================================================
1995 SALOMEDSImpl_SObject SALOMEDSImpl_Study::GetSObject(const std::string& theEntry)
1996 {
1997   SALOMEDSImpl_SObject aSO;
1998   std::map<std::string, SALOMEDSImpl_SObject>::iterator it=_mapOfSO.find(theEntry);
1999   if(it != _mapOfSO.end())
2000     aSO = it->second;
2001   else {
2002     DF_Label aLabel = DF_Label::Label(_doc->Main(), theEntry);
2003     aSO = SALOMEDSImpl_SObject(aLabel);
2004     _mapOfSO[theEntry] = aSO;
2005   }
2006
2007   return aSO;
2008 }
2009
2010 //============================================================================
2011 /*! Function : GetSObject
2012  *  Purpose  :
2013  */
2014 //============================================================================
2015 SALOMEDSImpl_SObject SALOMEDSImpl_Study::GetSObject(const DF_Label& theLabel)
2016 {
2017   return SALOMEDSImpl_SObject(theLabel);
2018 }
2019
2020 //============================================================================
2021 /*! Function : GetAttribute
2022  *  Purpose  :
2023  */
2024 //============================================================================
2025 DF_Attribute* SALOMEDSImpl_Study::GetAttribute(const std::string& theEntry,
2026                                                const std::string& theType)
2027 {
2028   SALOMEDSImpl_SObject aSO = GetSObject(theEntry);
2029   DF_Attribute* anAttr;
2030   aSO.FindAttribute(anAttr, theType);
2031   return anAttr;
2032 }
2033
2034 //! number of spaces for indentation in Python dump files (to replace \t symbols)
2035 static const int indent_size = 2;
2036
2037 static std::string replace_tabs( const std::string& in )
2038 {
2039   std::string out = in;
2040 #ifdef WITHOUT_TABS
2041   size_t pos = out.find( '\t' );
2042   while ( pos != std::string::npos ) {
2043     out.replace( pos, 1, indent_size, ' ' );
2044     pos = out.find( '\t' );
2045   }
2046 #endif
2047   return out;
2048 }
2049
2050 static std::string GetComponentHeader(const char* theComponentName)
2051 {
2052   std::stringstream txt;
2053   txt << "###" << std::endl;
2054   txt << "### " << theComponentName << " component" << std::endl;
2055   txt << "###" << std::endl;
2056   return txt.str();
2057 }
2058
2059 //============================================================================
2060 /*! Function : DumpStudy
2061  *  Purpose  :
2062  */
2063 //============================================================================
2064 bool SALOMEDSImpl_Study::DumpStudy(const std::string& thePath,
2065                                    const std::string& theBaseName,
2066                                    bool isPublished,
2067                                    bool isMultiFile,
2068                                    SALOMEDSImpl_DriverFactory* theFactory)
2069 {
2070   _errorCode = "";
2071
2072   if(theFactory == NULL) {
2073     _errorCode = "Null factory for creation of Engines";
2074     return false;
2075   }
2076
2077   std::vector<std::string> aSeq;
2078   std::string aFactoryType;
2079
2080   //Build a list of all components in the Study
2081   SALOMEDSImpl_SComponentIterator itcomponent = NewComponentIterator();
2082
2083   for (; itcomponent.More(); itcomponent.Next())
2084     aSeq.push_back(itcomponent.Value().ComponentDataType());
2085
2086   std::vector<std::string>::iterator it;
2087   if ( (it = std::find( aSeq.begin(), aSeq.end(), "GEOM" )) != aSeq.end() ) {
2088     aSeq.erase( it );
2089     aSeq.insert(aSeq.begin(), "GEOM" );
2090   }
2091   if ( (it = std::find( aSeq.begin(), aSeq.end(), "SHAPER" )) != aSeq.end() ) {
2092     aSeq.erase( it );
2093     aSeq.insert(aSeq.begin(), "SHAPER" );
2094   }
2095
2096   // re-arrange modules in the sequence, if specific order is given via SALOME_MODULES_ORDER environment variable.
2097   if ( getenv("SALOME_MODULES_ORDER") != 0 ) {
2098     std::string order = getenv("SALOME_MODULES_ORDER");
2099     std::vector<std::string> mlist;
2100     while ( !order.empty() ) {
2101       size_t idx = order.find( ":" );
2102       std::string m = order.substr(0, idx);
2103       order = order.substr( ( idx == std::string::npos ) ? order.size() : idx+1 );
2104       if ( m.empty() || std::find( mlist.begin(), mlist.end(), m ) != mlist.end() ) continue;
2105       mlist.push_back( m );
2106     }
2107
2108     for ( std::vector<std::string>::reverse_iterator mit = mlist.rbegin(); mit != mlist.rend(); ++mit ) {
2109       std::vector<std::string>::iterator it = std::find( aSeq.begin(), aSeq.end(), *mit );
2110       if ( it != aSeq.end() ) {
2111         aSeq.erase( it );
2112         aSeq.insert( aSeq.begin(), *mit );
2113       }
2114     }
2115   }
2116
2117 #ifdef WIN32
2118   std::string aFileName =
2119     thePath + std::string("\\") + theBaseName + std::string(".py");
2120 #else
2121   std::string aFileName =
2122     thePath + std::string("/")  + theBaseName + std::string(".py");
2123 #endif
2124
2125   //Create a file that will contain a main Study script
2126   std::fstream fp;
2127 #if defined(WIN32) && defined(UNICODE)
2128   std::wstring aConverterFN = Kernel_Utils::utf8_decode_s(aFileName);
2129   fp.open(aConverterFN.c_str(), std::ios::out);
2130 #else
2131   fp.open(aFileName.c_str(), std::ios::out);
2132 #endif
2133
2134 #ifdef WIN32
2135   bool isOpened = fp.is_open();
2136 #else
2137   bool isOpened = fp.rdbuf()->is_open();
2138 #endif
2139
2140   if(!isOpened) {
2141     _errorCode = std::string("Can't create a file ")+aFileName;
2142     return false;
2143   }
2144
2145   std::stringstream sfp;
2146
2147   std::string aBatchModeScript = "salome";
2148
2149   //Output to the main Study script required Python modules import,
2150   //set sys.path and add a creation of the study.
2151
2152   // dump header
2153   sfp << GetDumpStudyComment() << std::endl;
2154
2155   // global imports
2156   sfp << "import sys" << std::endl;
2157   sfp << "import " << aBatchModeScript << std::endl << std::endl;
2158
2159   // initialization function
2160   sfp << aBatchModeScript << ".salome_init()" << std::endl;
2161
2162   // notebook initialization
2163   sfp << _GetNoteBookAccess() << std::endl;
2164
2165   // extend sys.path with the directory where the script is being dumped to
2166   sfp << "sys.path.insert(0, r\'" << thePath << "\')" << std::endl << std::endl;
2167
2168   // dump NoteBook variables
2169   sfp << _GetStudyVariablesScript();
2170
2171   // dump visual parameters if necessary
2172   bool isDumpVisuals = SALOMEDSImpl_IParameters::isDumpPython(this);
2173   int lastSavePoint = -1;
2174   if(isDumpVisuals) {
2175     lastSavePoint = SALOMEDSImpl_IParameters::getLastSavePoint(this);
2176     if(lastSavePoint > 0) {
2177       sfp << SALOMEDSImpl_IParameters::getStudyScript(this, lastSavePoint) << std::endl << std::endl;
2178     }
2179   }
2180
2181   std::vector<std::string> aSeqOfFileNames;
2182
2183   // dump all components and create the components specific scripts
2184   bool isOk = true;
2185   int aLength = aSeq.size();
2186   for(int i = 1; i <= aLength; i++) {
2187
2188     std::string aCompType = aSeq[i-1];
2189     SALOMEDSImpl_SComponent sco = FindComponent(aCompType);
2190     SALOMEDSImpl_Driver* aDriver = NULL;
2191     // if there is an associated Engine call its method for saving
2192     std::string IOREngine;
2193     try {
2194       if (!sco.ComponentIOR(IOREngine)) {
2195         if (!aCompType.empty()) {
2196
2197           aDriver = theFactory->GetDriverByType(aCompType);
2198
2199           if (aDriver != NULL) {
2200             SALOMEDSImpl_StudyBuilder* SB = NewBuilder();
2201             if(!SB->LoadWith(sco, aDriver)) {
2202               _errorCode = SB->GetErrorCode();
2203               return false;
2204             }
2205           }
2206           else continue;
2207         }
2208       }
2209       else {
2210         aDriver = theFactory->GetDriverByIOR(IOREngine);
2211       }
2212     } catch(...) {
2213       _errorCode = "Can not restore information to dump it";
2214       return false;
2215     }
2216
2217     if(aDriver == NULL) continue;
2218
2219     bool isValidScript;
2220     long aStreamLength  = 0;
2221     SALOMEDSImpl_TMPFile* aStream = aDriver->DumpPython(isPublished, isMultiFile, isValidScript, aStreamLength);
2222     if ( !isValidScript )
2223       isOk = false;
2224
2225     std::stringstream sfp2;
2226
2227     //Output the Python script generated by the component in the newly created file.
2228     if ( isMultiFile )
2229       sfp2 << GetDumpStudyComment( aCompType.c_str() ) << std::endl;
2230     else
2231       sfp2 << GetComponentHeader( aCompType.c_str() ) << std::endl;
2232     sfp2 << aStream->Data();
2233
2234     if ( isMultiFile ) {
2235       //Create a file that will contain the component specific script
2236       std::fstream fp2;
2237 #ifdef WIN32
2238       aFileName=thePath+std::string("\\");
2239 #else
2240       aFileName=thePath+std::string("/");
2241 #endif
2242       std::string aScriptName;
2243       aScriptName += theBaseName;
2244       aScriptName += "_";
2245       aScriptName += aCompType;
2246
2247       aFileName += aScriptName+ std::string(".py");
2248       aSeqOfFileNames.push_back(aFileName);
2249
2250 #if defined(WIN32) && defined(UNICODE)
2251       std::wstring aConverterFN2 = Kernel_Utils::utf8_decode_s(aFileName);
2252       fp2.open(aConverterFN2.c_str(), std::ios::out);
2253 #else
2254       fp2.open(aFileName.c_str(), std::ios::out);
2255 #endif
2256
2257 #ifdef WIN32
2258       isOpened = fp2.is_open();
2259 #else
2260       isOpened = fp2.rdbuf()->is_open();
2261 #endif
2262
2263       if(!isOpened) {
2264         _errorCode = std::string("Can't create a file ")+aFileName;
2265         SALOMEDSImpl_Tool::RemoveTemporaryFiles(thePath, aSeqOfFileNames, false);
2266         return false;
2267       }
2268
2269       // replace '\t' symbols
2270       fp2 << replace_tabs( sfp2.str() );
2271
2272       fp2.close();
2273
2274       //Add to the main script a call to RebuildData of the generated by the component the Python script
2275       sfp << "import " << aScriptName << std::endl;
2276       sfp << aScriptName << ".RebuildData()" << std::endl;
2277     }
2278     else
2279       sfp << sfp2.str();
2280
2281     if(aStream) delete aStream;
2282   }
2283
2284   sfp << std::endl;
2285   sfp << "if salome.sg.hasDesktop():" << std::endl;
2286   sfp << "\tsalome.sg.updateObjBrowser()" << std::endl;
2287
2288   if(isDumpVisuals) { //Output the call to Session's method restoreVisualState
2289     sfp << "\tiparameters.getSession().restoreVisualState(1)" << std::endl;
2290   }
2291
2292   // replace '\t' symbols
2293   fp << replace_tabs( sfp.str() );
2294
2295   fp.close();
2296
2297   return isOk;
2298 }
2299
2300 //=======================================================================
2301 //function : GetDumpStudyComment
2302 //purpose  : return a header comment for a DumpStudy script
2303 //=======================================================================
2304
2305 std::string SALOMEDSImpl_Study::GetDumpStudyComment(const char* theComponentName)
2306 {
2307   std::stringstream txt;
2308   txt << "#!/usr/bin/env python" << std::endl << std::endl;
2309   txt << "###" << std::endl;
2310   txt << "### This file is generated automatically by SALOME v"
2311       << KERNEL_VERSION_STR
2312       << " with dump python functionality";
2313   if ( theComponentName )
2314     txt << " (" << theComponentName << " component)";
2315   txt << std::endl;
2316   txt << "###" << std::endl;
2317   return txt.str();
2318 }
2319
2320 void dumpSO(const SALOMEDSImpl_SObject& theSO,
2321             std::fstream& fp,
2322             const std::string& Tab,
2323             SALOMEDSImpl_Study* theStudy);
2324
2325 //============================================================================
2326 /*! Function : dump
2327  *  Purpose  :
2328  */
2329 //============================================================================
2330 void SALOMEDSImpl_Study::dump(const std::string& theFileName)
2331 {
2332   //Create a file that will contain a main Study script
2333   std::fstream fp;
2334   fp.open(theFileName.c_str(), std::ios::out);
2335
2336 #ifdef WIN32
2337   bool isOpened = fp.is_open();
2338 #else
2339   bool isOpened = fp.rdbuf()->is_open();
2340 #endif
2341
2342   if(!isOpened) {
2343     _errorCode = std::string("Can't create a file ")+theFileName;
2344     std::cout << "### SALOMEDSImpl_Study::dump Error: " << _errorCode << std::endl;
2345     return;
2346   }
2347
2348   SALOMEDSImpl_SObject aSO = FindObjectID("0:1");
2349   fp << "0:1" << std::endl;
2350   SALOMEDSImpl_ChildIterator Itr = NewChildIterator(aSO);
2351   std::string aTab("   ");
2352   for(; Itr.More(); Itr.Next()) {
2353     dumpSO(Itr.Value(), fp, aTab, this);
2354   }
2355
2356   fp.close();
2357 }
2358
2359
2360 void dumpSO(const SALOMEDSImpl_SObject& theSO,
2361             std::fstream& fp,
2362             const std::string& Tab,
2363             SALOMEDSImpl_Study* theStudy)
2364 {
2365   std::string aTab(Tab), anID(theSO.GetID());
2366   fp << aTab << anID << std::endl;
2367   std::vector<DF_Attribute*> attribs = theSO.GetLabel().GetAttributes();
2368   for(int i = 0; i<attribs.size(); i++) {
2369     SALOMEDSImpl_GenericAttribute* anAttr = dynamic_cast<SALOMEDSImpl_GenericAttribute*>(attribs[i]);
2370
2371     if(!anAttr) {
2372       continue;
2373     }
2374
2375     std::string aType = anAttr->GetClassType();
2376     fp << Tab << "  -- " << aType;
2377
2378     if(aType == std::string("AttributeReal")) {
2379       fp << " : " << dynamic_cast<SALOMEDSImpl_AttributeReal*>(anAttr)->Value();
2380     }
2381     else if(aType == std::string("AttributeInteger")) {
2382       fp << " : " << dynamic_cast<SALOMEDSImpl_AttributeInteger*>(anAttr)->Value();
2383     }
2384     else if(aType ==  std::string("AttributeName")) {
2385       fp << " : " << dynamic_cast<SALOMEDSImpl_AttributeName*>(anAttr)->Value();
2386     }
2387     else if(aType == std::string("AttributeComment")) {
2388       fp << " : " << dynamic_cast<SALOMEDSImpl_AttributeComment*>(anAttr)->Value();
2389     }
2390     else if(aType == std::string("AttributeReference")) {
2391       fp << " : " << dynamic_cast<SALOMEDSImpl_AttributeReference*>(anAttr)->Save();
2392     }
2393     fp << std::endl;
2394   }
2395
2396   SALOMEDSImpl_ChildIterator Itr = theStudy->NewChildIterator(theSO);
2397   std::string aNewTab("   ");
2398   aNewTab+=aTab;
2399   for(; Itr.More(); Itr.Next()) {
2400     dumpSO(Itr.Value(), fp, aNewTab, theStudy);
2401   }
2402
2403   return;
2404 }
2405
2406 void SALOMEDSImpl_Study::Modify()
2407 {
2408   _errorCode = "";
2409   _doc->SetModified(true);
2410 }
2411
2412 //============================================================================
2413 /*! Function :
2414  *  Purpose  :
2415  */
2416 //============================================================================
2417 SALOMEDSImpl_AttributeParameter* SALOMEDSImpl_Study::GetCommonParameters(const char* theID, int theSavePoint)
2418 {
2419   if (theSavePoint < -1) return NULL;
2420   SALOMEDSImpl_StudyBuilder* builder = NewBuilder();
2421   SALOMEDSImpl_SObject so = FindComponent((char*)theID);
2422   if (!so) so = builder->NewComponent((char*)theID);
2423   SALOMEDSImpl_AttributeParameter* attParam = NULL;
2424
2425   if (theSavePoint == -1) {
2426     int ctag = 1;
2427     DF_Label savePointLabel = so.GetLabel().FindChild( ctag, /*create=*/0 );
2428     DF_Label prevPointLabel;
2429     while ( !savePointLabel.IsNull() ) {
2430       ctag++;
2431       prevPointLabel = savePointLabel;
2432       savePointLabel = so.GetLabel().FindChild( ctag, /*create=*/0 );
2433     }
2434     if ( !prevPointLabel.IsNull() )
2435       so = GetSObject( prevPointLabel );
2436   }
2437   if (theSavePoint > 0) { // Try to find SObject that contains attribute parameter ...
2438     DF_Label savePointLabel = so.GetLabel().FindChild( theSavePoint, /*create=*/0 );
2439     if ( !savePointLabel.IsNull() )
2440       so = GetSObject( savePointLabel );
2441     else // ... if it does not exist - create a new one
2442       so = builder->NewObjectToTag( so, theSavePoint );
2443   }
2444
2445   DF_Attribute* A;
2446   if (so) {
2447     builder->FindAttribute(so, A, "AttributeParameter");
2448     if ( !A ) { // first call of GetCommonParameters on "Interface Applicative" component
2449       A = builder->FindOrCreateAttribute(so, "AttributeParameter");
2450     }
2451     attParam = dynamic_cast<SALOMEDSImpl_AttributeParameter*>( A );
2452   }
2453   return attParam;
2454 }
2455
2456 //============================================================================
2457 /*! Function :
2458  *  Purpose  :
2459  */
2460 //============================================================================
2461 SALOMEDSImpl_AttributeParameter* SALOMEDSImpl_Study::GetModuleParameters(const char* theID,
2462                                                                          const char* theModuleName,
2463                                                                          int theSavePoint)
2464 {
2465   if(theSavePoint < -1) return NULL;
2466   SALOMEDSImpl_AttributeParameter* main_ap = GetCommonParameters(theID, theSavePoint);
2467   SALOMEDSImpl_SObject main_so = main_ap->GetSObject();
2468   SALOMEDSImpl_AttributeParameter* par = NULL;
2469
2470   SALOMEDSImpl_ChildIterator it = NewChildIterator(main_so);
2471   std::string moduleName(theModuleName);
2472   for(; it.More(); it.Next()) {
2473     SALOMEDSImpl_SObject so(it.Value());
2474     if((par=(SALOMEDSImpl_AttributeParameter*)so.GetLabel().FindAttribute(SALOMEDSImpl_AttributeParameter::GetID()))) {
2475       if(!par->IsSet("AP_MODULE_NAME", (Parameter_Types)3)) continue; //3 -> PT_STRING
2476       if(par->GetString("AP_MODULE_NAME") == moduleName) return par;
2477     }
2478   }
2479
2480   SALOMEDSImpl_StudyBuilder* builder = NewBuilder();
2481   SALOMEDSImpl_SObject so = builder->NewObject(main_so);
2482   par  = dynamic_cast<SALOMEDSImpl_AttributeParameter*>(builder->FindOrCreateAttribute(so, "AttributeParameter"));
2483   par->SetString("AP_MODULE_NAME", moduleName);
2484   return par;
2485 }
2486
2487 //============================================================================
2488 /*! Function : SetStudyLock
2489  *  Purpose  :
2490  */
2491 //============================================================================
2492 void SALOMEDSImpl_Study::SetStudyLock(const char* theLockerID)
2493 {
2494   _lockers.push_back(theLockerID);
2495 }
2496
2497 //============================================================================
2498 /*! Function : IsStudyLocked
2499  *  Purpose  :
2500  */
2501 //============================================================================
2502 bool SALOMEDSImpl_Study::IsStudyLocked()
2503 {
2504   return (_lockers.size() > 0);
2505 }
2506
2507 //============================================================================
2508 /*! Function : UnLockStudy
2509  *  Purpose  :
2510  */
2511 //============================================================================
2512 void SALOMEDSImpl_Study::UnLockStudy(const char* theLockerID)
2513 {
2514   std::vector<std::string>::iterator vsI = _lockers.begin();
2515   int length = _lockers.size();
2516   bool isFound = false;
2517   std::string id(theLockerID);
2518   for(int i = 0; i<length; i++, vsI++) {
2519     if(id == _lockers[i]) {
2520       isFound = true;;
2521       break;
2522     }
2523   }
2524   if(isFound) _lockers.erase(vsI);
2525 }
2526
2527 //============================================================================
2528 /*! Function : GetLockerID
2529  *  Purpose  :
2530  */
2531 //============================================================================
2532 std::vector<std::string> SALOMEDSImpl_Study::GetLockerID()
2533 {
2534   return _lockers;
2535 }
2536
2537 //============================================================================
2538 /*! Function : SetVariable
2539  *  Purpose  :
2540  */
2541 //============================================================================
2542 void SALOMEDSImpl_Study::SetVariable(const std::string& theVarName,
2543                                      const double theValue,
2544                                      const SALOMEDSImpl_GenericVariable::VariableTypes theType)
2545 {
2546   bool modified = false;
2547   SALOMEDSImpl_GenericVariable* aGVar = GetVariable(theVarName);
2548
2549   if( aGVar == NULL ) {
2550
2551     SALOMEDSImpl_ScalarVariable* aSVar = new SALOMEDSImpl_ScalarVariable(theType, theVarName);
2552
2553     aSVar->setValue(theValue);
2554     myNoteBookVars.push_back(aSVar);
2555     modified = true;
2556   }
2557   else {
2558     if(SALOMEDSImpl_ScalarVariable* aSVar = dynamic_cast<SALOMEDSImpl_ScalarVariable*>(aGVar)) {
2559       modified = aSVar->setValue(theValue) || modified;
2560       modified = aSVar->setType(theType) || modified;
2561     }
2562   }
2563   if(modified)
2564     Modify();
2565 }
2566
2567 //============================================================================
2568 /*! Function : SetStringVariable
2569  *  Purpose  :
2570  */
2571 //============================================================================
2572 void SALOMEDSImpl_Study::SetStringVariable(const std::string& theVarName,
2573                                            const std::string& theValue,
2574                                            const SALOMEDSImpl_GenericVariable::VariableTypes theType)
2575 {
2576   bool modified = false;
2577   SALOMEDSImpl_GenericVariable* aGVar = GetVariable(theVarName);
2578
2579   if( aGVar == NULL ) {
2580
2581     SALOMEDSImpl_ScalarVariable* aSVar = new SALOMEDSImpl_ScalarVariable(theType, theVarName);
2582
2583     aSVar->setStringValue(theValue);
2584     myNoteBookVars.push_back(aSVar);
2585     modified = true;
2586   }
2587   else {
2588     if(SALOMEDSImpl_ScalarVariable* aSVar = dynamic_cast<SALOMEDSImpl_ScalarVariable*>(aGVar)) {
2589       modified = aSVar->setStringValue(theValue) || modified;
2590       modified = aSVar->setType(theType) || modified;
2591     }
2592   }
2593   if(modified)
2594     Modify();
2595 }
2596
2597 //============================================================================
2598 /*! Function : SetStringVariableAsDouble
2599  *  Purpose  :
2600  */
2601 //============================================================================
2602 void SALOMEDSImpl_Study::SetStringVariableAsDouble(const std::string& theVarName,
2603                                                    const double theValue,
2604                                                    const SALOMEDSImpl_GenericVariable::VariableTypes theType)
2605 {
2606   SALOMEDSImpl_GenericVariable* aGVar = GetVariable(theVarName);
2607   if(SALOMEDSImpl_ScalarVariable* aSVar = dynamic_cast<SALOMEDSImpl_ScalarVariable*>(aGVar))
2608     aSVar->setValue(theValue);
2609 }
2610
2611 //============================================================================
2612 /*! Function : GetReal
2613  *  Purpose  :
2614  */
2615 //============================================================================
2616 double SALOMEDSImpl_Study::GetVariableValue(const std::string& theVarName)
2617 {
2618   SALOMEDSImpl_GenericVariable* aGVar = GetVariable(theVarName);
2619
2620   if(aGVar != NULL )
2621     if(SALOMEDSImpl_ScalarVariable* aSVar = dynamic_cast<SALOMEDSImpl_ScalarVariable*>(aGVar))
2622       return aSVar->getValue();
2623
2624   return 0;
2625 }
2626
2627 //============================================================================
2628 /*! Function : GetString
2629  *  Purpose  :
2630  */
2631 //============================================================================
2632 std::string SALOMEDSImpl_Study::GetStringVariableValue(const std::string& theVarName)
2633 {
2634   SALOMEDSImpl_GenericVariable* aGVar = GetVariable(theVarName);
2635
2636   if(aGVar != NULL )
2637     if(SALOMEDSImpl_ScalarVariable* aSVar = dynamic_cast<SALOMEDSImpl_ScalarVariable*>(aGVar))
2638       return aSVar->getStringValue();
2639
2640   return 0;
2641 }
2642
2643 //============================================================================
2644 /*! Function : IsTypeOf
2645  *  Purpose  :
2646  */
2647 //============================================================================
2648 bool SALOMEDSImpl_Study::IsTypeOf(const std::string& theVarName,
2649                                   SALOMEDSImpl_GenericVariable::
2650                                   VariableTypes theType) const
2651 {
2652   SALOMEDSImpl_GenericVariable* aGVar = GetVariable(theVarName);
2653
2654   if(aGVar != NULL )
2655     return aGVar->Type() == theType;
2656
2657   return false;
2658 }
2659
2660 //============================================================================
2661 /*! Function : IsVariable
2662  *  Purpose  :
2663  */
2664 //============================================================================
2665 bool SALOMEDSImpl_Study::IsVariable(const std::string& theVarName) const
2666 {
2667   SALOMEDSImpl_GenericVariable* aGVar = GetVariable(theVarName);
2668   return (aGVar != NULL);
2669 }
2670
2671 //============================================================================
2672 /*! Function : GetVariableNames
2673  *  Purpose  :
2674  */
2675 //============================================================================
2676 std::vector<std::string> SALOMEDSImpl_Study::GetVariableNames() const
2677 {
2678   std::vector<std::string> aResult;
2679
2680   for(int i = 0; i < myNoteBookVars.size(); i++)
2681     aResult.push_back(myNoteBookVars[i]->Name());
2682
2683   return aResult;
2684 }
2685
2686 //============================================================================
2687 /*! Function : AddVariable
2688  *  Purpose  :
2689  */
2690 //============================================================================
2691 void SALOMEDSImpl_Study::AddVariable(SALOMEDSImpl_GenericVariable* theVariable)
2692 {
2693   myNoteBookVars.push_back(theVariable);
2694 }
2695
2696 //============================================================================
2697 /*! Function : AddVariable
2698  *  Purpose  :
2699  */
2700 //============================================================================
2701 SALOMEDSImpl_GenericVariable* SALOMEDSImpl_Study::GetVariable(const std::string& theName) const
2702 {
2703   SALOMEDSImpl_GenericVariable* aResult = NULL;
2704   for(int i = 0; i < myNoteBookVars.size();i++) {
2705     if(theName.compare(myNoteBookVars[i]->Name()) == 0) {
2706       aResult = myNoteBookVars[i];
2707       break;
2708     }
2709   }
2710   return aResult;
2711 }
2712
2713 //============================================================================
2714 /*! Function : RemoveVariable
2715  *  Purpose  :
2716  */
2717 //============================================================================
2718 bool SALOMEDSImpl_Study::RemoveVariable(const std::string& theVarName)
2719 {
2720   SALOMEDSImpl_GenericVariable* aVariable = GetVariable( theVarName );
2721   if( !aVariable )
2722     return false;
2723
2724   std::string aValue = aVariable->SaveToScript();
2725   ReplaceVariableAttribute( theVarName, aValue );
2726
2727   std::vector<SALOMEDSImpl_GenericVariable*>::iterator it = myNoteBookVars.begin(), itEnd = myNoteBookVars.end();
2728   for( ; it != itEnd; it++ )
2729   {
2730     SALOMEDSImpl_GenericVariable* aVariableRef = *it;
2731     if( aVariableRef && theVarName.compare( aVariableRef->Name() ) == 0 )
2732     {
2733       myNoteBookVars.erase( it );
2734       Modify();
2735       break;
2736     }
2737   }
2738
2739   return true;
2740 }
2741
2742 //============================================================================
2743 /*! Function : RenameVariable
2744  *  Purpose  :
2745  */
2746 //============================================================================
2747 bool SALOMEDSImpl_Study::RenameVariable(const std::string& theVarName, const std::string& theNewVarName)
2748 {
2749   SALOMEDSImpl_GenericVariable* aVariable = GetVariable( theVarName );
2750   if( !aVariable )
2751     return false;
2752
2753   ReplaceVariableAttribute( theVarName, theNewVarName );
2754
2755   std::vector<SALOMEDSImpl_GenericVariable*>::iterator it = myNoteBookVars.begin(), itEnd = myNoteBookVars.end();
2756   for( ; it != itEnd; it++ )
2757   {
2758     SALOMEDSImpl_GenericVariable* aVariableRef = *it;
2759     if( aVariableRef && theVarName.compare( aVariableRef->Name() ) == 0 )
2760     {
2761       aVariableRef->setName( theNewVarName );
2762       Modify();
2763       break;
2764     }
2765   }
2766
2767   return true;
2768 }
2769
2770 //============================================================================
2771 /*! Function : IsVariableUsed
2772  *  Purpose  :
2773  */
2774 //============================================================================
2775 bool SALOMEDSImpl_Study::IsVariableUsed(const std::string& theVarName)
2776 {
2777   return FindVariableAttribute( theVarName );
2778 }
2779
2780 //============================================================================
2781 /*! Function : FindVariableAttribute
2782  *  Purpose  :
2783  */
2784 //============================================================================
2785 bool SALOMEDSImpl_Study::FindVariableAttribute(SALOMEDSImpl_StudyBuilder* theStudyBuilder,
2786                                                SALOMEDSImpl_SObject theSObject,
2787                                                const std::string& theName)
2788 {
2789   SALOMEDSImpl_ChildIterator anIter = NewChildIterator( theSObject );
2790   for( ; anIter.More(); anIter.Next() )
2791     if( FindVariableAttribute( theStudyBuilder, anIter.Value(), theName ) )
2792       return true;
2793
2794   DF_Attribute* anAttr;
2795   if( theStudyBuilder->FindAttribute( theSObject, anAttr, "AttributeString" ) )
2796   {
2797     if( SALOMEDSImpl_AttributeString* aStringAttr = ( SALOMEDSImpl_AttributeString* )anAttr )
2798     {
2799       std::string aString = aStringAttr->Value();
2800
2801       std::vector< std::vector<std::string> > aSections = ParseVariables( aString );
2802       for( int i = 0, n = aSections.size(); i < n; i++ )
2803       {
2804         std::vector<std::string> aVector = aSections[i];
2805         for( int j = 0, m = aVector.size(); j < m; j++ )
2806         {
2807           std::string aStr = aVector[j];
2808           if( aStr.compare( theName ) == 0 )
2809             return true;
2810         }
2811       }
2812     }
2813   }
2814   return false;
2815 }
2816
2817 //============================================================================
2818 /*! Function : FindVariableAttribute
2819  *  Purpose  :
2820  */
2821 //============================================================================
2822 bool SALOMEDSImpl_Study::FindVariableAttribute(const std::string& theName)
2823 {
2824   SALOMEDSImpl_StudyBuilder* aStudyBuilder = NewBuilder();
2825   SALOMEDSImpl_SComponentIterator aCompIter = NewComponentIterator();
2826   for( ; aCompIter.More(); aCompIter.Next() )
2827   {
2828     SALOMEDSImpl_SObject aComp = aCompIter.Value();
2829     if( FindVariableAttribute( aStudyBuilder, aComp, theName ) )
2830       return true;
2831   }
2832   return false;
2833 }
2834
2835 //============================================================================
2836 /*! Function : ReplaceVariableAttribute
2837  *  Purpose  :
2838  */
2839 //============================================================================
2840 void SALOMEDSImpl_Study::ReplaceVariableAttribute(SALOMEDSImpl_StudyBuilder* theStudyBuilder,
2841                                                   SALOMEDSImpl_SObject theSObject,
2842                                                   const std::string& theSource,
2843                                                   const std::string& theDest)
2844 {
2845   SALOMEDSImpl_ChildIterator anIter = NewChildIterator( theSObject );
2846   for( ; anIter.More(); anIter.Next() )
2847     ReplaceVariableAttribute( theStudyBuilder, anIter.Value(), theSource, theDest );
2848
2849   DF_Attribute* anAttr;
2850   if( theStudyBuilder->FindAttribute( theSObject, anAttr, "AttributeString" ) )
2851   {
2852     if( SALOMEDSImpl_AttributeString* aStringAttr = ( SALOMEDSImpl_AttributeString* )anAttr )
2853     {
2854       bool isChanged = false;
2855       std::string aNewString, aCurrentString = aStringAttr->Value();
2856
2857       std::vector< std::vector<std::string> > aSections = ParseVariables( aCurrentString );
2858       for( int i = 0, n = aSections.size(); i < n; i++ )
2859       {
2860         std::vector<std::string> aVector = aSections[i];
2861         for( int j = 0, m = aVector.size(); j < m; j++ )
2862         {
2863           std::string aStr = aVector[j];
2864           if( aStr.compare( theSource ) == 0 )
2865           {
2866             isChanged = true;
2867             aStr = theDest;
2868           }
2869
2870           aNewString.append( aStr );
2871           if( j != m - 1 )
2872             aNewString.append( ":" );
2873         }
2874         if( i != n - 1 )
2875           aNewString.append( "|" );
2876       }
2877
2878       if( isChanged )
2879         aStringAttr->SetValue( aNewString );
2880     }
2881   }
2882 }
2883
2884 //============================================================================
2885 /*! Function : ReplaceVariableAttribute
2886  *  Purpose  :
2887  */
2888 //============================================================================
2889 void SALOMEDSImpl_Study::ReplaceVariableAttribute(const std::string& theSource, const std::string& theDest)
2890 {
2891   SALOMEDSImpl_StudyBuilder* aStudyBuilder = NewBuilder();
2892   SALOMEDSImpl_SComponentIterator aCompIter = NewComponentIterator();
2893   for( ; aCompIter.More(); aCompIter.Next() )
2894   {
2895     SALOMEDSImpl_SObject aComp = aCompIter.Value();
2896     ReplaceVariableAttribute( aStudyBuilder, aComp, theSource, theDest );
2897   }
2898 }
2899
2900 //============================================================================
2901 /*! Function : ParseVariables
2902  *  Purpose  :
2903  */
2904 //============================================================================
2905 std::vector< std::vector< std::string > > SALOMEDSImpl_Study::ParseVariables(const std::string& theVariables) const
2906 {
2907   return SALOMEDSImpl_Tool::splitStringWithEmpty( theVariables, OPERATION_SEPARATOR, VARIABLE_SEPARATOR );
2908 }
2909
2910 //============================================================================
2911 /*! Function : EnableUseCaseAutoFilling
2912  *  Purpose  :
2913  */
2914 //============================================================================
2915 void SALOMEDSImpl_Study::EnableUseCaseAutoFilling(bool isEnabled)
2916 {
2917   _errorCode = ""; _autoFill = isEnabled;
2918   if(isEnabled) {
2919     _builder->SetOnAddSObject(_cb);
2920     _builder->SetOnRemoveSObject(_cb);
2921   }
2922   else {
2923     _builder->SetOnAddSObject(NULL);
2924     _builder->SetOnRemoveSObject(NULL);
2925   }
2926 }
2927
2928 //============================================================================
2929 /*! Function : GetIORs
2930  *  Purpose  :
2931  */
2932 //============================================================================
2933 std::vector<std::string> SALOMEDSImpl_Study::GetIORs()
2934 {
2935   std::vector<std::string> anIORs;
2936   std::map<std::string, DF_Label>::const_iterator MI;
2937   for(MI = myIORLabels.begin(); MI!=myIORLabels.end(); MI++)
2938     anIORs.push_back(MI->first);
2939
2940   return anIORs;
2941 }
2942
2943 //============================================================================
2944 /*! Function : addSO_Notification
2945  *  Purpose  : This function tells all the observers that a SO has been added
2946  */
2947 //============================================================================
2948 bool SALOMEDSImpl_Study::addSO_Notification (const SALOMEDSImpl_SObject& theSObject)
2949 {
2950   if(_notifier)
2951     return _notifier->addSO_Notification(theSObject);
2952   else
2953     return false;
2954 }
2955
2956 //============================================================================
2957 /*! Function : removeSO_Notification
2958  *  Purpose  : This function tells all the observers that a SO has been removed
2959  */
2960 //============================================================================
2961 bool SALOMEDSImpl_Study::removeSO_Notification (const SALOMEDSImpl_SObject& theSObject)
2962 {
2963   if(_notifier)
2964     return _notifier->removeSO_Notification(theSObject);
2965   else
2966     return false;
2967 }
2968
2969 //============================================================================
2970 /*! Function : modifySO_Notification
2971  *  Purpose  : This function tells all the observers that a SO has been modified and
2972                pass the mofification reason
2973  */
2974 //============================================================================
2975 bool SALOMEDSImpl_Study::modifySO_Notification (const SALOMEDSImpl_SObject& theSObject, int reason)
2976 {
2977   if(_notifier)
2978     return _notifier->modifySO_Notification(theSObject, reason);
2979   else
2980     return false;
2981 }
2982
2983 //============================================================================
2984 /*! Function : setNotifier
2985  *  Purpose  : register a notifier
2986  */
2987 //============================================================================
2988 void SALOMEDSImpl_Study::setNotifier(SALOMEDSImpl_AbstractCallback* notifier)
2989 {
2990   _notifier=notifier;
2991 }
2992
2993 static SALOMEDSImpl_AbstractCallback* & getGenObjRegister( DF_Document* doc )
2994 {
2995   static std::vector< SALOMEDSImpl_AbstractCallback* > _genObjRegVec;
2996   if ( doc->GetDocumentID() >= (int)_genObjRegVec.size() )
2997     _genObjRegVec.resize( doc->GetDocumentID() + 1, 0 );
2998   return _genObjRegVec[ doc->GetDocumentID() ];
2999 }
3000
3001 //================================================================================
3002 /*!
3003  * \brief Stores theRegister
3004  */
3005 //================================================================================
3006
3007 void SALOMEDSImpl_Study::setGenObjRegister(SALOMEDSImpl_AbstractCallback* theRegister)
3008 {
3009   getGenObjRegister( _doc ) = theRegister;
3010 }
3011
3012 //================================================================================
3013 /*!
3014  * \brief Indirectly invokes GenericObj_i::Register()
3015  */
3016 //================================================================================
3017
3018 void SALOMEDSImpl_Study::RegisterGenObj  (const std::string& theIOR, DF_Label label)
3019 {
3020   if ( SALOMEDSImpl_AbstractCallback* goRegister = getGenObjRegister( label.GetDocument() ))
3021     goRegister->RegisterGenObj( theIOR );
3022 }
3023
3024 //================================================================================
3025 /*!
3026  * \brief Indirectly invokes GenericObj_i::UnRegister()
3027  */
3028 //================================================================================
3029
3030 void SALOMEDSImpl_Study::UnRegisterGenObj(const std::string& theIOR, DF_Label label)
3031 {
3032   if ( SALOMEDSImpl_AbstractCallback* goRegister = getGenObjRegister( label.GetDocument() ))
3033     goRegister->UnRegisterGenObj( theIOR );
3034 }
3035
3036 //#######################################################################################################
3037 //#                                     STATIC PRIVATE FUNCTIONS
3038 //#######################################################################################################
3039
3040 //============================================================================
3041 /*! Function : SaveAttributes
3042  *  Purpose  : Save attributes for object
3043  */
3044 //============================================================================
3045 static void SaveAttributes(const SALOMEDSImpl_SObject& aSO, HDFgroup *hdf_group_sobject)
3046 {
3047   hdf_size size[1];
3048   std::vector<DF_Attribute*> attrList = aSO.GetLabel().GetAttributes();
3049   DF_Attribute* anAttr = NULL;
3050   for(int i = 0, len = attrList.size(); i<len; i++) {
3051     anAttr = attrList[i];
3052     //The following attributes are not supposed to be written to the file
3053     std::string type = SALOMEDSImpl_GenericAttribute::Impl_GetType(anAttr);
3054     if(type == std::string("AttributeIOR")) continue; //IOR attribute is not saved
3055     std::string aSaveStr =anAttr->Save();
3056     //cout << "Saving: " << aSO.GetID() << " type: "<< type<<"|" << endl;
3057     size[0] = (hdf_int32) strlen(aSaveStr.c_str()) + 1;
3058     HDFdataset *hdf_dataset = new HDFdataset((char*)type.c_str(), hdf_group_sobject, HDF_STRING,size, 1);
3059     hdf_dataset->CreateOnDisk();
3060     hdf_dataset->WriteOnDisk((char*)aSaveStr.c_str());
3061     hdf_dataset->CloseOnDisk();
3062     hdf_dataset=0; //will be deleted by hdf_sco_group destructor
3063   }
3064 }
3065
3066 //===========================================================================
3067 //Function : ReadAttributes
3068 //===========================================================================
3069 static void ReadAttributes(SALOMEDSImpl_Study* theStudy,
3070                            const SALOMEDSImpl_SObject& aSO,
3071                            HDFdataset* hdf_dataset)
3072 {
3073   hdf_dataset->OpenOnDisk();
3074
3075   DF_Attribute* anAttr = NULL;
3076   char* current_string = new char[hdf_dataset->GetSize()+1];
3077   hdf_dataset->ReadFromDisk(current_string);
3078   //cout << "Reading attr type = " << hdf_dataset->GetName() << "  SO = " << aSO.GetID() << endl;
3079   if (!strcmp(hdf_dataset->GetName(),"COMPONENTDATATYPE")) {
3080     anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, "AttributeComment");
3081   }
3082   else if (!strcmp(hdf_dataset->GetName(),"AttributeReference") ||
3083            !strcmp(hdf_dataset->GetName(),"Reference")) { // Old format maintenance
3084     theStudy->NewBuilder()->Addreference(aSO, theStudy->CreateObjectID(current_string));
3085     delete [] (current_string);
3086     hdf_dataset->CloseOnDisk();
3087     return;
3088   }
3089   else {
3090     anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, hdf_dataset->GetName());
3091   }
3092
3093   if (anAttr) {
3094     anAttr->Load(current_string);
3095   }
3096
3097   delete [] (current_string);
3098   hdf_dataset->CloseOnDisk();
3099 }
3100
3101 //============================================================================
3102 //Function : BuildlTree
3103 //============================================================================
3104 static void BuildTree (SALOMEDSImpl_Study* theStudy, HDFgroup* hdf_current_group)
3105 {
3106   hdf_current_group->OpenOnDisk();
3107   SALOMEDSImpl_SObject aSO;
3108   char* Entry = hdf_current_group->GetName();
3109   if (strcmp(Entry,"STUDY_STRUCTURE") == 0) {
3110     aSO = theStudy->CreateObjectID("0:1");
3111   }
3112   else {
3113     aSO = theStudy->CreateObjectID(Entry);
3114   }
3115
3116   char name[HDF_NAME_MAX_LEN+1];
3117   int nbsons = hdf_current_group->nInternalObjects();
3118   for (int i=0; i<nbsons; i++) {
3119     hdf_current_group->InternalObjectIndentify(i,name);
3120     if (strncmp(name, "INTERNAL_COMPLEX",16) == 0) continue;
3121     hdf_object_type type = hdf_current_group->InternalObjectType(name);
3122
3123     if (type == HDF_DATASET) {
3124       HDFdataset* new_dataset = new HDFdataset(name,hdf_current_group);
3125       ReadAttributes(theStudy,aSO,new_dataset);
3126       new_dataset = 0; // will be deleted by father destructor
3127     }
3128     else if (type == HDF_GROUP)   {
3129       HDFgroup* new_group = new HDFgroup(name,hdf_current_group);
3130       BuildTree (theStudy, new_group);
3131       new_group = 0; // will be deleted by father destructor
3132     }
3133   }
3134   hdf_current_group->CloseOnDisk();
3135 }
3136
3137
3138 //============================================================================
3139 //Function : Translate_IOR_to_persistentID
3140 //============================================================================
3141 static void Translate_IOR_to_persistentID (const SALOMEDSImpl_SObject& so,
3142                                            SALOMEDSImpl_Driver*        engine,
3143                                            bool                        isMultiFile,
3144                                            bool                        isASCII)
3145 {
3146   DF_ChildIterator itchild(so.GetLabel());
3147   std::string ior_string,  persistent_string, curid;
3148
3149   for (; itchild.More(); itchild.Next()) {
3150     SALOMEDSImpl_SObject current = SALOMEDSImpl_Study::SObject(itchild.Value());
3151     SALOMEDSImpl_AttributeIOR* IOR = NULL;
3152     if ((IOR=(SALOMEDSImpl_AttributeIOR*)current.GetLabel().FindAttribute(SALOMEDSImpl_AttributeIOR::GetID()))) {
3153       ior_string = IOR->Value();
3154
3155       persistent_string = engine->IORToLocalPersistentID (current, ior_string, isMultiFile, isASCII);
3156       SALOMEDSImpl_AttributePersistentRef::Set(current.GetLabel(), persistent_string);
3157     }
3158     Translate_IOR_to_persistentID (current, engine, isMultiFile, isASCII);
3159   }
3160 }
3161
3162 void ReadNoteBookVariables(SALOMEDSImpl_Study* theStudy, HDFgroup* theGroup)
3163 {
3164   if(!theGroup)
3165     return;
3166
3167   HDFgroup* new_group =0;
3168   HDFdataset* new_dataset =0;
3169
3170   char aVarName[HDF_NAME_MAX_LEN+1];
3171   char *currentVarType = 0;
3172   char *currentVarValue = 0;
3173   char *currentVarIndex = 0;
3174   int order = 0;
3175   //Open HDF group with notebook variables
3176   theGroup->OpenOnDisk();
3177
3178   //Get Nb of variables
3179   int aNbVars = theGroup->nInternalObjects();
3180
3181   std::map<int,SALOMEDSImpl_GenericVariable*> aVarsMap;
3182
3183   for( int iVar=0;iVar < aNbVars;iVar++ ) {
3184     theGroup->InternalObjectIndentify(iVar,aVarName);
3185     hdf_object_type type = theGroup->InternalObjectType(aVarName);
3186     if(type == HDF_GROUP) {
3187
3188       //Read Variable
3189       new_group = new HDFgroup(aVarName,theGroup);
3190       new_group->OpenOnDisk();
3191
3192       //Read Type
3193       new_dataset = new HDFdataset("VARIABLE_TYPE",new_group);
3194       new_dataset->OpenOnDisk();
3195       currentVarType = new char[new_dataset->GetSize()+1];
3196       new_dataset->ReadFromDisk(currentVarType);
3197       new_dataset->CloseOnDisk();
3198       new_dataset = 0; //will be deleted by hdf_sco_group destructor
3199
3200       //Read Order
3201       if(new_group->ExistInternalObject("VARIABLE_INDEX")) {
3202         new_dataset = new HDFdataset("VARIABLE_INDEX",new_group);
3203         new_dataset->OpenOnDisk();
3204         currentVarIndex = new char[new_dataset->GetSize()+1];
3205         new_dataset->ReadFromDisk(currentVarIndex);
3206         new_dataset->CloseOnDisk();
3207         new_dataset = 0; //will be deleted by hdf_sco_group destructor
3208         order = atoi(currentVarIndex);
3209         delete [] currentVarIndex;
3210       }
3211       else
3212         order = iVar;
3213
3214       //Read Value
3215       new_dataset = new HDFdataset("VARIABLE_VALUE",new_group);
3216       new_dataset->OpenOnDisk();
3217       currentVarValue = new char[new_dataset->GetSize()+1];
3218       new_dataset->ReadFromDisk(currentVarValue);
3219       new_dataset->CloseOnDisk();
3220       new_dataset = 0; //will be deleted by hdf_sco_group destructor
3221
3222       new_group->CloseOnDisk();
3223       new_group = 0;  //will be deleted by hdf_sco_group destructor
3224
3225       SALOMEDSImpl_GenericVariable::VariableTypes aVarType =
3226         SALOMEDSImpl_GenericVariable::String2VariableType(std::string(currentVarType));
3227       delete [] currentVarType;
3228
3229       //Create variable and add it in the study
3230       SALOMEDSImpl_GenericVariable* aVariable =
3231         new SALOMEDSImpl_ScalarVariable(aVarType,std::string(aVarName));
3232       aVariable->Load(std::string(currentVarValue));
3233       aVarsMap.insert(std::make_pair(order,aVariable));
3234       delete [] currentVarValue;
3235     }
3236   }
3237
3238   std::map<int,SALOMEDSImpl_GenericVariable*>::const_iterator it= aVarsMap.begin();
3239   for(;it!=aVarsMap.end();it++)
3240     theStudy->AddVariable((*it).second);
3241
3242   theGroup->CloseOnDisk();
3243 }