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