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