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