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