Salome HOME
bos #17005 [CEA][Windows] cannot save study.
[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
805 #ifdef WIN32    
806         // Force removing readonly attribute from a file under Windows, because of a but in the HDF
807     std::string aReadOlnyRmCmd = "attrib -r \"" + aStudyTmpDir + std::string(buffer)+ "\" > nul 2>&1";
808 #ifdef UNICODE
809     std::wstring awReadOlnyRmCmd = Kernel_Utils::utf8_decode_s(aReadOlnyRmCmd);
810     _wsystem(awReadOlnyRmCmd.c_str());
811 #else  
812     system(aReadOlnyRmCmd.c_str());
813 #endif
814
815     aCmd = "move /Y \"" + aStudyTmpDir + std::string(buffer) + "\" \"" + SALOMEDSImpl_Tool::GetDirFromPath(aStudyUrl) +"\" > nul 2>&1";
816 #else
817     aCmd = "mv -f \"" + aStudyTmpDir + std::string(buffer) + "\" \"" + SALOMEDSImpl_Tool::GetDirFromPath(aStudyUrl)+"\"";
818 #endif
819 #if defined(WIN32) && defined(UNICODE)
820     std::wstring awCmd = Kernel_Utils::utf8_decode_s(aCmd);
821     errors = _wsystem(awCmd.c_str());
822 #else  
823     errors = system(aCmd.c_str());
824 #endif
825   }
826
827   delete []buffer;
828   fclose(fp);
829
830   // Perform cleanup
831 #ifdef WIN32
832 #ifdef UNICODE
833   std::wstring aTmpFileToDelete = Kernel_Utils::utf8_decode_s(aTmpFile);
834  
835 #else
836   std::string aTmpFileToDelete = aTmpFile;
837 #endif
838   DeleteFile(aTmpFileToDelete.c_str());
839 #else
840   unlink(aTmpFile.c_str());
841 #endif
842
843 #ifdef WIN32
844 #ifdef UNICODE
845   std::wstring aTmpFileDirToDelete = Kernel_Utils::utf8_decode_s( aTmpFileDir );
846   std::wstring aStudyTmpDirToDelete = Kernel_Utils::utf8_decode_s( aStudyTmpDir );
847 #else
848   std::string aTmpFileDirToDelete = aTmpFileDir;
849   std::string aStudyTmpDirToDelete = aStudyTmpDir;
850 #endif  
851   RemoveDirectory( aTmpFileDirToDelete.c_str() );
852   RemoveDirectory( aStudyTmpDirToDelete.c_str() );
853 #else
854   rmdir(aTmpFileDir.c_str());
855   rmdir(aStudyTmpDir.c_str());
856 #endif
857
858   if ( !errors ) {
859     // VSR: finally, if all is done without errors, mark study as Saved
860     IsSaved(true);
861   }
862
863   std::map<std::string, SALOMEDSImpl_Driver*>::iterator n2dr = aMapTypeDriver.begin();
864   for ( ; n2dr != aMapTypeDriver.end(); ++n2dr )
865     delete n2dr->second;
866
867   return !errors;
868 }
869
870 //============================================================================
871 /*! Function : Impl_SaveObject
872  *  Purpose  :
873  */
874 //============================================================================
875 bool SALOMEDSImpl_Study::Impl_SaveObject(const SALOMEDSImpl_SObject& SC,
876                                          HDFgroup *hdf_group_datatype)
877 {
878   _errorCode = "";
879
880   // Write in group hdf_group_datatype all information of SObject SC
881   // Iterative function to parse all SObjects under a SComponent
882
883   HDFgroup *hdf_group_sobject = 0;
884
885   DF_ChildIterator itchild(SC.GetLabel());
886   for (; itchild.More(); itchild.Next()) {
887     // mpv: don't save empty labels
888     std::vector<DF_Attribute*> attr = itchild.Value().GetAttributes();
889     if (attr.size() == 0) {  //No attributes on the label
890       DF_ChildIterator subchild(itchild.Value());
891       if (!subchild.More()) {
892         continue;
893       }
894       subchild.Init(itchild.Value(), true);
895       bool anEmpty = true;
896       for (; subchild.More() && anEmpty; subchild.Next()) {
897         std::vector<DF_Attribute*> attr2 = subchild.Value().GetAttributes();
898         if (attr2.size()) {
899           anEmpty = false;  //There are attributes on the child label
900           break;
901         }
902       }
903       if (anEmpty) continue;
904     }
905
906     SALOMEDSImpl_SObject SO = SALOMEDSImpl_Study::SObject(itchild.Value());
907
908     std::string scoid = SO.GetID();
909     hdf_group_sobject = new HDFgroup(scoid.c_str(), hdf_group_datatype);
910     hdf_group_sobject->CreateOnDisk();
911     SaveAttributes(SO, hdf_group_sobject);
912     Impl_SaveObject(SO, hdf_group_sobject);
913     hdf_group_sobject->CloseOnDisk();
914     hdf_group_sobject =0; // will be deleted by father hdf object destructor
915   }
916   return true;
917 }
918
919 //============================================================================
920 /*! Function : CanCopy
921  *  Purpose  :
922  */
923 //============================================================================
924 bool SALOMEDSImpl_Study::CanCopy(const SALOMEDSImpl_SObject& theObject,
925                                  SALOMEDSImpl_Driver* theEngine)
926 {
927   _errorCode = "";
928   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
929   if (!aComponent) return false;
930   if (aComponent.GetLabel() == theObject.GetLabel()) return false;
931   std::string IOREngine;
932   if (!aComponent.ComponentIOR(IOREngine)) return false;
933   if (theEngine == NULL) return false;
934   return theEngine->CanCopy(theObject);
935 }
936
937 //============================================================================
938 /*! Function : CopyLabel
939  *  Purpose  :
940  */
941 //============================================================================
942 bool SALOMEDSImpl_Study::CopyLabel(SALOMEDSImpl_Driver* theEngine,
943                                    const int theSourceStartDepth,
944                                    const DF_Label& theSource,
945                                    const DF_Label& theDestinationMain)
946 {
947   _errorCode = "";
948
949   int a;
950   DF_Label aTargetLabel = theDestinationMain;
951   DF_Label aAuxTargetLabel = theDestinationMain.Father().FindChild(2);
952   for(a = theSource.Depth() - theSourceStartDepth; a > 0 ; a--) {
953     DF_Label aSourceLabel = theSource;
954     for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
955     aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
956     aAuxTargetLabel = aAuxTargetLabel.FindChild(aSourceLabel.Tag());
957   }
958   // iterate attributes
959   std::vector<DF_Attribute*> attrList = theSource.GetAttributes();
960   for(int i = 0, len = attrList.size(); i<len; i++) {
961     DF_Attribute* anAttr = attrList[i];
962     std::string type = SALOMEDSImpl_GenericAttribute::Impl_GetType(anAttr);
963     if (type.substr(0, 17) == std::string("AttributeTreeNode")) continue; // never copy tree node attribute
964     if (type == std::string("AttributeTarget")) continue; // and target attribute
965
966     if (type == std::string("AttributeReference")) { // reference copied as Comment in aux tree
967       DF_Label aReferenced = dynamic_cast<SALOMEDSImpl_AttributeReference*>(anAttr)->Get();
968       std::string anEntry = aReferenced.Entry();
969       // store the value of name attribute of referenced label
970       SALOMEDSImpl_AttributeName* aNameAttribute;
971       if ((aNameAttribute=(SALOMEDSImpl_AttributeName*)aReferenced.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
972         anEntry += " ";
973         anEntry += aNameAttribute->Value();
974       }
975       SALOMEDSImpl_AttributeComment::Set(aAuxTargetLabel, anEntry);
976       continue;
977     }
978
979     if (type == std::string("AttributeIOR")) { // IOR => ID and TMPFile of Engine
980       std::string anEntry = theSource.Entry();
981       SALOMEDSImpl_SObject aSO = FindObjectID(anEntry);
982       int anObjID;
983       long aLen;
984       SALOMEDSImpl_TMPFile* aStream = theEngine->CopyFrom(aSO, anObjID, aLen);
985       std::string aResStr("");
986       for(a = 0; a < aLen; a++) {
987         aResStr += (char)(aStream->Get(a));
988       }
989
990       if(aStream) delete aStream;
991
992       SALOMEDSImpl_AttributeInteger::Set(aAuxTargetLabel, anObjID);
993       SALOMEDSImpl_AttributeName::Set(aAuxTargetLabel, aResStr);
994       continue;
995     }
996     DF_Attribute* aNewAttribute = anAttr->NewEmpty();
997     aTargetLabel.AddAttribute(aNewAttribute);
998     anAttr->Paste(aNewAttribute);
999   }
1000
1001   return true;
1002 }
1003
1004 //============================================================================
1005 /*! Function : Copy
1006  *  Purpose  :
1007  */
1008 //============================================================================
1009 bool SALOMEDSImpl_Study::Copy(const SALOMEDSImpl_SObject& theObject,
1010                                     SALOMEDSImpl_Driver* theEngine)
1011 {
1012   _errorCode = "";
1013
1014   // adoptation for alliances datamodel copy: without IOR attributes !!!
1015   bool aStructureOnly; // copy only SObjects and attributes without component help
1016   aStructureOnly = !theObject.GetLabel().IsAttribute(SALOMEDSImpl_AttributeIOR::GetID());
1017
1018   if (!_doc) {
1019     _errorCode = "Document is null";
1020     return false;
1021   }
1022
1023   //Clear the clipboard
1024   _clipboard->Main().Root().ForgetAllAttributes(true);
1025   _appli->Close(_clipboard);
1026   _clipboard = _appli->NewDocument("SALOME_STUDY");
1027
1028   // set component data type to the name attribute of root label
1029   if (!aStructureOnly) {
1030     SALOMEDSImpl_AttributeComment::Set(_clipboard->Main().Root(),
1031                                        theEngine->ComponentDataType());
1032   }
1033   // iterate all theObject's label children
1034   DF_Label aStartLabel = theObject.GetLabel();
1035   int aSourceStartDepth = aStartLabel.Depth();
1036
1037   // copy main source label
1038   CopyLabel(theEngine, aSourceStartDepth, aStartLabel, _clipboard->Main());
1039
1040   // copy all subchildren of the main source label (all levels)
1041   DF_ChildIterator anIterator(aStartLabel, true);
1042   for(; anIterator.More(); anIterator.Next()) {
1043     CopyLabel(theEngine, aSourceStartDepth, anIterator.Value(), _clipboard->Main());
1044   }
1045
1046   return true;
1047 }
1048
1049 //============================================================================
1050 /*! Function : CanPaste
1051  *  Purpose  :
1052  */
1053 //============================================================================
1054 bool SALOMEDSImpl_Study::CanPaste(const SALOMEDSImpl_SObject& theObject,
1055                                          SALOMEDSImpl_Driver* theEngine)
1056 {
1057   _errorCode = "";
1058
1059   if (!_clipboard) {
1060     _errorCode = "Clipboard is null";
1061     return false;
1062   }
1063
1064   SALOMEDSImpl_AttributeComment* aCompName = NULL;
1065   if (!(aCompName=(SALOMEDSImpl_AttributeComment*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID()))) {
1066     _errorCode = "Clipboard has no component type";
1067     return false;
1068   }
1069   SALOMEDSImpl_AttributeInteger* anObjID;
1070   if (!(anObjID=(SALOMEDSImpl_AttributeInteger*)_clipboard->Main().Father().FindChild(2).FindAttribute(SALOMEDSImpl_AttributeInteger::GetID()))) {
1071     _errorCode = "Clipboard has no object id";
1072     return false;
1073   }
1074   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
1075   if (!aComponent) {
1076     _errorCode = "Object doesn't belong to component";
1077     return false;
1078   }
1079
1080   std::string IOREngine;
1081   if (!aComponent.ComponentIOR(IOREngine)) {
1082     _errorCode = "component has no IOR";
1083     return false;
1084   }
1085   return theEngine->CanPaste(aCompName->Value(), anObjID->Value());
1086 }
1087
1088 //============================================================================
1089 /*! Function : PasteLabel
1090  *  Purpose  :
1091  */
1092 //============================================================================
1093 DF_Label SALOMEDSImpl_Study::PasteLabel(SALOMEDSImpl_Driver* theEngine,
1094                                         const DF_Label& theSource,
1095                                         const DF_Label& theDestinationStart,
1096                                         const bool isFirstElement)
1097 {
1098   _errorCode = "";
1099
1100   // get corresponding source, target and auxiliary labels
1101   DF_Label aTargetLabel = theDestinationStart;
1102
1103   DF_Label aAuxSourceLabel = theSource.Root().FindChild(2);
1104   int a;
1105   if (!isFirstElement) {
1106     for(a = theSource.Depth() - 1; a > 0 ; a--) {
1107       DF_Label aSourceLabel = theSource;
1108       for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
1109       aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
1110       aAuxSourceLabel = aAuxSourceLabel.FindChild(aSourceLabel.Tag());
1111     }
1112     SALOMEDSImpl_SObject so = GetSObject(aTargetLabel);
1113     addSO_Notification(so);
1114   }
1115
1116   // check auxiliary label for TMPFile => IOR
1117   SALOMEDSImpl_AttributeName* aNameAttribute = NULL;
1118   if ((aNameAttribute=(SALOMEDSImpl_AttributeName*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
1119     SALOMEDSImpl_AttributeInteger* anObjID = (SALOMEDSImpl_AttributeInteger*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeInteger::GetID());
1120     SALOMEDSImpl_AttributeComment* aComponentName = (SALOMEDSImpl_AttributeComment*)theSource.Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID());
1121     std::string aCompName = aComponentName->Value();
1122
1123     if (theEngine->CanPaste(aCompName, anObjID->Value())) {
1124       std::string aTMPStr = aNameAttribute->Value();
1125       int aLen = aTMPStr.size();
1126       unsigned char* aStream = NULL;
1127       if(aLen > 0) {
1128         aStream = new unsigned char[aLen+10];
1129         for(a = 0; a < aLen; a++) {
1130           aStream[a] = aTMPStr[a];
1131         }
1132       }
1133
1134       std::string anEntry = aTargetLabel.Entry();
1135       SALOMEDSImpl_SObject aPastedSO = FindObjectID(anEntry);
1136
1137       if (isFirstElement) {
1138         std::string aDestEntry = theEngine->PasteInto(aStream,
1139                                                       aLen,
1140                                                       anObjID->Value(),
1141                                                       aPastedSO.GetFatherComponent());
1142         aTargetLabel = DF_Label::Label(theDestinationStart, aDestEntry);
1143       } else
1144         theEngine->PasteInto(aStream, aLen, anObjID->Value(), aPastedSO);
1145
1146       if(aStream != NULL) delete []aStream;
1147     }
1148   }
1149
1150   // iterate attributes
1151   std::vector<DF_Attribute*> attrList = theSource.GetAttributes();
1152   for(int i = 0, len = attrList.size(); i<len; i++) {
1153     DF_Attribute* anAttr = attrList[i];
1154     if (aTargetLabel.FindAttribute(anAttr->ID())) {
1155       aTargetLabel.ForgetAttribute(anAttr->ID());
1156     }
1157     DF_Attribute* aNewAttribute = anAttr->NewEmpty();
1158     aTargetLabel.AddAttribute(aNewAttribute);
1159     anAttr->Paste(aNewAttribute);
1160   }
1161
1162   // check auxiliary label for Comment => reference or name attribute of the referenced object
1163   SALOMEDSImpl_AttributeComment* aCommentAttribute = NULL;
1164   if ((aCommentAttribute=(SALOMEDSImpl_AttributeComment*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeComment::GetID()))) {
1165     char * anEntry = new char[aCommentAttribute->Value().size() + 1];
1166     strcpy(anEntry, std::string(aCommentAttribute->Value()).c_str());
1167     char* aNameStart = strchr(anEntry, ' ');
1168     if (aNameStart) {
1169       *aNameStart = '\0';
1170       aNameStart++;
1171     }
1172     // copy to the same study, reanimate reference
1173     DF_Label aRefLabel = DF_Label::Label(aTargetLabel, anEntry);
1174     SALOMEDSImpl_AttributeReference::Set(aTargetLabel, aRefLabel);
1175     // target attributes structure support
1176     SALOMEDSImpl_AttributeTarget::Set(aRefLabel)->Add(SALOMEDSImpl_Study::SObject(aTargetLabel));
1177
1178     delete [] anEntry;
1179   }
1180
1181   return aTargetLabel;
1182 }
1183
1184 //============================================================================
1185 /*! Function : Paste
1186  *  Purpose  :
1187  */
1188 //============================================================================
1189 SALOMEDSImpl_SObject SALOMEDSImpl_Study::Paste(const SALOMEDSImpl_SObject& theObject,
1190                                                SALOMEDSImpl_Driver* theEngine)
1191 {
1192   _errorCode = "";
1193
1194   SALOMEDSImpl_SObject so;
1195
1196   // if study is locked, then paste can't be done
1197   if (GetProperties()->IsLocked()) {
1198     _errorCode = "LockProtection";
1199     throw LockProtection("LockProtection");
1200   }
1201
1202   // if there is no component name, then paste only SObjects and attributes: without component help
1203   SALOMEDSImpl_AttributeComment* aComponentName = NULL;
1204   bool aStructureOnly = !(aComponentName=(SALOMEDSImpl_AttributeComment*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID()));
1205
1206   // CAF document of current study usage
1207   if (!_doc) {
1208     _errorCode = "Document is null";
1209     return so;
1210   }
1211
1212   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
1213
1214   // fill root inserted SObject
1215   DF_Label aStartLabel;
1216   if (aStructureOnly) {
1217     DF_Label anObjectLabel = DF_Label::Label(_doc->Main(), theObject.GetID());
1218     aStartLabel = PasteLabel(theEngine, _clipboard->Main(), anObjectLabel, false);
1219   } else {
1220     DF_Label aComponentLabel = DF_Label::Label(_doc->Main(), aComponent.GetID());
1221     aStartLabel = PasteLabel(theEngine, _clipboard->Main(), aComponentLabel, true);
1222   }
1223
1224   // paste all sublebels
1225   DF_ChildIterator anIterator(_clipboard->Main(), true);
1226   for(; anIterator.More(); anIterator.Next()) {
1227     PasteLabel(theEngine, anIterator.Value(), aStartLabel, false);
1228   }
1229
1230   return SALOMEDSImpl_Study::SObject(aStartLabel);
1231 }
1232
1233 //============================================================================
1234 /*! Function : GetPersistentReference
1235  *  Purpose  : Get persistent reference of study (idem URL())
1236  */
1237 //============================================================================
1238 std::string SALOMEDSImpl_Study::GetPersistentReference()
1239 {
1240   _errorCode = "";
1241   return URL();
1242 }
1243
1244 //============================================================================
1245 /*! Function : IsEmpty
1246  *  Purpose  : Detect if study is empty
1247  */
1248 //============================================================================
1249 bool SALOMEDSImpl_Study::IsEmpty()
1250 {
1251   _errorCode = "";
1252   if (!_doc) return true;
1253   return _doc->IsEmpty();
1254 }
1255
1256 //============================================================================
1257 /*! Function : FindComponent
1258  *  Purpose  : Find a Component with ComponentDataType = aComponentName
1259  */
1260 //============================================================================
1261 SALOMEDSImpl_SComponent SALOMEDSImpl_Study::FindComponent (const std::string& aComponentName)
1262 {
1263   _errorCode = "";
1264   bool _find = false;
1265   std::string name;
1266   SALOMEDSImpl_SComponentIterator itcomp = NewComponentIterator();
1267   SALOMEDSImpl_SComponent compo;
1268
1269   for (; itcomp.More(); itcomp.Next()) {
1270     SALOMEDSImpl_SComponent SC = itcomp.Value();
1271     name = SC.ComponentDataType();
1272     if(aComponentName == name) {
1273       _find = true;
1274       return SC;
1275     }
1276   }
1277
1278   if(!_find)
1279     {
1280       _errorCode = "No component was found";
1281       return compo;
1282     }
1283   return compo;
1284 }
1285
1286 //============================================================================
1287 /*! Function : FindComponentID
1288  *  Purpose  : Find a Component from it's ID
1289  */
1290 //============================================================================
1291 SALOMEDSImpl_SComponent SALOMEDSImpl_Study::FindComponentID(const std::string& aComponentID)
1292 {
1293   _errorCode = "";
1294
1295   // Iterate on each components defined in the study
1296   // Get the component ID and compare with aComponentID
1297   bool _find = false;
1298   std::string ID;
1299   SALOMEDSImpl_SComponent compo;
1300
1301   SALOMEDSImpl_SComponentIterator itcomp = NewComponentIterator();
1302   for (; itcomp.More(); itcomp.Next()) {
1303     SALOMEDSImpl_SComponent SC = itcomp.Value();
1304     ID = SC.GetID();
1305     if(aComponentID == ID)
1306       {
1307         // ComponentID found
1308         _find = true;
1309         compo = SC;
1310       }
1311   }
1312   if(!_find)
1313     {
1314       _errorCode = "No component was found";
1315       compo = compo;
1316     }
1317
1318   return compo;
1319 }
1320
1321 //============================================================================
1322 /*! Function : FindObject
1323  *  Purpose  : Find an Object with SALOMEDSImpl_Name = anObjectName
1324  */
1325 //============================================================================
1326 SALOMEDSImpl_SObject SALOMEDSImpl_Study::FindObject(const std::string& anObjectName)
1327 {
1328   _errorCode = "";
1329
1330   // Iterate to all components defined in the study
1331   // After testing the component name, iterate in all objects defined under
1332   // components (function _FindObject)
1333   bool _find = false;
1334   SALOMEDSImpl_SObject RefSO;
1335
1336   SALOMEDSImpl_SComponentIterator it = NewComponentIterator();
1337   for (; it.More();it.Next()){
1338     if(!_find)
1339       {
1340         SALOMEDSImpl_SComponent SC = it.Value();
1341         if (SC.GetName() == anObjectName)
1342         {
1343             _find = true;
1344             RefSO = SC;
1345
1346         }
1347         if (!_find) RefSO =  _FindObject(SC, anObjectName, _find);
1348       }
1349   }
1350   if(!RefSO) _errorCode = "No object was found";
1351   return RefSO;
1352 }
1353
1354 //============================================================================
1355 /*! Function : FindObjectID
1356  *  Purpose  : Find an Object with ID = anObjectID
1357  */
1358 //============================================================================
1359 SALOMEDSImpl_SObject SALOMEDSImpl_Study::FindObjectID(const std::string& anObjectID)
1360 {
1361   _errorCode = "";
1362   SALOMEDSImpl_SObject so;
1363
1364   // Convert aSO->GetID in DF_Label.
1365   DF_Label Lab = DF_Label::Label(_doc->Main(), anObjectID, false);
1366
1367   if (Lab.IsNull()) {
1368     _errorCode = "No label was found by ID";
1369     return so;
1370   }
1371   return GetSObject(Lab);
1372
1373 }
1374
1375 //============================================================================
1376 /*! Function : CreateObjectID
1377  *  Purpose  : Creates an Object with ID = anObjectID
1378  */
1379 //============================================================================
1380 SALOMEDSImpl_SObject SALOMEDSImpl_Study::CreateObjectID(const std::string& anObjectID)
1381 {
1382   _errorCode = "";
1383   SALOMEDSImpl_SObject so;
1384
1385   // Convert aSO->GetID in DF_Label.
1386   DF_Label Lab = DF_Label::Label(_doc->Main(), anObjectID, true);
1387
1388   if (Lab.IsNull()) {
1389     _errorCode = "Can not create a label";
1390     return so;
1391   }
1392   return GetSObject(Lab);
1393
1394 }
1395
1396 //============================================================================
1397 /*! Function : FindObjectByName
1398  *  Purpose  : Find Objects with SALOMEDSImpl_Name = anObjectName in a Component
1399  *           : with ComponentDataType = aComponentName
1400  */
1401 //============================================================================
1402 std::vector<SALOMEDSImpl_SObject> SALOMEDSImpl_Study::FindObjectByName(const std::string& anObjectName,
1403                                                                        const std::string& aComponentName)
1404 {
1405   _errorCode = "";
1406
1407   std::vector<SALOMEDSImpl_SObject> listSO;
1408
1409   SALOMEDSImpl_SComponent compo = FindComponent(aComponentName) ;
1410   if ( !compo ) {
1411     _errorCode = "Can not find the component";
1412     return listSO;
1413   }
1414
1415   // Iterate on each object and subobject of the component
1416   // If objectName is found add it to the list of SObjects
1417   std::string childName ;
1418
1419   std::string compoId = compo.GetID();
1420   SALOMEDSImpl_ChildIterator it = NewChildIterator(compo);
1421   for ( ; it.More(); it.Next() ) {
1422
1423     SALOMEDSImpl_SObject CSO = it.Value();
1424     if ( CSO.GetName() == anObjectName ) {
1425         /* add to list */
1426         listSO.push_back(CSO) ;
1427     }
1428
1429     /* looks also for eventual children */
1430     bool found = false ;
1431     CSO = _FindObject( CSO, anObjectName, found ) ;
1432     if( found) {
1433       listSO.push_back(CSO) ;
1434     }
1435   }
1436
1437   return listSO;
1438 }
1439
1440
1441
1442 //============================================================================
1443 /*! Function : FindObjectIOR
1444  *  Purpose  : Find an Object with IOR = anObjectIOR
1445  */
1446 //============================================================================
1447 SALOMEDSImpl_SObject SALOMEDSImpl_Study::FindObjectIOR(const std::string& anObjectIOR)
1448 {
1449   _errorCode = "";
1450
1451   SALOMEDSImpl_SObject aResult ;
1452
1453   // searching in the datamap for optimization
1454   std::map<std::string, DF_Label>::iterator it=myIORLabels.find(anObjectIOR);
1455   if (it != myIORLabels.end()) {
1456     aResult = GetSObject(it->second);
1457     // 11 oct 2002: forbidden attributes must be checked here
1458     if (!aResult.GetLabel().IsAttribute(SALOMEDSImpl_AttributeIOR::GetID())) {
1459       myIORLabels.erase(anObjectIOR);
1460       aResult = SALOMEDSImpl_SObject();
1461     }
1462   }
1463
1464   if(!aResult) _errorCode = "No object was found";
1465   return aResult;
1466 }
1467
1468 //============================================================================
1469 /*! Function : FindObjectByPath
1470  *  Purpose  : Find an Object by its path = thePath
1471  */
1472 //============================================================================
1473 SALOMEDSImpl_SObject SALOMEDSImpl_Study::FindObjectByPath(const std::string& thePath)
1474 {
1475   _errorCode = "";
1476
1477   std::string aPath(thePath), aToken;
1478   SALOMEDSImpl_SObject aSO;
1479   int aLength = aPath.size();
1480   bool isRelative = false;
1481
1482   if(aLength == 0) {  //Empty path - return the current context
1483     return aSO;
1484   }
1485
1486   if(aPath[0] != '/')  //Relative path
1487     isRelative = true;
1488
1489   DF_ChildIterator anIterator;
1490   DF_Label aLabel;
1491   SALOMEDSImpl_AttributeName* anAttr;
1492
1493   if(isRelative) {
1494     return aSO;
1495   }
1496   else {
1497     if(aPath.size() == 1 && aPath[0] == '/') {    //Root
1498       return GetSObject(_doc->Main());
1499     }
1500     anIterator.Init(_doc->Main(), false);
1501   }
1502
1503   std::vector<std::string> vs = SALOMEDSImpl_Tool::splitString(aPath, '/');
1504   for(int i = 0, len = vs.size(); i<len; i++) {
1505
1506     aToken = vs[i];
1507     if(aToken.size() == 0) break;
1508
1509     for ( ; anIterator.More(); anIterator.Next() ) {
1510       aLabel = anIterator.Value();
1511       if((anAttr=(SALOMEDSImpl_AttributeName*)aLabel.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
1512         if(anAttr->Value() == aToken) {
1513           if(i == (len-1)) {  //The searched label is found (no part of the path is left)
1514               return GetSObject(aLabel);
1515           }
1516
1517           anIterator.Init(aLabel, false);
1518           break;
1519         }
1520       }
1521     }
1522
1523   }
1524
1525   if(!aSO) _errorCode = "No object was found";
1526   return aSO;
1527 }
1528
1529 //============================================================================
1530 /*! Function : GetObjectPath
1531  *  Purpose  :
1532  */
1533 //============================================================================
1534 std::string SALOMEDSImpl_Study::GetObjectPath(const SALOMEDSImpl_SObject& theObject)
1535 {
1536   _errorCode = "";
1537
1538   std::string aPath("");
1539   if(!theObject) {
1540     _errorCode = "Null object";
1541     return aPath;
1542   }
1543
1544   std::string aName = theObject.GetName();
1545   if(!aName.empty() && aName != "" ) {
1546     std::string aValue("/");
1547     aValue+=aName;
1548     aValue += aPath;
1549     aPath = aValue;
1550     SALOMEDSImpl_SObject aFather = theObject.GetFather();
1551     if(aFather) {
1552        aName = aFather.GetName();
1553        if(!aName.empty() && aName != "") {
1554            aValue = GetObjectPath(aFather);
1555           aPath = aValue + aPath;
1556        }
1557     }
1558   }
1559
1560   return aPath;
1561 }
1562
1563
1564 //============================================================================
1565 /*! Function : GetObjectPathByIOR
1566  *  Purpose  :
1567  */
1568 //============================================================================
1569 std::string SALOMEDSImpl_Study::GetObjectPathByIOR(const std::string& theIOR)
1570 {
1571   _errorCode = "";
1572
1573   std::string aPath;
1574   SALOMEDSImpl_SObject so = FindObjectIOR(theIOR);
1575   if(!so) {
1576     _errorCode = "No SObject was found by IOR";
1577     return aPath;
1578   }
1579
1580   return GetObjectPath(so);
1581 }
1582
1583 //============================================================================
1584 /*! Function : NewChildIterator
1585  *  Purpose  : Create a ChildIterator from an SObject
1586  */
1587 //============================================================================
1588 SALOMEDSImpl_ChildIterator SALOMEDSImpl_Study::NewChildIterator(const SALOMEDSImpl_SObject& aSO)
1589 {
1590   _errorCode = "";
1591   return SALOMEDSImpl_ChildIterator(aSO);
1592 }
1593
1594
1595 //============================================================================
1596 /*! Function : NewComponentIterator
1597  *  Purpose  : Create a SComponentIterator
1598  */
1599 //============================================================================
1600 SALOMEDSImpl_SComponentIterator SALOMEDSImpl_Study::NewComponentIterator()
1601 {
1602   _errorCode = "";
1603   return SALOMEDSImpl_SComponentIterator(_doc);
1604 }
1605
1606
1607 //============================================================================
1608 /*! Function : NewBuilder
1609  *  Purpose  : Create a StudyBuilder
1610  */
1611 //============================================================================
1612 SALOMEDSImpl_StudyBuilder* SALOMEDSImpl_Study::NewBuilder()
1613 {
1614   _errorCode = "";
1615   if(_autoFill) {
1616     _builder->SetOnAddSObject(_cb);
1617     _builder->SetOnRemoveSObject(_cb);
1618   }
1619   return _builder;
1620
1621 }
1622
1623 //============================================================================
1624 /*! Function : Name
1625  *  Purpose  : get study name
1626  */
1627 //============================================================================
1628 std::string SALOMEDSImpl_Study::Name()
1629 {
1630   _errorCode = "";
1631   return Kernel_Utils::GetBaseName( _name, false );
1632 }
1633
1634 //============================================================================
1635 /*! Function : Name
1636  *  Purpose  : set study name
1637  */
1638 //============================================================================
1639 void SALOMEDSImpl_Study::Name(const std::string& name)
1640 {
1641   _errorCode = "";
1642   _name = name;
1643 }
1644
1645 //============================================================================
1646 /*! Function : IsSaved
1647  *  Purpose  : get if study has been saved
1648  */
1649 //============================================================================
1650 bool SALOMEDSImpl_Study::IsSaved()
1651 {
1652   _errorCode = "";
1653   return _Saved;
1654 }
1655
1656 //============================================================================
1657 /*! Function : IsSaved
1658  *  Purpose  : set if study has been saved
1659  */
1660 //============================================================================
1661 void SALOMEDSImpl_Study::IsSaved(bool save)
1662 {
1663   _errorCode = "";
1664   _Saved = save;
1665   if(save) _doc->SetModified(false);
1666 }
1667
1668 //============================================================================
1669 /*! Function : IsModified
1670  *  Purpose  : Detect if a Study has been modified since it has been saved
1671  */
1672 //============================================================================
1673 bool SALOMEDSImpl_Study::IsModified()
1674 {
1675   _errorCode = "";
1676
1677   // True if is modified
1678   if (_doc && _doc->IsModified()) return true;
1679
1680   return false;
1681 }
1682
1683 //============================================================================
1684 /*! Function : URL
1685  *  Purpose  : get URL of the study (persistent reference of the study)
1686  */
1687 //============================================================================
1688 std::string SALOMEDSImpl_Study::URL()
1689 {
1690   _errorCode = "";
1691   return _URL;
1692 }
1693
1694 //============================================================================
1695 /*! Function : URL
1696  *  Purpose  : set URL of the study (persistent reference of the study)
1697  */
1698 //============================================================================
1699 void SALOMEDSImpl_Study::URL(const std::string& url)
1700 {
1701   _errorCode = "";
1702   _URL = url;
1703   _name = url;
1704
1705   /*jfa: Now name of SALOMEDS study will correspond to name of SalomeApp study
1706   std::string tmp(_URL);
1707
1708   char *aName = (char*)tmp.ToCString();
1709   char *adr = strtok(aName, "/");
1710   while (adr)
1711     {
1712       aName = adr;
1713       adr = strtok(NULL, "/");
1714     }
1715   Name(aName);*/
1716 }
1717
1718
1719 //============================================================================
1720 /*! Function : _FindObject
1721  *  Purpose  : Find an Object with SALOMEDSImpl_Name = anObjectName
1722  */
1723 //============================================================================
1724 SALOMEDSImpl_SObject SALOMEDSImpl_Study::_FindObject(const SALOMEDSImpl_SObject& SO,
1725                                                      const std::string& theObjectName,
1726                                                      bool& _find)
1727 {
1728   SALOMEDSImpl_SObject RefSO;
1729   if(!SO) return RefSO;
1730
1731   // Iterate on each objects and subobjects of the component
1732   // If objectName find, stop the loop and get the object reference
1733   SALOMEDSImpl_AttributeName* anAttr;
1734
1735   std::string soid = SO.GetID();
1736   DF_ChildIterator it(SO.GetLabel());
1737   for (; it.More(); it.Next()){
1738     if(!_find)
1739       {
1740         if ((anAttr=(SALOMEDSImpl_AttributeName*)it.Value().FindAttribute(SALOMEDSImpl_AttributeName::GetID())))
1741         {
1742           std::string Val(anAttr->Value());
1743           if (Val == theObjectName)
1744             {
1745               RefSO = GetSObject(it.Value());
1746               _find = true;
1747             }
1748         }
1749         if (!_find) RefSO = _FindObject(GetSObject(it.Value()), theObjectName, _find);
1750       }
1751   }
1752   return RefSO;
1753 }
1754
1755 //============================================================================
1756 /*! Function : _FindObjectIOR
1757  *  Purpose  : Find an Object with SALOMEDSImpl_IOR = anObjectIOR
1758  */
1759 //============================================================================
1760 SALOMEDSImpl_SObject
1761 SALOMEDSImpl_Study::_FindObjectIOR(const SALOMEDSImpl_SObject& SO,
1762                                    const std::string& theObjectIOR,
1763                                    bool& _find)
1764 {
1765   SALOMEDSImpl_SObject RefSO, aSO;
1766   if(!SO) return RefSO;
1767
1768   // Iterate on each objects and subobjects of the component
1769   // If objectName find, stop the loop and get the object reference
1770   SALOMEDSImpl_AttributeIOR* anAttr;
1771
1772   DF_ChildIterator it(SO.GetLabel());
1773   for (; it.More();it.Next()){
1774     if(!_find)
1775       {
1776         if ((anAttr=(SALOMEDSImpl_AttributeIOR*)it.Value().FindAttribute(SALOMEDSImpl_AttributeIOR::GetID())))
1777         {
1778           std::string Val(anAttr->Value());
1779           if (Val == theObjectIOR)
1780             {
1781               RefSO = GetSObject(it.Value());
1782               _find = true;
1783             }
1784         }
1785         aSO = GetSObject(it.Value());
1786         if (!_find) RefSO =  _FindObjectIOR(aSO, theObjectIOR, _find);
1787       }
1788   }
1789   return RefSO;
1790 }
1791
1792 //============================================================================
1793 /*! Function : _GetNoteBookAccessor
1794  *  Purpose  : Find an Object with SALOMEDSImpl_IOR = anObjectIOR
1795  */
1796 //============================================================================
1797 std::string SALOMEDSImpl_Study::_GetNoteBookAccessor(){
1798   return std::string("notebook");
1799 }
1800
1801 //============================================================================
1802 /*! Function : _GetStudyVariablesScript
1803  *  Purpose  :
1804  */
1805 //============================================================================
1806 std::string SALOMEDSImpl_Study::_GetStudyVariablesScript()
1807 {
1808   std::string dump("");
1809
1810   if(myNoteBookVars.empty())
1811     return dump;
1812
1813   Kernel_Utils::Localizer loc;
1814
1815   dump += "####################################################\n";
1816   dump += "##       Begin of NoteBook variables section      ##\n";
1817   dump += "####################################################\n";
1818
1819   std::string set_method = _GetNoteBookAccessor()+".set(";
1820   std::string varName;
1821   std::string varValue;
1822   for(int i = 0 ; i < myNoteBookVars.size();i++ ) {
1823     varName = myNoteBookVars[i]->Name();
1824     varValue = myNoteBookVars[i]->SaveToScript();
1825     dump+=set_method+"\""+varName+"\", "+varValue+")\n";
1826   }
1827
1828   dump += "####################################################\n";
1829   dump += "##        End of NoteBook variables section       ##\n";
1830   dump += "####################################################\n";
1831
1832   return dump;
1833 }
1834
1835 //============================================================================
1836 /*! Function : _GetNoteBookAccess
1837  *  Purpose  :
1838  */
1839 //============================================================================
1840 std::string SALOMEDSImpl_Study::_GetNoteBookAccess()
1841 {
1842   std::string notebook = "import salome_notebook\n";
1843   notebook += _GetNoteBookAccessor() + " = salome_notebook.NoteBook()" ;
1844   return notebook;
1845 }
1846
1847 bool SALOMEDSImpl_Study::IsLocked()
1848 {
1849   _errorCode = "";
1850   return GetProperties()->IsLocked();
1851 }
1852
1853 void SALOMEDSImpl_Study::UpdateIORLabelMap(const std::string& anIOR,const std::string& anEntry)
1854 {
1855   _errorCode = "";
1856   DF_Label aLabel = DF_Label::Label(_doc->Main(), anEntry, true);
1857   std::map<std::string, DF_Label>::iterator it=myIORLabels.find(anIOR);
1858   if (it != myIORLabels.end()) myIORLabels.erase(it);
1859   myIORLabels[anIOR] = aLabel;
1860 }
1861
1862 void SALOMEDSImpl_Study::DeleteIORLabelMapItem(const std::string& anIOR)
1863 {
1864   std::map<std::string, DF_Label>::iterator it=myIORLabels.find(anIOR);
1865   if (it != myIORLabels.end())
1866     {
1867       //remove the ior entry and decref the genericobj (if it's one)
1868       myIORLabels.erase(it);
1869     }
1870 }
1871
1872 SALOMEDSImpl_Study* SALOMEDSImpl_Study::GetStudyImpl(const DF_Label& theLabel)
1873 {
1874   SALOMEDSImpl_StudyHandle* Att;
1875   if ((Att=(SALOMEDSImpl_StudyHandle*)theLabel.Root().FindAttribute(SALOMEDSImpl_StudyHandle::GetID()))) {
1876     return Att->Get();
1877   }
1878   return NULL;
1879 }
1880
1881 SALOMEDSImpl_SObject SALOMEDSImpl_Study::SObject(const DF_Label& theLabel)
1882 {
1883   return GetStudyImpl(theLabel)->GetSObject(theLabel);
1884 }
1885
1886 SALOMEDSImpl_SComponent SALOMEDSImpl_Study::SComponent(const DF_Label& theLabel)
1887 {
1888   return GetStudyImpl(theLabel)->GetSComponent(theLabel);
1889 }
1890
1891
1892 void SALOMEDSImpl_Study::IORUpdated(const SALOMEDSImpl_AttributeIOR* theAttribute)
1893 {
1894   std::string aString = theAttribute->Label().Entry();
1895   GetStudyImpl(theAttribute->Label())->UpdateIORLabelMap(theAttribute->Value(), aString);
1896 }
1897
1898 std::vector<SALOMEDSImpl_SObject> SALOMEDSImpl_Study::FindDependances(const SALOMEDSImpl_SObject& anObject)
1899 {
1900   _errorCode = "";
1901   std::vector<SALOMEDSImpl_SObject> aSeq;
1902
1903   SALOMEDSImpl_AttributeTarget* aTarget;
1904   if ((aTarget=(SALOMEDSImpl_AttributeTarget*)anObject.GetLabel().FindAttribute(SALOMEDSImpl_AttributeTarget::GetID()))) {
1905     return aTarget->Get();
1906   }
1907
1908   return aSeq;
1909 }
1910
1911
1912 SALOMEDSImpl_AttributeStudyProperties* SALOMEDSImpl_Study::GetProperties()
1913 {
1914   _errorCode = "";
1915   return SALOMEDSImpl_AttributeStudyProperties::Set(_doc->Main());
1916 }
1917
1918 std::string SALOMEDSImpl_Study::GetLastModificationDate()
1919 {
1920   _errorCode = "";
1921   SALOMEDSImpl_AttributeStudyProperties* aProp = GetProperties();
1922
1923   std::vector<std::string> aNames;
1924   std::vector<int> aMinutes, aHours, aDays, aMonths, aYears;
1925   aProp->GetModifications(aNames, aMinutes, aHours, aDays, aMonths, aYears);
1926
1927   int aLastIndex = aNames.size()-1;
1928   char aResult[20];
1929   sprintf(aResult, "%2.2d/%2.2d/%4.4d %2.2d:%2.2d",
1930           (int)(aDays[aLastIndex]),(int)(aMonths[aLastIndex]), (int)(aYears[aLastIndex]),
1931           (int)(aHours[aLastIndex]), (int)(aMinutes[aLastIndex]));
1932   std::string aResStr (aResult);
1933   return aResStr;
1934 }
1935
1936 std::vector<std::string> SALOMEDSImpl_Study::GetModificationsDate()
1937 {
1938   _errorCode = "";
1939   SALOMEDSImpl_AttributeStudyProperties* aProp = GetProperties();
1940
1941   std::vector<std::string> aNames;
1942   std::vector<int> aMinutes, aHours, aDays, aMonths, aYears;
1943   aProp->GetModifications(aNames, aMinutes, aHours, aDays, aMonths, aYears);
1944
1945   int anIndex, aLength = aNames.size();
1946   std::vector<std::string> aDates;
1947
1948   for (anIndex = 1; anIndex < aLength; anIndex++) {
1949     char aDate[20];
1950     sprintf(aDate, "%2.2d/%2.2d/%4.4d %2.2d:%2.2d",
1951             (int)(aDays[anIndex]), (int)(aMonths[anIndex]), (int)(aYears[anIndex]),
1952             (int)(aHours[anIndex]), (int)(aMinutes[anIndex]));
1953     aDates.push_back(aDate);
1954   }
1955   return aDates;
1956 }
1957
1958
1959
1960 //============================================================================
1961 /*! Function : GetUseCaseBuilder
1962  *  Purpose  : Returns a UseCase builder
1963  */
1964 //============================================================================
1965 SALOMEDSImpl_UseCaseBuilder* SALOMEDSImpl_Study::GetUseCaseBuilder()
1966 {
1967   _errorCode = "";
1968   return _useCaseBuilder;
1969 }
1970
1971 //============================================================================
1972 /*! Function : GetSComponent
1973  *  Purpose  :
1974  */
1975 //============================================================================
1976 SALOMEDSImpl_SComponent SALOMEDSImpl_Study::GetSComponent(const std::string& theEntry)
1977 {
1978   SALOMEDSImpl_SComponent aSCO;
1979   if(_mapOfSCO.find(theEntry) != _mapOfSCO.end())
1980     aSCO = _mapOfSCO[theEntry];
1981   else {
1982     DF_Label aLabel = DF_Label::Label(_doc->Main(), theEntry);
1983     aSCO = SALOMEDSImpl_SComponent(aLabel);
1984     _mapOfSCO[theEntry] = aSCO;
1985   }
1986
1987   return aSCO;
1988 }
1989
1990 //============================================================================
1991 /*! Function : GetSComponent
1992  *  Purpose  :
1993  */
1994 //============================================================================
1995 SALOMEDSImpl_SComponent SALOMEDSImpl_Study::GetSComponent(const DF_Label& theLabel)
1996 {
1997   return SALOMEDSImpl_SComponent(theLabel);
1998 }
1999
2000 //============================================================================
2001 /*! Function : GetSObject
2002  *  Purpose  :
2003  */
2004 //============================================================================
2005 SALOMEDSImpl_SObject SALOMEDSImpl_Study::GetSObject(const std::string& theEntry)
2006 {
2007   SALOMEDSImpl_SObject aSO;
2008   std::map<std::string, SALOMEDSImpl_SObject>::iterator it=_mapOfSO.find(theEntry);
2009   if(it != _mapOfSO.end())
2010     aSO = it->second;
2011   else {
2012     DF_Label aLabel = DF_Label::Label(_doc->Main(), theEntry);
2013     aSO = SALOMEDSImpl_SObject(aLabel);
2014     _mapOfSO[theEntry] = aSO;
2015   }
2016
2017   return aSO;
2018 }
2019
2020 //============================================================================
2021 /*! Function : GetSObject
2022  *  Purpose  :
2023  */
2024 //============================================================================
2025 SALOMEDSImpl_SObject SALOMEDSImpl_Study::GetSObject(const DF_Label& theLabel)
2026 {
2027   return SALOMEDSImpl_SObject(theLabel);
2028 }
2029
2030 //============================================================================
2031 /*! Function : GetAttribute
2032  *  Purpose  :
2033  */
2034 //============================================================================
2035 DF_Attribute* SALOMEDSImpl_Study::GetAttribute(const std::string& theEntry,
2036                                                const std::string& theType)
2037 {
2038   SALOMEDSImpl_SObject aSO = GetSObject(theEntry);
2039   DF_Attribute* anAttr;
2040   aSO.FindAttribute(anAttr, theType);
2041   return anAttr;
2042 }
2043
2044 //! number of spaces for indentation in Python dump files (to replace \t symbols)
2045 static const int indent_size = 2;
2046
2047 static std::string replace_tabs( const std::string& in )
2048 {
2049   std::string out = in;
2050 #ifdef WITHOUT_TABS
2051   size_t pos = out.find( '\t' );
2052   while ( pos != std::string::npos ) {
2053     out.replace( pos, 1, indent_size, ' ' );
2054     pos = out.find( '\t' );
2055   }
2056 #endif
2057   return out;
2058 }
2059
2060 static std::string GetComponentHeader(const char* theComponentName)
2061 {
2062   std::stringstream txt;
2063   txt << "###" << std::endl;
2064   txt << "### " << theComponentName << " component" << std::endl;
2065   txt << "###" << std::endl;
2066   return txt.str();
2067 }
2068
2069 //============================================================================
2070 /*! Function : DumpStudy
2071  *  Purpose  :
2072  */
2073 //============================================================================
2074 bool SALOMEDSImpl_Study::DumpStudy(const std::string& thePath,
2075                                    const std::string& theBaseName,
2076                                    bool isPublished,
2077                                    bool isMultiFile,
2078                                    SALOMEDSImpl_DriverFactory* theFactory)
2079 {
2080   _errorCode = "";
2081
2082   if(theFactory == NULL) {
2083     _errorCode = "Null factory for creation of Engines";
2084     return false;
2085   }
2086
2087   std::vector<std::string> aSeq;
2088   std::string aFactoryType;
2089
2090   //Build a list of all components in the Study
2091   SALOMEDSImpl_SComponentIterator itcomponent = NewComponentIterator();
2092
2093   for (; itcomponent.More(); itcomponent.Next())
2094     aSeq.push_back(itcomponent.Value().ComponentDataType());
2095
2096   std::vector<std::string>::iterator it;
2097   if ( (it = std::find( aSeq.begin(), aSeq.end(), "GEOM" )) != aSeq.end() ) {
2098     aSeq.erase( it );
2099     aSeq.insert(aSeq.begin(), "GEOM" );
2100   }
2101   if ( (it = std::find( aSeq.begin(), aSeq.end(), "SHAPER" )) != aSeq.end() ) {
2102     aSeq.erase( it );
2103     aSeq.insert(aSeq.begin(), "SHAPER" );
2104   }
2105
2106   // re-arrange modules in the sequence, if specific order is given via SALOME_MODULES_ORDER environment variable.
2107   if ( getenv("SALOME_MODULES_ORDER") != 0 ) {
2108     std::string order = getenv("SALOME_MODULES_ORDER");
2109     std::vector<std::string> mlist;
2110     while ( !order.empty() ) {
2111       size_t idx = order.find( ":" );
2112       std::string m = order.substr(0, idx);
2113       order = order.substr( ( idx == std::string::npos ) ? order.size() : idx+1 );
2114       if ( m.empty() || std::find( mlist.begin(), mlist.end(), m ) != mlist.end() ) continue;
2115       mlist.push_back( m );
2116     }
2117
2118     for ( std::vector<std::string>::reverse_iterator mit = mlist.rbegin(); mit != mlist.rend(); ++mit ) {
2119       std::vector<std::string>::iterator it = std::find( aSeq.begin(), aSeq.end(), *mit );
2120       if ( it != aSeq.end() ) {
2121         aSeq.erase( it );
2122         aSeq.insert( aSeq.begin(), *mit );
2123       }
2124     }
2125   }
2126
2127 #ifdef WIN32
2128   std::string aFileName =
2129     thePath + std::string("\\") + theBaseName + std::string(".py");
2130 #else
2131   std::string aFileName =
2132     thePath + std::string("/")  + theBaseName + std::string(".py");
2133 #endif
2134
2135   //Create a file that will contain a main Study script
2136   std::fstream fp;
2137 #if defined(WIN32) && defined(UNICODE)
2138   std::wstring aConverterFN = Kernel_Utils::utf8_decode_s(aFileName);
2139   fp.open(aConverterFN.c_str(), std::ios::out);
2140 #else
2141   fp.open(aFileName.c_str(), std::ios::out);
2142 #endif
2143
2144 #ifdef WIN32
2145   bool isOpened = fp.is_open();
2146 #else
2147   bool isOpened = fp.rdbuf()->is_open();
2148 #endif
2149
2150   if(!isOpened) {
2151     _errorCode = std::string("Can't create a file ")+aFileName;
2152     return false;
2153   }
2154
2155   std::stringstream sfp;
2156
2157   std::string aBatchModeScript = "salome";
2158
2159   //Output to the main Study script required Python modules import,
2160   //set sys.path and add a creation of the study.
2161
2162   // dump header
2163   sfp << GetDumpStudyComment() << std::endl;
2164
2165   // global imports
2166   sfp << "import sys" << std::endl;
2167   sfp << "import " << aBatchModeScript << std::endl << std::endl;
2168
2169   // initialization function
2170   sfp << aBatchModeScript << ".salome_init()" << std::endl;
2171
2172   // notebook initialization
2173   sfp << _GetNoteBookAccess() << std::endl;
2174
2175   // extend sys.path with the directory where the script is being dumped to
2176   sfp << "sys.path.insert(0, r\'" << thePath << "\')" << std::endl << std::endl;
2177
2178   // dump NoteBook variables
2179   sfp << _GetStudyVariablesScript();
2180
2181   // dump visual parameters if necessary
2182   bool isDumpVisuals = SALOMEDSImpl_IParameters::isDumpPython(this);
2183   int lastSavePoint = -1;
2184   if(isDumpVisuals) {
2185     lastSavePoint = SALOMEDSImpl_IParameters::getLastSavePoint(this);
2186     if(lastSavePoint > 0) {
2187       sfp << SALOMEDSImpl_IParameters::getStudyScript(this, lastSavePoint) << std::endl << std::endl;
2188     }
2189   }
2190
2191   std::vector<std::string> aSeqOfFileNames;
2192
2193   // dump all components and create the components specific scripts
2194   bool isOk = true;
2195   int aLength = aSeq.size();
2196   for(int i = 1; i <= aLength; i++) {
2197
2198     std::string aCompType = aSeq[i-1];
2199     SALOMEDSImpl_SComponent sco = FindComponent(aCompType);
2200     SALOMEDSImpl_Driver* aDriver = NULL;
2201     // if there is an associated Engine call its method for saving
2202     std::string IOREngine;
2203     try {
2204       if (!sco.ComponentIOR(IOREngine)) {
2205         if (!aCompType.empty()) {
2206
2207           aDriver = theFactory->GetDriverByType(aCompType);
2208
2209           if (aDriver != NULL) {
2210             SALOMEDSImpl_StudyBuilder* SB = NewBuilder();
2211             if(!SB->LoadWith(sco, aDriver)) {
2212               _errorCode = SB->GetErrorCode();
2213               return false;
2214             }
2215           }
2216           else continue;
2217         }
2218       }
2219       else {
2220         aDriver = theFactory->GetDriverByIOR(IOREngine);
2221       }
2222     } catch(...) {
2223       _errorCode = "Can not restore information to dump it";
2224       return false;
2225     }
2226
2227     if(aDriver == NULL) continue;
2228
2229     bool isValidScript;
2230     long aStreamLength  = 0;
2231     SALOMEDSImpl_TMPFile* aStream = aDriver->DumpPython(isPublished, isMultiFile, isValidScript, aStreamLength);
2232     if ( !isValidScript )
2233       isOk = false;
2234
2235     std::stringstream sfp2;
2236
2237     //Output the Python script generated by the component in the newly created file.
2238     if ( isMultiFile )
2239       sfp2 << GetDumpStudyComment( aCompType.c_str() ) << std::endl;
2240     else
2241       sfp2 << GetComponentHeader( aCompType.c_str() ) << std::endl;
2242     sfp2 << aStream->Data();
2243
2244     if ( isMultiFile ) {
2245       //Create a file that will contain the component specific script
2246       std::fstream fp2;
2247 #ifdef WIN32
2248       aFileName=thePath+std::string("\\");
2249 #else
2250       aFileName=thePath+std::string("/");
2251 #endif
2252       std::string aScriptName;
2253       aScriptName += theBaseName;
2254       aScriptName += "_";
2255       aScriptName += aCompType;
2256
2257       aFileName += aScriptName+ std::string(".py");
2258       aSeqOfFileNames.push_back(aFileName);
2259
2260 #if defined(WIN32) && defined(UNICODE)
2261       std::wstring aConverterFN2 = Kernel_Utils::utf8_decode_s(aFileName);
2262       fp2.open(aConverterFN2.c_str(), std::ios::out);
2263 #else
2264       fp2.open(aFileName.c_str(), std::ios::out);
2265 #endif
2266
2267 #ifdef WIN32
2268       isOpened = fp2.is_open();
2269 #else
2270       isOpened = fp2.rdbuf()->is_open();
2271 #endif
2272
2273       if(!isOpened) {
2274         _errorCode = std::string("Can't create a file ")+aFileName;
2275         SALOMEDSImpl_Tool::RemoveTemporaryFiles(thePath, aSeqOfFileNames, false);
2276         return false;
2277       }
2278
2279       // replace '\t' symbols
2280       fp2 << replace_tabs( sfp2.str() );
2281
2282       fp2.close();
2283
2284       //Add to the main script a call to RebuildData of the generated by the component the Python script
2285       sfp << "import " << aScriptName << std::endl;
2286       sfp << aScriptName << ".RebuildData()" << std::endl;
2287     }
2288     else
2289       sfp << sfp2.str();
2290
2291     if(aStream) delete aStream;
2292   }
2293
2294   sfp << std::endl;
2295   sfp << "if salome.sg.hasDesktop():" << std::endl;
2296   sfp << "\tsalome.sg.updateObjBrowser()" << std::endl;
2297
2298   if(isDumpVisuals) { //Output the call to Session's method restoreVisualState
2299     sfp << "\tiparameters.getSession().restoreVisualState(1)" << std::endl;
2300   }
2301
2302   // replace '\t' symbols
2303   fp << replace_tabs( sfp.str() );
2304
2305   fp.close();
2306
2307   return isOk;
2308 }
2309
2310 //=======================================================================
2311 //function : GetDumpStudyComment
2312 //purpose  : return a header comment for a DumpStudy script
2313 //=======================================================================
2314
2315 std::string SALOMEDSImpl_Study::GetDumpStudyComment(const char* theComponentName)
2316 {
2317   std::stringstream txt;
2318   txt << "#!/usr/bin/env python" << std::endl << std::endl;
2319   txt << "###" << std::endl;
2320   txt << "### This file is generated automatically by SALOME v"
2321       << KERNEL_VERSION_STR
2322       << " with dump python functionality";
2323   if ( theComponentName )
2324     txt << " (" << theComponentName << " component)";
2325   txt << std::endl;
2326   txt << "###" << std::endl;
2327   return txt.str();
2328 }
2329
2330 void dumpSO(const SALOMEDSImpl_SObject& theSO,
2331             std::fstream& fp,
2332             const std::string& Tab,
2333             SALOMEDSImpl_Study* theStudy);
2334
2335 //============================================================================
2336 /*! Function : dump
2337  *  Purpose  :
2338  */
2339 //============================================================================
2340 void SALOMEDSImpl_Study::dump(const std::string& theFileName)
2341 {
2342   //Create a file that will contain a main Study script
2343   std::fstream fp;
2344   fp.open(theFileName.c_str(), std::ios::out);
2345
2346 #ifdef WIN32
2347   bool isOpened = fp.is_open();
2348 #else
2349   bool isOpened = fp.rdbuf()->is_open();
2350 #endif
2351
2352   if(!isOpened) {
2353     _errorCode = std::string("Can't create a file ")+theFileName;
2354     std::cout << "### SALOMEDSImpl_Study::dump Error: " << _errorCode << std::endl;
2355     return;
2356   }
2357
2358   SALOMEDSImpl_SObject aSO = FindObjectID("0:1");
2359   fp << "0:1" << std::endl;
2360   SALOMEDSImpl_ChildIterator Itr = NewChildIterator(aSO);
2361   std::string aTab("   ");
2362   for(; Itr.More(); Itr.Next()) {
2363     dumpSO(Itr.Value(), fp, aTab, this);
2364   }
2365
2366   fp.close();
2367 }
2368
2369
2370 void dumpSO(const SALOMEDSImpl_SObject& theSO,
2371             std::fstream& fp,
2372             const std::string& Tab,
2373             SALOMEDSImpl_Study* theStudy)
2374 {
2375   std::string aTab(Tab), anID(theSO.GetID());
2376   fp << aTab << anID << std::endl;
2377   std::vector<DF_Attribute*> attribs = theSO.GetLabel().GetAttributes();
2378   for(int i = 0; i<attribs.size(); i++) {
2379     SALOMEDSImpl_GenericAttribute* anAttr = dynamic_cast<SALOMEDSImpl_GenericAttribute*>(attribs[i]);
2380
2381     if(!anAttr) {
2382       continue;
2383     }
2384
2385     std::string aType = anAttr->GetClassType();
2386     fp << Tab << "  -- " << aType;
2387
2388     if(aType == std::string("AttributeReal")) {
2389       fp << " : " << dynamic_cast<SALOMEDSImpl_AttributeReal*>(anAttr)->Value();
2390     }
2391     else if(aType == std::string("AttributeInteger")) {
2392       fp << " : " << dynamic_cast<SALOMEDSImpl_AttributeInteger*>(anAttr)->Value();
2393     }
2394     else if(aType ==  std::string("AttributeName")) {
2395       fp << " : " << dynamic_cast<SALOMEDSImpl_AttributeName*>(anAttr)->Value();
2396     }
2397     else if(aType == std::string("AttributeComment")) {
2398       fp << " : " << dynamic_cast<SALOMEDSImpl_AttributeComment*>(anAttr)->Value();
2399     }
2400     else if(aType == std::string("AttributeReference")) {
2401       fp << " : " << dynamic_cast<SALOMEDSImpl_AttributeReference*>(anAttr)->Save();
2402     }
2403     fp << std::endl;
2404   }
2405
2406   SALOMEDSImpl_ChildIterator Itr = theStudy->NewChildIterator(theSO);
2407   std::string aNewTab("   ");
2408   aNewTab+=aTab;
2409   for(; Itr.More(); Itr.Next()) {
2410     dumpSO(Itr.Value(), fp, aNewTab, theStudy);
2411   }
2412
2413   return;
2414 }
2415
2416 void SALOMEDSImpl_Study::Modify()
2417 {
2418   _errorCode = "";
2419   _doc->SetModified(true);
2420 }
2421
2422 //============================================================================
2423 /*! Function :
2424  *  Purpose  :
2425  */
2426 //============================================================================
2427 SALOMEDSImpl_AttributeParameter* SALOMEDSImpl_Study::GetCommonParameters(const char* theID, int theSavePoint)
2428 {
2429   if (theSavePoint < -1) return NULL;
2430   SALOMEDSImpl_StudyBuilder* builder = NewBuilder();
2431   SALOMEDSImpl_SObject so = FindComponent((char*)theID);
2432   if (!so) so = builder->NewComponent((char*)theID);
2433   SALOMEDSImpl_AttributeParameter* attParam = NULL;
2434
2435   if (theSavePoint == -1) {
2436     int ctag = 1;
2437     DF_Label savePointLabel = so.GetLabel().FindChild( ctag, /*create=*/0 );
2438     DF_Label prevPointLabel;
2439     while ( !savePointLabel.IsNull() ) {
2440       ctag++;
2441       prevPointLabel = savePointLabel;
2442       savePointLabel = so.GetLabel().FindChild( ctag, /*create=*/0 );
2443     }
2444     if ( !prevPointLabel.IsNull() )
2445       so = GetSObject( prevPointLabel );
2446   }
2447   if (theSavePoint > 0) { // Try to find SObject that contains attribute parameter ...
2448     DF_Label savePointLabel = so.GetLabel().FindChild( theSavePoint, /*create=*/0 );
2449     if ( !savePointLabel.IsNull() )
2450       so = GetSObject( savePointLabel );
2451     else // ... if it does not exist - create a new one
2452       so = builder->NewObjectToTag( so, theSavePoint );
2453   }
2454
2455   DF_Attribute* A;
2456   if (so) {
2457     builder->FindAttribute(so, A, "AttributeParameter");
2458     if ( !A ) { // first call of GetCommonParameters on "Interface Applicative" component
2459       A = builder->FindOrCreateAttribute(so, "AttributeParameter");
2460     }
2461     attParam = dynamic_cast<SALOMEDSImpl_AttributeParameter*>( A );
2462   }
2463   return attParam;
2464 }
2465
2466 //============================================================================
2467 /*! Function :
2468  *  Purpose  :
2469  */
2470 //============================================================================
2471 SALOMEDSImpl_AttributeParameter* SALOMEDSImpl_Study::GetModuleParameters(const char* theID,
2472                                                                          const char* theModuleName,
2473                                                                          int theSavePoint)
2474 {
2475   if(theSavePoint < -1) return NULL;
2476   SALOMEDSImpl_AttributeParameter* main_ap = GetCommonParameters(theID, theSavePoint);
2477   SALOMEDSImpl_SObject main_so = main_ap->GetSObject();
2478   SALOMEDSImpl_AttributeParameter* par = NULL;
2479
2480   SALOMEDSImpl_ChildIterator it = NewChildIterator(main_so);
2481   std::string moduleName(theModuleName);
2482   for(; it.More(); it.Next()) {
2483     SALOMEDSImpl_SObject so(it.Value());
2484     if((par=(SALOMEDSImpl_AttributeParameter*)so.GetLabel().FindAttribute(SALOMEDSImpl_AttributeParameter::GetID()))) {
2485       if(!par->IsSet("AP_MODULE_NAME", (Parameter_Types)3)) continue; //3 -> PT_STRING
2486       if(par->GetString("AP_MODULE_NAME") == moduleName) return par;
2487     }
2488   }
2489
2490   SALOMEDSImpl_StudyBuilder* builder = NewBuilder();
2491   SALOMEDSImpl_SObject so = builder->NewObject(main_so);
2492   par  = dynamic_cast<SALOMEDSImpl_AttributeParameter*>(builder->FindOrCreateAttribute(so, "AttributeParameter"));
2493   par->SetString("AP_MODULE_NAME", moduleName);
2494   return par;
2495 }
2496
2497 //============================================================================
2498 /*! Function : SetStudyLock
2499  *  Purpose  :
2500  */
2501 //============================================================================
2502 void SALOMEDSImpl_Study::SetStudyLock(const char* theLockerID)
2503 {
2504   _lockers.push_back(theLockerID);
2505 }
2506
2507 //============================================================================
2508 /*! Function : IsStudyLocked
2509  *  Purpose  :
2510  */
2511 //============================================================================
2512 bool SALOMEDSImpl_Study::IsStudyLocked()
2513 {
2514   return (_lockers.size() > 0);
2515 }
2516
2517 //============================================================================
2518 /*! Function : UnLockStudy
2519  *  Purpose  :
2520  */
2521 //============================================================================
2522 void SALOMEDSImpl_Study::UnLockStudy(const char* theLockerID)
2523 {
2524   std::vector<std::string>::iterator vsI = _lockers.begin();
2525   int length = _lockers.size();
2526   bool isFound = false;
2527   std::string id(theLockerID);
2528   for(int i = 0; i<length; i++, vsI++) {
2529     if(id == _lockers[i]) {
2530       isFound = true;;
2531       break;
2532     }
2533   }
2534   if(isFound) _lockers.erase(vsI);
2535 }
2536
2537 //============================================================================
2538 /*! Function : GetLockerID
2539  *  Purpose  :
2540  */
2541 //============================================================================
2542 std::vector<std::string> SALOMEDSImpl_Study::GetLockerID()
2543 {
2544   return _lockers;
2545 }
2546
2547 //============================================================================
2548 /*! Function : SetVariable
2549  *  Purpose  :
2550  */
2551 //============================================================================
2552 void SALOMEDSImpl_Study::SetVariable(const std::string& theVarName,
2553                                      const double theValue,
2554                                      const SALOMEDSImpl_GenericVariable::VariableTypes theType)
2555 {
2556   bool modified = false;
2557   SALOMEDSImpl_GenericVariable* aGVar = GetVariable(theVarName);
2558
2559   if( aGVar == NULL ) {
2560
2561     SALOMEDSImpl_ScalarVariable* aSVar = new SALOMEDSImpl_ScalarVariable(theType, theVarName);
2562
2563     aSVar->setValue(theValue);
2564     myNoteBookVars.push_back(aSVar);
2565     modified = true;
2566   }
2567   else {
2568     if(SALOMEDSImpl_ScalarVariable* aSVar = dynamic_cast<SALOMEDSImpl_ScalarVariable*>(aGVar)) {
2569       modified = aSVar->setValue(theValue) || modified;
2570       modified = aSVar->setType(theType) || modified;
2571     }
2572   }
2573   if(modified)
2574     Modify();
2575 }
2576
2577 //============================================================================
2578 /*! Function : SetStringVariable
2579  *  Purpose  :
2580  */
2581 //============================================================================
2582 void SALOMEDSImpl_Study::SetStringVariable(const std::string& theVarName,
2583                                            const std::string& theValue,
2584                                            const SALOMEDSImpl_GenericVariable::VariableTypes theType)
2585 {
2586   bool modified = false;
2587   SALOMEDSImpl_GenericVariable* aGVar = GetVariable(theVarName);
2588
2589   if( aGVar == NULL ) {
2590
2591     SALOMEDSImpl_ScalarVariable* aSVar = new SALOMEDSImpl_ScalarVariable(theType, theVarName);
2592
2593     aSVar->setStringValue(theValue);
2594     myNoteBookVars.push_back(aSVar);
2595     modified = true;
2596   }
2597   else {
2598     if(SALOMEDSImpl_ScalarVariable* aSVar = dynamic_cast<SALOMEDSImpl_ScalarVariable*>(aGVar)) {
2599       modified = aSVar->setStringValue(theValue) || modified;
2600       modified = aSVar->setType(theType) || modified;
2601     }
2602   }
2603   if(modified)
2604     Modify();
2605 }
2606
2607 //============================================================================
2608 /*! Function : SetStringVariableAsDouble
2609  *  Purpose  :
2610  */
2611 //============================================================================
2612 void SALOMEDSImpl_Study::SetStringVariableAsDouble(const std::string& theVarName,
2613                                                    const double theValue,
2614                                                    const SALOMEDSImpl_GenericVariable::VariableTypes theType)
2615 {
2616   SALOMEDSImpl_GenericVariable* aGVar = GetVariable(theVarName);
2617   if(SALOMEDSImpl_ScalarVariable* aSVar = dynamic_cast<SALOMEDSImpl_ScalarVariable*>(aGVar))
2618     aSVar->setValue(theValue);
2619 }
2620
2621 //============================================================================
2622 /*! Function : GetReal
2623  *  Purpose  :
2624  */
2625 //============================================================================
2626 double SALOMEDSImpl_Study::GetVariableValue(const std::string& theVarName)
2627 {
2628   SALOMEDSImpl_GenericVariable* aGVar = GetVariable(theVarName);
2629
2630   if(aGVar != NULL )
2631     if(SALOMEDSImpl_ScalarVariable* aSVar = dynamic_cast<SALOMEDSImpl_ScalarVariable*>(aGVar))
2632       return aSVar->getValue();
2633
2634   return 0;
2635 }
2636
2637 //============================================================================
2638 /*! Function : GetString
2639  *  Purpose  :
2640  */
2641 //============================================================================
2642 std::string SALOMEDSImpl_Study::GetStringVariableValue(const std::string& theVarName)
2643 {
2644   SALOMEDSImpl_GenericVariable* aGVar = GetVariable(theVarName);
2645
2646   if(aGVar != NULL )
2647     if(SALOMEDSImpl_ScalarVariable* aSVar = dynamic_cast<SALOMEDSImpl_ScalarVariable*>(aGVar))
2648       return aSVar->getStringValue();
2649
2650   return 0;
2651 }
2652
2653 //============================================================================
2654 /*! Function : IsTypeOf
2655  *  Purpose  :
2656  */
2657 //============================================================================
2658 bool SALOMEDSImpl_Study::IsTypeOf(const std::string& theVarName,
2659                                   SALOMEDSImpl_GenericVariable::
2660                                   VariableTypes theType) const
2661 {
2662   SALOMEDSImpl_GenericVariable* aGVar = GetVariable(theVarName);
2663
2664   if(aGVar != NULL )
2665     return aGVar->Type() == theType;
2666
2667   return false;
2668 }
2669
2670 //============================================================================
2671 /*! Function : IsVariable
2672  *  Purpose  :
2673  */
2674 //============================================================================
2675 bool SALOMEDSImpl_Study::IsVariable(const std::string& theVarName) const
2676 {
2677   SALOMEDSImpl_GenericVariable* aGVar = GetVariable(theVarName);
2678   return (aGVar != NULL);
2679 }
2680
2681 //============================================================================
2682 /*! Function : GetVariableNames
2683  *  Purpose  :
2684  */
2685 //============================================================================
2686 std::vector<std::string> SALOMEDSImpl_Study::GetVariableNames() const
2687 {
2688   std::vector<std::string> aResult;
2689
2690   for(int i = 0; i < myNoteBookVars.size(); i++)
2691     aResult.push_back(myNoteBookVars[i]->Name());
2692
2693   return aResult;
2694 }
2695
2696 //============================================================================
2697 /*! Function : AddVariable
2698  *  Purpose  :
2699  */
2700 //============================================================================
2701 void SALOMEDSImpl_Study::AddVariable(SALOMEDSImpl_GenericVariable* theVariable)
2702 {
2703   myNoteBookVars.push_back(theVariable);
2704 }
2705
2706 //============================================================================
2707 /*! Function : AddVariable
2708  *  Purpose  :
2709  */
2710 //============================================================================
2711 SALOMEDSImpl_GenericVariable* SALOMEDSImpl_Study::GetVariable(const std::string& theName) const
2712 {
2713   SALOMEDSImpl_GenericVariable* aResult = NULL;
2714   for(int i = 0; i < myNoteBookVars.size();i++) {
2715     if(theName.compare(myNoteBookVars[i]->Name()) == 0) {
2716       aResult = myNoteBookVars[i];
2717       break;
2718     }
2719   }
2720   return aResult;
2721 }
2722
2723 //============================================================================
2724 /*! Function : RemoveVariable
2725  *  Purpose  :
2726  */
2727 //============================================================================
2728 bool SALOMEDSImpl_Study::RemoveVariable(const std::string& theVarName)
2729 {
2730   SALOMEDSImpl_GenericVariable* aVariable = GetVariable( theVarName );
2731   if( !aVariable )
2732     return false;
2733
2734   std::string aValue = aVariable->SaveToScript();
2735   ReplaceVariableAttribute( theVarName, aValue );
2736
2737   std::vector<SALOMEDSImpl_GenericVariable*>::iterator it = myNoteBookVars.begin(), itEnd = myNoteBookVars.end();
2738   for( ; it != itEnd; it++ )
2739   {
2740     SALOMEDSImpl_GenericVariable* aVariableRef = *it;
2741     if( aVariableRef && theVarName.compare( aVariableRef->Name() ) == 0 )
2742     {
2743       myNoteBookVars.erase( it );
2744       Modify();
2745       break;
2746     }
2747   }
2748
2749   return true;
2750 }
2751
2752 //============================================================================
2753 /*! Function : RenameVariable
2754  *  Purpose  :
2755  */
2756 //============================================================================
2757 bool SALOMEDSImpl_Study::RenameVariable(const std::string& theVarName, const std::string& theNewVarName)
2758 {
2759   SALOMEDSImpl_GenericVariable* aVariable = GetVariable( theVarName );
2760   if( !aVariable )
2761     return false;
2762
2763   ReplaceVariableAttribute( theVarName, theNewVarName );
2764
2765   std::vector<SALOMEDSImpl_GenericVariable*>::iterator it = myNoteBookVars.begin(), itEnd = myNoteBookVars.end();
2766   for( ; it != itEnd; it++ )
2767   {
2768     SALOMEDSImpl_GenericVariable* aVariableRef = *it;
2769     if( aVariableRef && theVarName.compare( aVariableRef->Name() ) == 0 )
2770     {
2771       aVariableRef->setName( theNewVarName );
2772       Modify();
2773       break;
2774     }
2775   }
2776
2777   return true;
2778 }
2779
2780 //============================================================================
2781 /*! Function : IsVariableUsed
2782  *  Purpose  :
2783  */
2784 //============================================================================
2785 bool SALOMEDSImpl_Study::IsVariableUsed(const std::string& theVarName)
2786 {
2787   return FindVariableAttribute( theVarName );
2788 }
2789
2790 //============================================================================
2791 /*! Function : FindVariableAttribute
2792  *  Purpose  :
2793  */
2794 //============================================================================
2795 bool SALOMEDSImpl_Study::FindVariableAttribute(SALOMEDSImpl_StudyBuilder* theStudyBuilder,
2796                                                SALOMEDSImpl_SObject theSObject,
2797                                                const std::string& theName)
2798 {
2799   SALOMEDSImpl_ChildIterator anIter = NewChildIterator( theSObject );
2800   for( ; anIter.More(); anIter.Next() )
2801     if( FindVariableAttribute( theStudyBuilder, anIter.Value(), theName ) )
2802       return true;
2803
2804   DF_Attribute* anAttr;
2805   if( theStudyBuilder->FindAttribute( theSObject, anAttr, "AttributeString" ) )
2806   {
2807     if( SALOMEDSImpl_AttributeString* aStringAttr = ( SALOMEDSImpl_AttributeString* )anAttr )
2808     {
2809       std::string aString = aStringAttr->Value();
2810
2811       std::vector< std::vector<std::string> > aSections = ParseVariables( aString );
2812       for( int i = 0, n = aSections.size(); i < n; i++ )
2813       {
2814         std::vector<std::string> aVector = aSections[i];
2815         for( int j = 0, m = aVector.size(); j < m; j++ )
2816         {
2817           std::string aStr = aVector[j];
2818           if( aStr.compare( theName ) == 0 )
2819             return true;
2820         }
2821       }
2822     }
2823   }
2824   return false;
2825 }
2826
2827 //============================================================================
2828 /*! Function : FindVariableAttribute
2829  *  Purpose  :
2830  */
2831 //============================================================================
2832 bool SALOMEDSImpl_Study::FindVariableAttribute(const std::string& theName)
2833 {
2834   SALOMEDSImpl_StudyBuilder* aStudyBuilder = NewBuilder();
2835   SALOMEDSImpl_SComponentIterator aCompIter = NewComponentIterator();
2836   for( ; aCompIter.More(); aCompIter.Next() )
2837   {
2838     SALOMEDSImpl_SObject aComp = aCompIter.Value();
2839     if( FindVariableAttribute( aStudyBuilder, aComp, theName ) )
2840       return true;
2841   }
2842   return false;
2843 }
2844
2845 //============================================================================
2846 /*! Function : ReplaceVariableAttribute
2847  *  Purpose  :
2848  */
2849 //============================================================================
2850 void SALOMEDSImpl_Study::ReplaceVariableAttribute(SALOMEDSImpl_StudyBuilder* theStudyBuilder,
2851                                                   SALOMEDSImpl_SObject theSObject,
2852                                                   const std::string& theSource,
2853                                                   const std::string& theDest)
2854 {
2855   SALOMEDSImpl_ChildIterator anIter = NewChildIterator( theSObject );
2856   for( ; anIter.More(); anIter.Next() )
2857     ReplaceVariableAttribute( theStudyBuilder, anIter.Value(), theSource, theDest );
2858
2859   DF_Attribute* anAttr;
2860   if( theStudyBuilder->FindAttribute( theSObject, anAttr, "AttributeString" ) )
2861   {
2862     if( SALOMEDSImpl_AttributeString* aStringAttr = ( SALOMEDSImpl_AttributeString* )anAttr )
2863     {
2864       bool isChanged = false;
2865       std::string aNewString, aCurrentString = aStringAttr->Value();
2866
2867       std::vector< std::vector<std::string> > aSections = ParseVariables( aCurrentString );
2868       for( int i = 0, n = aSections.size(); i < n; i++ )
2869       {
2870         std::vector<std::string> aVector = aSections[i];
2871         for( int j = 0, m = aVector.size(); j < m; j++ )
2872         {
2873           std::string aStr = aVector[j];
2874           if( aStr.compare( theSource ) == 0 )
2875           {
2876             isChanged = true;
2877             aStr = theDest;
2878           }
2879
2880           aNewString.append( aStr );
2881           if( j != m - 1 )
2882             aNewString.append( ":" );
2883         }
2884         if( i != n - 1 )
2885           aNewString.append( "|" );
2886       }
2887
2888       if( isChanged )
2889         aStringAttr->SetValue( aNewString );
2890     }
2891   }
2892 }
2893
2894 //============================================================================
2895 /*! Function : ReplaceVariableAttribute
2896  *  Purpose  :
2897  */
2898 //============================================================================
2899 void SALOMEDSImpl_Study::ReplaceVariableAttribute(const std::string& theSource, const std::string& theDest)
2900 {
2901   SALOMEDSImpl_StudyBuilder* aStudyBuilder = NewBuilder();
2902   SALOMEDSImpl_SComponentIterator aCompIter = NewComponentIterator();
2903   for( ; aCompIter.More(); aCompIter.Next() )
2904   {
2905     SALOMEDSImpl_SObject aComp = aCompIter.Value();
2906     ReplaceVariableAttribute( aStudyBuilder, aComp, theSource, theDest );
2907   }
2908 }
2909
2910 //============================================================================
2911 /*! Function : ParseVariables
2912  *  Purpose  :
2913  */
2914 //============================================================================
2915 std::vector< std::vector< std::string > > SALOMEDSImpl_Study::ParseVariables(const std::string& theVariables) const
2916 {
2917   return SALOMEDSImpl_Tool::splitStringWithEmpty( theVariables, OPERATION_SEPARATOR, VARIABLE_SEPARATOR );
2918 }
2919
2920 //============================================================================
2921 /*! Function : EnableUseCaseAutoFilling
2922  *  Purpose  :
2923  */
2924 //============================================================================
2925 void SALOMEDSImpl_Study::EnableUseCaseAutoFilling(bool isEnabled)
2926 {
2927   _errorCode = ""; _autoFill = isEnabled;
2928   if(isEnabled) {
2929     _builder->SetOnAddSObject(_cb);
2930     _builder->SetOnRemoveSObject(_cb);
2931   }
2932   else {
2933     _builder->SetOnAddSObject(NULL);
2934     _builder->SetOnRemoveSObject(NULL);
2935   }
2936 }
2937
2938 //============================================================================
2939 /*! Function : GetIORs
2940  *  Purpose  :
2941  */
2942 //============================================================================
2943 std::vector<std::string> SALOMEDSImpl_Study::GetIORs()
2944 {
2945   std::vector<std::string> anIORs;
2946   std::map<std::string, DF_Label>::const_iterator MI;
2947   for(MI = myIORLabels.begin(); MI!=myIORLabels.end(); MI++)
2948     anIORs.push_back(MI->first);
2949
2950   return anIORs;
2951 }
2952
2953 //============================================================================
2954 /*! Function : addSO_Notification
2955  *  Purpose  : This function tells all the observers that a SO has been added
2956  */
2957 //============================================================================
2958 bool SALOMEDSImpl_Study::addSO_Notification (const SALOMEDSImpl_SObject& theSObject)
2959 {
2960   if(_notifier)
2961     return _notifier->addSO_Notification(theSObject);
2962   else
2963     return false;
2964 }
2965
2966 //============================================================================
2967 /*! Function : removeSO_Notification
2968  *  Purpose  : This function tells all the observers that a SO has been removed
2969  */
2970 //============================================================================
2971 bool SALOMEDSImpl_Study::removeSO_Notification (const SALOMEDSImpl_SObject& theSObject)
2972 {
2973   if(_notifier)
2974     return _notifier->removeSO_Notification(theSObject);
2975   else
2976     return false;
2977 }
2978
2979 //============================================================================
2980 /*! Function : modifySO_Notification
2981  *  Purpose  : This function tells all the observers that a SO has been modified and
2982                pass the mofification reason
2983  */
2984 //============================================================================
2985 bool SALOMEDSImpl_Study::modifySO_Notification (const SALOMEDSImpl_SObject& theSObject, int reason)
2986 {
2987   if(_notifier)
2988     return _notifier->modifySO_Notification(theSObject, reason);
2989   else
2990     return false;
2991 }
2992
2993 //============================================================================
2994 /*! Function : setNotifier
2995  *  Purpose  : register a notifier
2996  */
2997 //============================================================================
2998 void SALOMEDSImpl_Study::setNotifier(SALOMEDSImpl_AbstractCallback* notifier)
2999 {
3000   _notifier=notifier;
3001 }
3002
3003 static SALOMEDSImpl_AbstractCallback* & getGenObjRegister( DF_Document* doc )
3004 {
3005   static std::vector< SALOMEDSImpl_AbstractCallback* > _genObjRegVec;
3006   if ( doc->GetDocumentID() >= (int)_genObjRegVec.size() )
3007     _genObjRegVec.resize( doc->GetDocumentID() + 1, 0 );
3008   return _genObjRegVec[ doc->GetDocumentID() ];
3009 }
3010
3011 //================================================================================
3012 /*!
3013  * \brief Stores theRegister
3014  */
3015 //================================================================================
3016
3017 void SALOMEDSImpl_Study::setGenObjRegister(SALOMEDSImpl_AbstractCallback* theRegister)
3018 {
3019   getGenObjRegister( _doc ) = theRegister;
3020 }
3021
3022 //================================================================================
3023 /*!
3024  * \brief Indirectly invokes GenericObj_i::Register()
3025  */
3026 //================================================================================
3027
3028 void SALOMEDSImpl_Study::RegisterGenObj  (const std::string& theIOR, DF_Label label)
3029 {
3030   if ( SALOMEDSImpl_AbstractCallback* goRegister = getGenObjRegister( label.GetDocument() ))
3031     goRegister->RegisterGenObj( theIOR );
3032 }
3033
3034 //================================================================================
3035 /*!
3036  * \brief Indirectly invokes GenericObj_i::UnRegister()
3037  */
3038 //================================================================================
3039
3040 void SALOMEDSImpl_Study::UnRegisterGenObj(const std::string& theIOR, DF_Label label)
3041 {
3042   if ( SALOMEDSImpl_AbstractCallback* goRegister = getGenObjRegister( label.GetDocument() ))
3043     goRegister->UnRegisterGenObj( theIOR );
3044 }
3045
3046 //#######################################################################################################
3047 //#                                     STATIC PRIVATE FUNCTIONS
3048 //#######################################################################################################
3049
3050 //============================================================================
3051 /*! Function : SaveAttributes
3052  *  Purpose  : Save attributes for object
3053  */
3054 //============================================================================
3055 static void SaveAttributes(const SALOMEDSImpl_SObject& aSO, HDFgroup *hdf_group_sobject)
3056 {
3057   hdf_size size[1];
3058   std::vector<DF_Attribute*> attrList = aSO.GetLabel().GetAttributes();
3059   DF_Attribute* anAttr = NULL;
3060   for(int i = 0, len = attrList.size(); i<len; i++) {
3061     anAttr = attrList[i];
3062     //The following attributes are not supposed to be written to the file
3063     std::string type = SALOMEDSImpl_GenericAttribute::Impl_GetType(anAttr);
3064     if(type == std::string("AttributeIOR")) continue; //IOR attribute is not saved
3065     std::string aSaveStr =anAttr->Save();
3066     //cout << "Saving: " << aSO.GetID() << " type: "<< type<<"|" << endl;
3067     size[0] = (hdf_int32) strlen(aSaveStr.c_str()) + 1;
3068     HDFdataset *hdf_dataset = new HDFdataset((char*)type.c_str(), hdf_group_sobject, HDF_STRING,size, 1);
3069     hdf_dataset->CreateOnDisk();
3070     hdf_dataset->WriteOnDisk((char*)aSaveStr.c_str());
3071     hdf_dataset->CloseOnDisk();
3072     hdf_dataset=0; //will be deleted by hdf_sco_group destructor
3073   }
3074 }
3075
3076 //===========================================================================
3077 //Function : ReadAttributes
3078 //===========================================================================
3079 static void ReadAttributes(SALOMEDSImpl_Study* theStudy,
3080                            const SALOMEDSImpl_SObject& aSO,
3081                            HDFdataset* hdf_dataset)
3082 {
3083   hdf_dataset->OpenOnDisk();
3084
3085   DF_Attribute* anAttr = NULL;
3086   char* current_string = new char[hdf_dataset->GetSize()+1];
3087   hdf_dataset->ReadFromDisk(current_string);
3088   //cout << "Reading attr type = " << hdf_dataset->GetName() << "  SO = " << aSO.GetID() << endl;
3089   if (!strcmp(hdf_dataset->GetName(),"COMPONENTDATATYPE")) {
3090     anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, "AttributeComment");
3091   }
3092   else if (!strcmp(hdf_dataset->GetName(),"AttributeReference") ||
3093            !strcmp(hdf_dataset->GetName(),"Reference")) { // Old format maintenance
3094     theStudy->NewBuilder()->Addreference(aSO, theStudy->CreateObjectID(current_string));
3095     delete [] (current_string);
3096     hdf_dataset->CloseOnDisk();
3097     return;
3098   }
3099   else {
3100     anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, hdf_dataset->GetName());
3101   }
3102
3103   if (anAttr) {
3104     anAttr->Load(current_string);
3105   }
3106
3107   delete [] (current_string);
3108   hdf_dataset->CloseOnDisk();
3109 }
3110
3111 //============================================================================
3112 //Function : BuildlTree
3113 //============================================================================
3114 static void BuildTree (SALOMEDSImpl_Study* theStudy, HDFgroup* hdf_current_group)
3115 {
3116   hdf_current_group->OpenOnDisk();
3117   SALOMEDSImpl_SObject aSO;
3118   char* Entry = hdf_current_group->GetName();
3119   if (strcmp(Entry,"STUDY_STRUCTURE") == 0) {
3120     aSO = theStudy->CreateObjectID("0:1");
3121   }
3122   else {
3123     aSO = theStudy->CreateObjectID(Entry);
3124   }
3125
3126   char name[HDF_NAME_MAX_LEN+1];
3127   int nbsons = hdf_current_group->nInternalObjects();
3128   for (int i=0; i<nbsons; i++) {
3129     hdf_current_group->InternalObjectIndentify(i,name);
3130     if (strncmp(name, "INTERNAL_COMPLEX",16) == 0) continue;
3131     hdf_object_type type = hdf_current_group->InternalObjectType(name);
3132
3133     if (type == HDF_DATASET) {
3134       HDFdataset* new_dataset = new HDFdataset(name,hdf_current_group);
3135       ReadAttributes(theStudy,aSO,new_dataset);
3136       new_dataset = 0; // will be deleted by father destructor
3137     }
3138     else if (type == HDF_GROUP)   {
3139       HDFgroup* new_group = new HDFgroup(name,hdf_current_group);
3140       BuildTree (theStudy, new_group);
3141       new_group = 0; // will be deleted by father destructor
3142     }
3143   }
3144   hdf_current_group->CloseOnDisk();
3145 }
3146
3147
3148 //============================================================================
3149 //Function : Translate_IOR_to_persistentID
3150 //============================================================================
3151 static void Translate_IOR_to_persistentID (const SALOMEDSImpl_SObject& so,
3152                                            SALOMEDSImpl_Driver*        engine,
3153                                            bool                        isMultiFile,
3154                                            bool                        isASCII)
3155 {
3156   DF_ChildIterator itchild(so.GetLabel());
3157   std::string ior_string,  persistent_string, curid;
3158
3159   for (; itchild.More(); itchild.Next()) {
3160     SALOMEDSImpl_SObject current = SALOMEDSImpl_Study::SObject(itchild.Value());
3161     SALOMEDSImpl_AttributeIOR* IOR = NULL;
3162     if ((IOR=(SALOMEDSImpl_AttributeIOR*)current.GetLabel().FindAttribute(SALOMEDSImpl_AttributeIOR::GetID()))) {
3163       ior_string = IOR->Value();
3164
3165       persistent_string = engine->IORToLocalPersistentID (current, ior_string, isMultiFile, isASCII);
3166       SALOMEDSImpl_AttributePersistentRef::Set(current.GetLabel(), persistent_string);
3167     }
3168     Translate_IOR_to_persistentID (current, engine, isMultiFile, isASCII);
3169   }
3170 }
3171
3172 void ReadNoteBookVariables(SALOMEDSImpl_Study* theStudy, HDFgroup* theGroup)
3173 {
3174   if(!theGroup)
3175     return;
3176
3177   HDFgroup* new_group =0;
3178   HDFdataset* new_dataset =0;
3179
3180   char aVarName[HDF_NAME_MAX_LEN+1];
3181   char *currentVarType = 0;
3182   char *currentVarValue = 0;
3183   char *currentVarIndex = 0;
3184   int order = 0;
3185   //Open HDF group with notebook variables
3186   theGroup->OpenOnDisk();
3187
3188   //Get Nb of variables
3189   int aNbVars = theGroup->nInternalObjects();
3190
3191   std::map<int,SALOMEDSImpl_GenericVariable*> aVarsMap;
3192
3193   for( int iVar=0;iVar < aNbVars;iVar++ ) {
3194     theGroup->InternalObjectIndentify(iVar,aVarName);
3195     hdf_object_type type = theGroup->InternalObjectType(aVarName);
3196     if(type == HDF_GROUP) {
3197
3198       //Read Variable
3199       new_group = new HDFgroup(aVarName,theGroup);
3200       new_group->OpenOnDisk();
3201
3202       //Read Type
3203       new_dataset = new HDFdataset("VARIABLE_TYPE",new_group);
3204       new_dataset->OpenOnDisk();
3205       currentVarType = new char[new_dataset->GetSize()+1];
3206       new_dataset->ReadFromDisk(currentVarType);
3207       new_dataset->CloseOnDisk();
3208       new_dataset = 0; //will be deleted by hdf_sco_group destructor
3209
3210       //Read Order
3211       if(new_group->ExistInternalObject("VARIABLE_INDEX")) {
3212         new_dataset = new HDFdataset("VARIABLE_INDEX",new_group);
3213         new_dataset->OpenOnDisk();
3214         currentVarIndex = new char[new_dataset->GetSize()+1];
3215         new_dataset->ReadFromDisk(currentVarIndex);
3216         new_dataset->CloseOnDisk();
3217         new_dataset = 0; //will be deleted by hdf_sco_group destructor
3218         order = atoi(currentVarIndex);
3219         delete [] currentVarIndex;
3220       }
3221       else
3222         order = iVar;
3223
3224       //Read Value
3225       new_dataset = new HDFdataset("VARIABLE_VALUE",new_group);
3226       new_dataset->OpenOnDisk();
3227       currentVarValue = new char[new_dataset->GetSize()+1];
3228       new_dataset->ReadFromDisk(currentVarValue);
3229       new_dataset->CloseOnDisk();
3230       new_dataset = 0; //will be deleted by hdf_sco_group destructor
3231
3232       new_group->CloseOnDisk();
3233       new_group = 0;  //will be deleted by hdf_sco_group destructor
3234
3235       SALOMEDSImpl_GenericVariable::VariableTypes aVarType =
3236         SALOMEDSImpl_GenericVariable::String2VariableType(std::string(currentVarType));
3237       delete [] currentVarType;
3238
3239       //Create variable and add it in the study
3240       SALOMEDSImpl_GenericVariable* aVariable =
3241         new SALOMEDSImpl_ScalarVariable(aVarType,std::string(aVarName));
3242       aVariable->Load(std::string(currentVarValue));
3243       aVarsMap.insert(std::make_pair(order,aVariable));
3244       delete [] currentVarValue;
3245     }
3246   }
3247
3248   std::map<int,SALOMEDSImpl_GenericVariable*>::const_iterator it= aVarsMap.begin();
3249   for(;it!=aVarsMap.end();it++)
3250     theStudy->AddVariable((*it).second);
3251
3252   theGroup->CloseOnDisk();
3253 }