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