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