Salome HOME
Merge from V6_main 01/04/2013
[modules/kernel.git] / src / SALOMEDSImpl / SALOMEDSImpl_StudyManager.cxx
1 // Copyright (C) 2007-2013  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.
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_StudyManager.cxx
24 //  Author : Sergey RUIN
25 //  Module : SALOME
26 //
27 #include "SALOMEDSImpl_StudyManager.hxx"
28
29 #include "DF_ChildIterator.hxx"
30 #include "HDFexplorer.hxx"
31 #include "Basics_Utils.hxx"
32
33 //Warning undef of Ascii Winwows define
34 #ifdef WIN32
35 # undef GetUserName
36 #endif
37
38 #include "SALOMEDSImpl_Attributes.hxx"
39 #include "SALOMEDSImpl_Tool.hxx"
40 #include "SALOMEDSImpl_SComponent.hxx"
41 #include "SALOMEDSImpl_GenericAttribute.hxx"
42 #include "SALOMEDSImpl_ScalarVariable.hxx"
43 #include "SALOMEDSImpl_IParameters.hxx"
44 #include <map>
45
46 #include "HDFOI.hxx"
47 #include <iostream>
48 #include <stdlib.h>
49 #include <string.h>
50
51 #define USE_CASE_LABEL_ID                       "0:2"
52
53 static void SaveAttributes(const SALOMEDSImpl_SObject& SO, HDFgroup *hdf_group_sobject);
54 static void ReadAttributes(SALOMEDSImpl_Study*, const SALOMEDSImpl_SObject&, HDFdataset* );
55 static void BuildTree (SALOMEDSImpl_Study*, HDFgroup*);
56 static void Translate_IOR_to_persistentID (const SALOMEDSImpl_SObject&,
57                                            SALOMEDSImpl_Driver*, bool isMultiFile, bool isASCII);
58 static void ReadNoteBookVariables(SALOMEDSImpl_Study* theStudy, HDFgroup* theGroup);
59
60 namespace {
61   class StudyUnlocker
62   {
63   public:
64     StudyUnlocker( SALOMEDSImpl_Study* study ): myStudy( study ), myLocked( false )
65     {
66       myPrevLocked = myStudy->GetProperties()->IsLocked();
67       resume();
68     }
69     ~StudyUnlocker()
70     {
71       suspend();
72     }
73     void suspend()
74     {
75       if (myLocked) {
76         myStudy->GetProperties()->SetLocked(true);
77         myPrevLocked = myLocked;
78         myLocked = false;
79       }
80     }
81     void resume()
82     {
83       if (myPrevLocked) { 
84         myStudy->GetProperties()->SetLocked(false);
85         myLocked = myPrevLocked;
86         myPrevLocked = false;
87       }
88     }
89   private:
90     SALOMEDSImpl_Study* myStudy;
91     bool myLocked;
92     bool myPrevLocked;
93   };
94 }
95
96 //============================================================================
97 /*! Function : SALOMEDSImpl_StudyManager
98  *  Purpose  : SALOMEDSImpl_StudyManager constructor
99  */
100 //============================================================================
101 SALOMEDSImpl_StudyManager::SALOMEDSImpl_StudyManager()
102 {
103   _errorCode = "";
104   _appli = new DF_Application();
105   _IDcounter = 0;
106   _clipboard = _appli->NewDocument("SALOME_STUDY");
107 }
108
109 //============================================================================
110 /*! Function : ~SALOMEDSImpl_StudyManager
111  *  Purpose  : SALOMEDSImpl_StudyManager destructor
112  */
113 //============================================================================
114 SALOMEDSImpl_StudyManager::~SALOMEDSImpl_StudyManager()
115 {
116   _appli->Close(_clipboard);
117   // Destroy application
118   delete _appli;    
119 }
120
121
122 //============================================================================
123 /*! Function : NewStudy
124  *  Purpose  : Create a New Study of name study_name
125  */
126 //==================================================T==========================
127 SALOMEDSImpl_Study* SALOMEDSImpl_StudyManager::NewStudy(const std::string& study_name)
128 {
129   _errorCode = "";
130
131   DF_Document* Doc = _appli->NewDocument("SALOME_STUDY");
132
133   SALOMEDSImpl_Study* Study = new SALOMEDSImpl_Study(Doc, study_name);
134
135   _IDcounter++;
136   Study->StudyId( _IDcounter );
137
138   // set Study properties
139   SALOMEDSImpl_AttributeStudyProperties* aProp = Study->GetProperties();
140   
141   int month=0,day=0,year=0,hh=0,mn=0,ss=0;
142   SALOMEDSImpl_Tool::GetSystemDate(year, month, day, hh, mn, ss);
143   aProp->SetModification(SALOMEDSImpl_Tool::GetUserName(),
144                          mn, hh, day, month, year);
145   aProp->SetCreationMode(1);  //"from scratch"
146
147   return Study;
148 }
149
150 //============================================================================
151 /*! Function : Open
152  *  Purpose  : Open a Study from it's persistent reference
153  */
154 //============================================================================
155 SALOMEDSImpl_Study* SALOMEDSImpl_StudyManager::Open(const std::string& aUrl)
156 {
157   // Set "C" locale temporarily to avoid possible localization problems
158   Kernel_Utils::Localizer loc;
159
160   _errorCode = "";
161
162   // open the HDFFile
163   HDFfile *hdf_file =0;
164   HDFgroup *hdf_group_study_structure =0;
165   HDFgroup *hdf_notebook_vars = 0; 
166
167   char* aC_HDFUrl;
168   std::string aHDFUrl;
169   bool isASCII = false;
170   if (HDFascii::isASCII(aUrl.c_str())) {
171     isASCII = true;
172     char* aResultPath = HDFascii::ConvertFromASCIIToHDF(aUrl.c_str());
173     if ( !aResultPath )
174       return NULL;
175     aC_HDFUrl = new char[strlen(aResultPath) + 19];
176     sprintf(aC_HDFUrl, "%shdf_from_ascii.hdf", aResultPath);
177     delete [] (aResultPath);
178     aHDFUrl = aC_HDFUrl;
179     delete [] aC_HDFUrl;
180   } else {
181     aHDFUrl = aUrl;
182   }
183
184   
185   hdf_file = new HDFfile((char*)aHDFUrl.c_str());
186   try {
187     hdf_file->OpenOnDisk(HDF_RDONLY);// mpv: was RDWR, but opened file can be write-protected too
188   }
189   catch (HDFexception)
190   {
191     char *eStr;
192     eStr = new char[strlen(aUrl.c_str())+17];
193     sprintf(eStr,"Can't open file %s",aUrl.c_str());
194     delete [] eStr;
195     _errorCode = std::string(eStr);
196     return NULL;
197   }
198   
199   // Temporary aStudyUrl in place of study name
200   DF_Document* Doc = _appli->NewDocument("SALOME_STUDY");
201
202   SALOMEDSImpl_Study* Study = new SALOMEDSImpl_Study(Doc, aUrl);
203
204   _IDcounter++;
205   Study->StudyId( _IDcounter );
206
207   // Assign the value of the URL in the study object
208   Study->URL (aUrl);
209
210   SALOMEDSImpl_AttributePersistentRef::Set(Doc->Main(), aUrl);
211
212   if (!hdf_file->ExistInternalObject("STUDY_STRUCTURE")) {
213      _errorCode = "Study is empty";
214     return Study;
215   }
216
217   //Create  the Structure of the Document
218   hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
219
220   try {
221     BuildTree (Study, hdf_group_study_structure);
222   }
223   catch (HDFexception)
224   {
225     char *eStr = new char [strlen(aUrl.c_str())+17];
226     sprintf(eStr,"Can't open file %s", aUrl.c_str());
227     _errorCode = std::string(eStr);
228     return NULL;
229   }
230   
231   //Read and create notebook variables 
232   if(hdf_file->ExistInternalObject("NOTEBOOK_VARIABLES")) {
233     hdf_notebook_vars  = new HDFgroup("NOTEBOOK_VARIABLES",hdf_file);
234     ReadNoteBookVariables(Study,hdf_notebook_vars);
235     hdf_notebook_vars =0; //will be deleted by hdf_sco_group destructor
236   }
237
238   hdf_file->CloseOnDisk();
239   hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
240   
241   if (isASCII) {
242     std::vector<std::string> aFilesToRemove;
243     aFilesToRemove.push_back("hdf_from_ascii.hdf");
244     SALOMEDSImpl_Tool::RemoveTemporaryFiles(SALOMEDSImpl_Tool::GetDirFromPath(aHDFUrl), aFilesToRemove, true);
245   }
246
247   delete hdf_file; // all related hdf objects will be deleted
248
249   // unlock study if it is locked, to set components versions
250   StudyUnlocker unlock(Study);
251
252   //For old studies we have to add "unknown" version tag for all stored components
253   SALOMEDSImpl_SComponentIterator itcomponent = Study->NewComponentIterator();
254   for (; itcomponent.More(); itcomponent.Next())
255   {
256     SALOMEDSImpl_SComponent sco = itcomponent.Value();
257     std::string aCompType = sco.GetComment();
258     if ( aCompType == SALOMEDSImpl_IParameters::getDefaultVisualComponent() ) continue;
259     if ( Study->GetProperties()->GetComponentVersions( aCompType ).empty() )
260       Study->GetProperties()->SetComponentVersion( aCompType, "" ); // empty version means "unknown"
261   }
262
263   return Study;
264 }
265
266
267
268 //============================================================================
269 /*! Function : Close
270  *  Purpose  : Close a study.
271  *             If the study hasn't been saved, ask the user to confirm the
272  *             close action without saving
273  */
274
275 //============================================================================
276 void  SALOMEDSImpl_StudyManager::Close(SALOMEDSImpl_Study* aStudy)
277 {
278   _errorCode = "";
279
280   if(!aStudy) {
281     _errorCode = "Study is null";
282     return;
283   }
284
285   aStudy->Close();
286   DF_Document* doc=aStudy->GetDocument();
287   _appli->Close(doc);
288 }
289
290 //============================================================================
291 /*! Function : Save
292  *  Purpose  : Save a Study to it's persistent reference
293  */
294 //============================================================================
295 bool SALOMEDSImpl_StudyManager::Save(SALOMEDSImpl_Study* aStudy,
296                                      SALOMEDSImpl_DriverFactory* aFactory,
297                                      bool theMultiFile)
298 {
299   _errorCode = "";
300
301   std::string url = aStudy->URL();
302   if (url.empty()) {
303     _errorCode = "No path specified to save the study. Nothing done";
304     return false;
305   }
306   else {
307     return Impl_SaveAs(url,aStudy, aFactory, theMultiFile, false);
308   }
309
310   return false;
311 }
312
313 bool SALOMEDSImpl_StudyManager::SaveASCII(SALOMEDSImpl_Study* aStudy,
314                                           SALOMEDSImpl_DriverFactory* aFactory,
315                                           bool theMultiFile)
316 {
317   _errorCode = "";
318
319   std::string url = aStudy->URL();
320   if (url.empty()) {
321     _errorCode = "No path specified to save the study. Nothing done";
322     return false;
323   }
324   else {
325     return Impl_SaveAs(url,aStudy, aFactory, theMultiFile, true);
326   }
327
328   return false;
329 }
330
331 //=============================================================================
332 /*! Function : SaveAs
333  *  Purpose  : Save a study to the persistent reference aUrl
334  */
335 //============================================================================
336 bool SALOMEDSImpl_StudyManager::SaveAs(const std::string& aUrl,
337                                        SALOMEDSImpl_Study* aStudy,
338                                        SALOMEDSImpl_DriverFactory* aFactory,
339                                        bool theMultiFile)
340 {
341   _errorCode = "";
342   return Impl_SaveAs(aUrl,aStudy, aFactory, theMultiFile, false);
343 }
344
345 bool SALOMEDSImpl_StudyManager::SaveAsASCII(const std::string& aUrl,
346                                             SALOMEDSImpl_Study* aStudy,
347                                             SALOMEDSImpl_DriverFactory* aFactory,
348                                             bool theMultiFile)
349 {
350   _errorCode = "";
351   return Impl_SaveAs(aUrl,aStudy, aFactory, theMultiFile, true);
352 }
353
354 //============================================================================
355 /*! Function : GetOpenStudies
356  *  Purpose  : Get name list of open studies in the session
357  */
358 //============================================================================
359 std::vector<SALOMEDSImpl_Study*> SALOMEDSImpl_StudyManager::GetOpenStudies()
360 {
361   _errorCode = "";
362   std::vector<SALOMEDSImpl_Study*> aList;
363
364   int nbDocs = _appli->NbDocuments();
365
366   if(nbDocs == 0) {
367     _errorCode = "No active study in this session";
368     return aList;
369   }
370   else {
371     SALOMEDSImpl_Study* aStudy;
372     std::vector<int> ids = _appli->GetDocumentIDs();
373     for (int i = 0, len = ids.size(); i<len; i++) {
374       DF_Document* D = _appli->GetDocument(ids[i]);
375       if(D == _clipboard) continue;
376       aStudy = SALOMEDSImpl_Study::GetStudy(D->Main());
377       if(!aStudy) continue;
378       aList.push_back(aStudy);
379     }
380   }
381
382   return aList;
383 }
384
385 //============================================================================
386 /*! Function : GetStudyByName
387  *  Purpose  : Get a study from its name
388  */
389 //============================================================================
390 SALOMEDSImpl_Study* SALOMEDSImpl_StudyManager::GetStudyByName
391                                    (const std::string& aStudyName)
392 {
393   _errorCode = "";
394   int nbDocs = _appli->NbDocuments();
395
396   if (nbDocs == 0) {
397     _errorCode = "No active study in this session";
398     return NULL;
399   }
400   else {
401     std::vector<SALOMEDSImpl_Study*> studies = GetOpenStudies();
402     for (int i = 0, len = studies.size(); i<len; i++) {
403       if (studies[i]->Name() == aStudyName) return studies[i];
404     }
405   }
406
407   _errorCode = std::string("Found no study with the name ") + aStudyName;
408   return NULL;
409 }
410
411 //============================================================================
412 /*! Function : GetStudyByID
413  *  Purpose  : Get a study from its ID
414  */
415 //============================================================================
416 SALOMEDSImpl_Study* SALOMEDSImpl_StudyManager::GetStudyByID(int aStudyID)
417 {
418   _errorCode = "";
419   int nbDocs = _appli->NbDocuments();
420
421   if (nbDocs == 0) {
422     _errorCode = "No active study in this session";
423     return NULL;
424   }
425   else {
426     std::vector<SALOMEDSImpl_Study*> studies = GetOpenStudies();
427     for (int i = 0, len = studies.size(); i<len; i++) {
428       if (studies[i]->StudyId() == aStudyID) return studies[i];
429     }
430   }
431
432   _errorCode = "Found no study with the given ID";
433   return NULL;
434 }
435
436 //=============================================================================
437 /*! Function : _SaveProperties
438  *  Purpose  : save the study properties in HDF file
439  */
440 //============================================================================
441 bool SALOMEDSImpl_StudyManager::Impl_SaveProperties(SALOMEDSImpl_Study* aStudy,
442                                                     HDFgroup *hdf_group)
443 {
444   _errorCode = "";
445
446   HDFdataset *hdf_dataset = 0;
447   hdf_size size[1];
448   hdf_int32 name_len;
449
450   // add modifications list (user and date of save)
451   SALOMEDSImpl_AttributeStudyProperties* aProp = aStudy->GetProperties();
452
453   // unlock study if it is locked, to set modification date
454   StudyUnlocker unlock(aStudy);
455   
456   int month=0,day=0,year=0,hh=0,mn=0,ss=0;
457   SALOMEDSImpl_Tool::GetSystemDate(year, month, day, hh, mn, ss);
458   aProp->SetModification(SALOMEDSImpl_Tool::GetUserName(),
459                          mn, hh, day, month, year);
460   
461   // lock study back if it was locked initially, to write correct value of Locked flag
462   unlock.suspend();
463
464   std::vector<std::string> aNames;
465   std::vector<int> aMinutes, aHours, aDays, aMonths, aYears;
466
467   aProp->GetModifications(aNames, aMinutes, aHours, aDays, aMonths, aYears);
468
469   std::string units = aProp->GetUnits();
470   std::string comment = aProp->GetComment();
471
472   std::map< std::string, std::vector<std::string> > allVersions = aProp->GetComponentsVersions();
473   std::map<std::string, std::string> versions;
474
475   int aLength = 0, aLength1 = 0, anIndex, i, unitsSize = 0, commentSize = 0;
476
477   for(i=1; i<=aNames.size(); i++)
478     aLength += aNames[i-1].size() + 1;
479
480   std::map< std::string, std::vector<std::string> >::const_iterator it;
481   for (it = allVersions.begin(); it != allVersions.end(); ++it ) {
482     std::string vlist = "";
483     std::vector<std::string> vl = it->second;
484     std::vector<std::string>::const_iterator vlit;
485     for ( vlit = vl.begin(); vlit != vl.end(); ++vlit ) {
486       if ( vlist != "" ) vlist += ";";
487       vlist += *vlit;
488     }
489     versions[ it->first ] = vlist;
490     aLength1 += it->first.size() + vlist.size() + 2;
491   }
492
493   unitsSize = units.size();
494   commentSize = comment.size();
495
496   //string format:
497   //locked flag, modified flag,
498   //minutes, hours, day, months, year, user name, char(1), 
499   //minutes, hours, day, months, year, user name, char(1),
500   //.....................................................,
501   //.....................................................,
502   //.....................................................,
503   //minutes, hours, day, months, year, user name, char(1), char(30) <- !!!! used to define end of section with modifications !!!!
504   //units, char(1), comment, char(30) <- !!!! used to define start of section with components' versions !!!!
505   //component=versions, char(1), 
506   //component=versions, char(1), 
507   //...........................,
508   //component=versions, char(1), char(0)
509
510   //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)
511   // unit length + 1, comment length, "zero" byte
512   
513   char* aProperty = new char[3 + aLength + 12 * aNames.size() + 1 + unitsSize + 1 + commentSize + 1 + aLength1 ];
514
515   sprintf(aProperty,"%c%c", (char)aProp->GetCreationMode(),  (aProp->IsLocked())?'l':'u');
516
517   aLength = aNames.size();
518   int a = 2;
519   for(anIndex = 0; anIndex<aLength; anIndex++) {
520     sprintf(&(aProperty[a]),"%2d%2d%2d%2d%4d%s",
521             (int)(aMinutes[anIndex]),
522             (int)(aHours[anIndex]),
523             (int)(aDays[anIndex]),
524             (int)(aMonths[anIndex]),
525             (int)(aYears[anIndex]),
526             aNames[anIndex].c_str());
527     a = strlen(aProperty);
528     aProperty[a++] = 1;
529   }
530
531   //Write delimeter of the section to define end of the modifications section
532   aProperty[a++] = 30;
533
534   //Write units if need
535   if(units.size() > 0) {
536     sprintf(&(aProperty[a]),"%s",units.c_str());
537     a = strlen(aProperty);
538   }
539
540   aProperty[a++] = 1;
541
542   //Write comments if need
543   if(comment.size() > 0) {
544     sprintf(&(aProperty[a]),"%s",comment.c_str());
545     a = strlen(aProperty);
546   }
547   
548   aProperty[a++] = 30; //delimeter of the component versions
549
550   std::map<std::string, std::string>::const_iterator versionsIt;
551   for ( versionsIt = versions.begin(); versionsIt != versions.end(); ++versionsIt ) {
552     sprintf(&(aProperty[a]),"%s=%s",
553             (char*)(versionsIt->first.c_str()),
554             (char*)(versionsIt->second.c_str()));
555     a = a + versionsIt->first.size() + versionsIt->second.size() + 1;
556     aProperty[a++] = 1;
557   }
558
559   aProperty[a] = 0;
560
561   name_len = (hdf_int32) a;
562   size[0] = name_len + 1 ;
563   hdf_dataset = new HDFdataset("AttributeStudyProperties",hdf_group,HDF_STRING,size,1);
564   hdf_dataset->CreateOnDisk();
565   hdf_dataset->WriteOnDisk(aProperty);
566   hdf_dataset->CloseOnDisk();
567   hdf_dataset=0; //will be deleted by hdf_sco_group destructor
568   delete [] aProperty;
569   
570   aProp->SetModified(0);
571   return true;
572 }
573
574 //=============================================================================
575 /*! Function : _SaveAs
576  *  Purpose  : save the study in HDF file
577  */
578 //============================================================================
579 bool SALOMEDSImpl_StudyManager::Impl_SaveAs(const std::string& aStudyUrl,
580                                             SALOMEDSImpl_Study* aStudy,
581                                             SALOMEDSImpl_DriverFactory* aFactory,
582                                             bool theMultiFile,
583                                             bool theASCII)
584 {
585   // Set "C" locale temporarily to avoid possible localization problems
586   Kernel_Utils::Localizer loc;
587
588   // HDF File will be composed of differents part :
589   // * For each ComponentDataType, all data created by the component
590   //   Informations in data group hdf_group_datacomponent
591   // * Study Structure -> Exactly what is contained in Document
592   //   Informations in data group hdf_group_study_structure
593
594   _errorCode = "";
595
596   HDFfile *hdf_file=0;
597   HDFgroup *hdf_group_study_structure =0;
598   HDFgroup *hdf_sco_group =0;
599   HDFgroup *hdf_sco_group2 =0;
600   HDFgroup *hdf_notebook_vars =0; 
601   HDFgroup *hdf_notebook_var  = 0;
602
603   HDFgroup *hdf_group_datacomponent =0;
604   HDFdataset *hdf_dataset =0;
605   hdf_size size[1];
606   hdf_int32 name_len = 0;
607   std::string component_name;
608
609   if(!aStudy) {
610     _errorCode = "Study is null";
611     return false;
612   }
613
614   // Store previous URL
615   std::string anOldName = aStudy->Name();
616
617   // Map to store components' versions
618   std::map<std::string, std::string> componentVersions;
619
620   //Create a temporary url to which the study is saved 
621   std::string aUrl = SALOMEDSImpl_Tool::GetTmpDir() + SALOMEDSImpl_Tool::GetNameFromPath(aStudyUrl);
622
623   // unlock study if it is locked, as some attributes need to be modified
624   StudyUnlocker unlock(aStudy);
625
626   SALOMEDSImpl_StudyBuilder* SB= aStudy->NewBuilder();
627   std::map<std::string, SALOMEDSImpl_Driver*> aMapTypeDriver;
628
629   try
630     {
631       // mpv 15.12.2003: for saving components we have to load all data from all modules
632       SALOMEDSImpl_SComponentIterator itcomponent = aStudy->NewComponentIterator();
633       for (; itcomponent.More(); itcomponent.Next())
634         {
635           SALOMEDSImpl_SComponent sco = itcomponent.Value();
636           // if there is an associated Engine call its method for saving
637           std::string IOREngine;
638           try {
639             SALOMEDSImpl_Driver* aDriver = NULL;
640             std::string aCompType = sco.GetComment();
641             if (!sco.ComponentIOR(IOREngine)) {
642               if (!aCompType.empty()) {
643
644                 aDriver = aFactory->GetDriverByType(aCompType);
645
646                 if (aDriver != NULL) {
647                   if(!SB->LoadWith(sco, aDriver)) {
648                     _errorCode = SB->GetErrorCode();
649                     return false;
650                   }
651                 }
652               }
653             }
654             else {
655               aDriver = aFactory->GetDriverByIOR(IOREngine);
656             }
657             aMapTypeDriver[aCompType] = aDriver;
658           } catch(...) {
659             _errorCode = "Can not restore information to resave it";
660             return false;
661           }
662         }
663
664       // VSR: set URL to new file name
665       // VSR: remember to set previous name if save operation fails
666       aStudy->URL(aStudyUrl);
667
668       // To change for Save
669       // Do not have to do a new file but just a Open??? Rewrite all informations after erasing evrything??
670       hdf_file = new HDFfile((char*)aUrl.c_str());
671       hdf_file->CreateOnDisk();
672
673       //-----------------------------------------------------------------------
674       // 1 - Create a groupe for each SComponent and Update the PersistanceRef
675       //-----------------------------------------------------------------------
676       hdf_group_datacomponent = new HDFgroup("DATACOMPONENT",hdf_file);
677       hdf_group_datacomponent->CreateOnDisk();
678
679       for (itcomponent.Init(); itcomponent.More(); itcomponent.Next())
680         {
681           SALOMEDSImpl_SComponent sco = itcomponent.Value();
682
683           std::string scoid = sco.GetID();
684           hdf_sco_group = new HDFgroup((char*)scoid.c_str(), hdf_group_datacomponent);
685           hdf_sco_group->CreateOnDisk();
686
687           std::string componentDataType = sco.ComponentDataType();
688           std::string IOREngine;
689           if (sco.ComponentIOR(IOREngine))
690             {
691               // Engine should be already in the map as it was to added before
692               SALOMEDSImpl_Driver* Engine = aMapTypeDriver[componentDataType];
693               if (Engine != NULL)
694                 {
695                   SALOMEDSImpl_TMPFile* aStream = NULL;
696                   long length = 0;
697
698                   componentVersions[ componentDataType ] = Engine->Version();
699
700                   if (theASCII) aStream = Engine->SaveASCII(sco,
701                                                             SALOMEDSImpl_Tool::GetDirFromPath(aUrl),
702                                                             length,
703                                                             theMultiFile);
704                   else aStream = Engine->Save(sco,
705                                               SALOMEDSImpl_Tool::GetDirFromPath(aUrl),
706                                               length,
707                                               theMultiFile);
708                   HDFdataset *hdf_dataset;
709                   hdf_size aHDFSize[1]; 
710                   if(length > 0) {  //The component saved some auxiliary files, then put them into HDF file
711
712                     aHDFSize[0] = length;
713
714                     HDFdataset *hdf_dataset = new HDFdataset("FILE_STREAM", hdf_sco_group, HDF_STRING, aHDFSize, 1);
715                     hdf_dataset->CreateOnDisk();
716                     hdf_dataset->WriteOnDisk(aStream->Data());  //Save the stream in the HDF file
717                     hdf_dataset->CloseOnDisk();
718                   }
719
720                   if(aStream) delete aStream;
721
722                   // store multifile state
723                   aHDFSize[0] = 2;
724                   hdf_dataset = new HDFdataset("MULTIFILE_STATE", hdf_sco_group, HDF_STRING, aHDFSize, 1);
725                   hdf_dataset->CreateOnDisk();
726                   hdf_dataset->WriteOnDisk((void*)(theMultiFile?"M":"S")); // save: multi or single
727                   hdf_dataset->CloseOnDisk();
728                   hdf_dataset=0; //will be deleted by hdf_sco_AuxFiles destructor
729                   // store ASCII state
730                   aHDFSize[0] = 2;
731                   hdf_dataset = new HDFdataset("ASCII_STATE", hdf_sco_group, HDF_STRING, aHDFSize, 1);
732                   hdf_dataset->CreateOnDisk();
733                   hdf_dataset->WriteOnDisk((void*)(theASCII?"A":"B")); // save: ASCII or BINARY
734                   hdf_dataset->CloseOnDisk();
735                   hdf_dataset=0; //will be deleted by hdf_sco_AuxFiles destructor
736                   // Creation of the persistance reference  attribute
737                   Translate_IOR_to_persistentID (sco, Engine, theMultiFile, theASCII);
738                 }
739             }
740           hdf_sco_group->CloseOnDisk();
741           hdf_sco_group=0; // will be deleted by hdf_group_datacomponent destructor
742         }
743       hdf_group_datacomponent->CloseOnDisk();
744       hdf_group_datacomponent =0;  // will be deleted by hdf_file destructor
745
746       //-----------------------------------------------------------------------
747       //3 - Write the Study Structure
748       //-----------------------------------------------------------------------
749       hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
750       hdf_group_study_structure->CreateOnDisk();
751       // save component attributes
752       for (itcomponent.Init(); itcomponent.More(); itcomponent.Next())
753         {
754           SALOMEDSImpl_SComponent SC = itcomponent.Value();
755           std::string scid = SC.GetID();
756           hdf_sco_group2 = new HDFgroup((char*)scid.c_str(), hdf_group_study_structure);
757           hdf_sco_group2->CreateOnDisk();
758           SaveAttributes(SC, hdf_sco_group2);
759           // ComponentDataType treatment
760           component_name = SC.ComponentDataType();
761           name_len = (hdf_int32)component_name.length();
762           size[0] = name_len +1 ;
763           hdf_dataset = new HDFdataset("COMPONENTDATATYPE",hdf_sco_group2,HDF_STRING,size,1);
764           hdf_dataset->CreateOnDisk();
765           hdf_dataset->WriteOnDisk((char*)component_name.c_str());
766           hdf_dataset->CloseOnDisk();
767           hdf_dataset=0; //will be deleted by hdf_sco_group destructor
768           Impl_SaveObject(SC, hdf_sco_group2);
769           hdf_sco_group2->CloseOnDisk();
770           hdf_sco_group2=0; // will be deleted by hdf_group_study_structure destructor
771         }
772       //-----------------------------------------------------------------------
773       //4 - Write the Study UseCases Structure
774       //-----------------------------------------------------------------------
775       SALOMEDSImpl_SObject aSO = aStudy->FindObjectID(USE_CASE_LABEL_ID);
776       if (aSO) {
777         HDFgroup *hdf_soo_group = new HDFgroup(USE_CASE_LABEL_ID,hdf_group_study_structure);
778         hdf_soo_group->CreateOnDisk();
779         SaveAttributes(aSO, hdf_soo_group);
780         Impl_SaveObject(aSO, hdf_soo_group);
781         hdf_soo_group->CloseOnDisk();
782         hdf_soo_group=0; // will be deleted by hdf_group_study_structure destructor
783       }
784       //-----------------------------------------------------------------------
785       //5 - Write the NoteBook Variables
786       //-----------------------------------------------------------------------
787
788       //5.1 Create group to store all note book variables
789       hdf_notebook_vars = new HDFgroup("NOTEBOOK_VARIABLES",hdf_file);
790       hdf_notebook_vars->CreateOnDisk();
791       
792       std::string varValue;
793       std::string varType;
794       std::string varIndex;
795
796       for(int i=0 ;i < aStudy->myNoteBookVars.size(); i++ ){
797         // For each variable create HDF group
798         hdf_notebook_var = new HDFgroup((char*)aStudy->myNoteBookVars[i]->Name().c_str(),hdf_notebook_vars);
799         hdf_notebook_var->CreateOnDisk();
800
801         // Save Variable type
802         varType = aStudy->myNoteBookVars[i]->SaveType();
803         name_len = (hdf_int32) varType.length();
804         size[0] = name_len +1 ;
805         hdf_dataset = new HDFdataset("VARIABLE_TYPE",hdf_notebook_var,HDF_STRING,size,1);
806         hdf_dataset->CreateOnDisk();
807         hdf_dataset->WriteOnDisk((char*)varType.c_str());
808         hdf_dataset->CloseOnDisk();
809         hdf_dataset=0; //will be deleted by hdf_sco_group destructor
810         
811         char buffer[256];
812         sprintf(buffer,"%d",i);
813         varIndex= std::string(buffer);
814         name_len = (hdf_int32) varIndex.length();
815         size[0] = name_len +1 ;
816         hdf_dataset = new HDFdataset("VARIABLE_INDEX",hdf_notebook_var,HDF_STRING,size,1);
817         hdf_dataset->CreateOnDisk();
818         hdf_dataset->WriteOnDisk((char*)varIndex.c_str());
819         hdf_dataset->CloseOnDisk();
820         hdf_dataset=0; //will be deleted by hdf_sco_group destructor
821         
822         
823         // Save Variable value
824         varValue = aStudy->myNoteBookVars[i]->Save();
825         name_len = (hdf_int32) varValue.length();
826         size[0] = name_len +1 ;
827         hdf_dataset = new HDFdataset("VARIABLE_VALUE",hdf_notebook_var,HDF_STRING,size,1);
828         hdf_dataset->CreateOnDisk();
829         hdf_dataset->WriteOnDisk((char*)varValue.c_str());
830         hdf_dataset->CloseOnDisk();
831         hdf_dataset=0; //will be deleted by hdf_sco_group destructor
832         hdf_notebook_var->CloseOnDisk();
833         hdf_notebook_var = 0; //will be deleted by hdf_sco_group destructor
834       }
835       hdf_notebook_vars->CloseOnDisk();
836       hdf_notebook_vars = 0; //will be deleted by hdf_sco_group destructor
837
838       // record component versions
839       std::map<std::string, std::string>::const_iterator itVersions;
840       for ( itVersions = componentVersions.begin(); itVersions != componentVersions.end(); ++itVersions )
841         aStudy->GetProperties()->SetComponentVersion( itVersions->first, itVersions->second );
842       
843       // lock study back if it was locked initially, to write correct value of Locked flag
844       unlock.suspend();
845
846       //-----------------------------------------------------------------------
847       //6 - Write the Study Properties
848       //-----------------------------------------------------------------------
849       std::string study_name = aStudy->Name();
850       name_len = (hdf_int32) study_name.size();
851       size[0] = name_len +1 ;
852       hdf_dataset = new HDFdataset("STUDY_NAME",hdf_group_study_structure,HDF_STRING,size,1);
853       hdf_dataset->CreateOnDisk();
854       hdf_dataset->WriteOnDisk((char*)study_name.c_str());
855       hdf_dataset->CloseOnDisk();
856       hdf_dataset=0; // will be deleted by hdf_group_study_structure destructor
857
858       Impl_SaveProperties(aStudy, hdf_group_study_structure);
859       hdf_group_study_structure->CloseOnDisk();
860       hdf_file->CloseOnDisk();
861
862       hdf_group_study_structure =0; // will be deleted by hdf_file destructor
863       delete hdf_file; // recursively deletes all hdf objects...
864     }
865   catch (HDFexception)
866     {
867       _errorCode = "HDFexception ! ";
868       aStudy->URL( anOldName ); // VSR: restore previous url if operation is failed
869       return false;
870     }
871   catch(std::exception& exc)
872     {
873       _errorCode = const_cast<char*>(exc.what());
874       aStudy->URL( anOldName ); // VSR: restore previous url if operation is failed
875       return false;
876     }
877   catch(...)
878     {
879       _errorCode = "Unknown exception ! ";
880       aStudy->URL( anOldName ); // VSR: restore previous url if operation is failed
881       return false;
882     }
883   if (theASCII) { // save file in ASCII format
884     HDFascii::ConvertFromHDFToASCII(aUrl.c_str(), true);
885   }
886   
887   //Now it's necessary to copy files from the temporary directory to the user defined directory.
888
889   //      The easiest way to get a list of file in the temporary directory
890
891   std::string aCmd, aTmpFileDir = SALOMEDSImpl_Tool::GetTmpDir();
892   std::string aTmpFile = aTmpFileDir +"files";
893   std::string aStudyTmpDir = SALOMEDSImpl_Tool::GetDirFromPath(aUrl);
894
895 #ifdef WIN32
896   aCmd = "dir /B \"" + aStudyTmpDir +"\" > " + aTmpFile;
897 #else
898   aCmd ="ls -1 \"" + aStudyTmpDir +"\" > " + aTmpFile;
899 #endif
900   system(aCmd.c_str());
901
902   //       Iterate and move files in the temporary directory
903   FILE* fp = fopen(aTmpFile.c_str(), "rb");
904   if(!fp) {
905     aStudy->URL( anOldName ); // VSR: restore previous url if operation is failed
906     return false;
907   }
908   char* buffer = new char[2047];
909   int errors = 0;
910   while(!feof(fp) && !errors) {
911     if((fgets(buffer, 2046, fp)) == NULL) break;
912     size_t aLen = strlen(buffer);
913     if(buffer[aLen-1] == '\n') buffer[aLen-1] = char(0);
914 #ifdef WIN32
915     aCmd = "move /Y \"" + aStudyTmpDir + std::string(buffer) + "\" \"" + SALOMEDSImpl_Tool::GetDirFromPath(aStudyUrl) +"\"";
916 #else 
917     aCmd = "mv -f \"" + aStudyTmpDir + std::string(buffer) + "\" \"" + SALOMEDSImpl_Tool::GetDirFromPath(aStudyUrl)+"\"";
918 #endif
919     errors = system(aCmd.c_str());
920   }
921
922   delete []buffer;
923   fclose(fp);
924
925   //       Perform cleanup
926 #ifdef WIN32
927   DeleteFileA(aTmpFile.c_str());
928 #else 
929   unlink(aTmpFile.c_str());
930 #endif
931
932 #ifdef WIN32
933   RemoveDirectoryA(aTmpFileDir.c_str());
934   RemoveDirectoryA(aStudyTmpDir.c_str());
935 #else
936   rmdir(aTmpFileDir.c_str());
937   rmdir(aStudyTmpDir.c_str());
938 #endif
939
940   if ( !errors ) {
941     // VSR: finally, if all is done without errors, mark study as Saved
942     aStudy->IsSaved(true);
943   }
944
945   return !errors;
946 }
947
948 //============================================================================
949 /*! Function : Impl_SaveObject
950  *  Purpose  :
951  */
952 //============================================================================
953 bool SALOMEDSImpl_StudyManager::Impl_SaveObject(const SALOMEDSImpl_SObject& SC,
954                                                 HDFgroup *hdf_group_datatype)
955 {
956   _errorCode = "";
957
958   // Write in group hdf_group_datatype all informations of SObject SC
959   // Iterative function to parse all SObjects under a SComponent
960
961   HDFgroup *hdf_group_sobject = 0;
962
963   DF_ChildIterator itchild(SC.GetLabel());
964   for (; itchild.More(); itchild.Next())
965     {
966
967       // mpv: don't save empty labels
968       std::vector<DF_Attribute*> attr = itchild.Value().GetAttributes();
969       if (attr.size() == 0) {  //No attributes on the label
970         DF_ChildIterator subchild(itchild.Value());
971         if (!subchild.More()) {
972           continue;
973         }
974         subchild.Init(itchild.Value(), true);
975         bool anEmpty = true;
976         for (; subchild.More() && anEmpty; subchild.Next()) {
977           std::vector<DF_Attribute*> attr2 = subchild.Value().GetAttributes();
978           if (attr2.size()) {
979             anEmpty = false;  //There are attributes on the child label
980             break;
981           }
982         }
983         if (anEmpty) continue;
984       }
985
986       SALOMEDSImpl_SObject SO = SALOMEDSImpl_Study::SObject(itchild.Value());
987
988       std::string scoid = SO.GetID();
989       hdf_group_sobject = new HDFgroup(scoid.c_str(), hdf_group_datatype);
990       hdf_group_sobject->CreateOnDisk();
991       SaveAttributes(SO, hdf_group_sobject);
992       Impl_SaveObject(SO, hdf_group_sobject);
993       hdf_group_sobject->CloseOnDisk();
994       hdf_group_sobject =0; // will be deleted by father hdf object destructor
995     }
996
997   return true;
998 }
999
1000 //============================================================================
1001 /*! Function : Impl_SubstituteSlash
1002  *  Purpose  :
1003  */
1004 //============================================================================
1005 std::string SALOMEDSImpl_StudyManager::Impl_SubstituteSlash(const std::string& aUrl)
1006 {
1007   _errorCode = "";
1008
1009   std::string theUrl(aUrl);
1010   for(int i = 0; i<theUrl.size(); i++)
1011     if(theUrl[i] == '/') theUrl[i] = ':';
1012   return theUrl;
1013 }
1014
1015 //============================================================================
1016 /*! Function : GetDocumentOfStudy
1017  *  Purpose  :
1018  */
1019 //============================================================================
1020 DF_Document* SALOMEDSImpl_StudyManager::GetDocumentOfStudy(SALOMEDSImpl_Study* theStudy)
1021 {
1022   _errorCode = "";
1023   return theStudy->_doc;
1024 }
1025
1026 //============================================================================
1027 /*! Function : CanCopy
1028  *  Purpose  :
1029  */
1030 //============================================================================
1031 bool SALOMEDSImpl_StudyManager::CanCopy(const SALOMEDSImpl_SObject& theObject,
1032                                         SALOMEDSImpl_Driver* theEngine)
1033 {
1034   _errorCode = "";
1035   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
1036   if (!aComponent) return false;
1037   if (aComponent.GetLabel() == theObject.GetLabel()) return false;
1038   std::string IOREngine;
1039   if (!aComponent.ComponentIOR(IOREngine)) return false;
1040   if (theEngine == NULL) return false;
1041   return theEngine->CanCopy(theObject);
1042 }
1043
1044 //============================================================================
1045 /*! Function : CopyLabel
1046  *  Purpose  :
1047  */
1048 //============================================================================
1049 bool SALOMEDSImpl_StudyManager::CopyLabel(SALOMEDSImpl_Study* theSourceStudy,
1050                                           SALOMEDSImpl_Driver* theEngine,
1051                                           const int theSourceStartDepth,
1052                                           const DF_Label& theSource,
1053                                           const DF_Label& theDestinationMain)
1054 {
1055   _errorCode = "";
1056
1057   int a;
1058   DF_Label aTargetLabel = theDestinationMain;
1059   DF_Label aAuxTargetLabel = theDestinationMain.Father().FindChild(2);
1060   for(a = theSource.Depth() - theSourceStartDepth; a > 0 ; a--) {
1061     DF_Label aSourceLabel = theSource;
1062     for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
1063     aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
1064     aAuxTargetLabel = aAuxTargetLabel.FindChild(aSourceLabel.Tag());
1065   }
1066   // iterate attributes
1067   std::vector<DF_Attribute*> attrList = theSource.GetAttributes();
1068   for(int i = 0, len = attrList.size(); i<len; i++) {
1069     DF_Attribute* anAttr = attrList[i];
1070     std::string type = SALOMEDSImpl_GenericAttribute::Impl_GetType(anAttr);
1071     if (type.substr(0, 17) == std::string("AttributeTreeNode")) continue; // never copy tree node attribute
1072     if (type == std::string("AttributeTarget")) continue; // and target attribute
1073
1074     if (type == std::string("AttributeReference")) { // reference copied as Comment in aux tree
1075       DF_Label aReferenced = dynamic_cast<SALOMEDSImpl_AttributeReference*>(anAttr)->Get();
1076       std::string anEntry = aReferenced.Entry();
1077       // store the value of name attribute of referenced label
1078       SALOMEDSImpl_AttributeName* aNameAttribute;
1079       if ((aNameAttribute=(SALOMEDSImpl_AttributeName*)aReferenced.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
1080         anEntry += " ";
1081         anEntry += aNameAttribute->Value();
1082       }
1083       SALOMEDSImpl_AttributeComment::Set(aAuxTargetLabel, anEntry);
1084       continue;
1085     }
1086
1087     if (type == std::string("AttributeIOR")) { // IOR => ID and TMPFile of Engine
1088       std::string anEntry = theSource.Entry();
1089       SALOMEDSImpl_SObject aSO = theSourceStudy->FindObjectID(anEntry);
1090       int anObjID;
1091       long aLen;
1092       SALOMEDSImpl_TMPFile* aStream = theEngine->CopyFrom(aSO, anObjID, aLen);
1093       std::string aResStr("");
1094       for(a = 0; a < aLen; a++) {
1095         aResStr += (char)(aStream->Get(a));
1096       }
1097
1098       if(aStream) delete aStream;
1099
1100       SALOMEDSImpl_AttributeInteger::Set(aAuxTargetLabel, anObjID);
1101       SALOMEDSImpl_AttributeName::Set(aAuxTargetLabel, aResStr);
1102       continue;
1103     }
1104     DF_Attribute* aNewAttribute = anAttr->NewEmpty();
1105     aTargetLabel.AddAttribute(aNewAttribute);
1106     anAttr->Paste(aNewAttribute);
1107   }
1108
1109   return true;
1110 }
1111
1112 //============================================================================
1113 /*! Function : Copy
1114  *  Purpose  :
1115  */
1116 //============================================================================
1117 bool SALOMEDSImpl_StudyManager::Copy(const SALOMEDSImpl_SObject& theObject,
1118                                      SALOMEDSImpl_Driver* theEngine)
1119 {
1120   _errorCode = "";
1121
1122   // adoptation for alliances datamodel copy: without IOR attributes !!!
1123   bool aStructureOnly; // copy only SObjects and attributes without component help
1124   aStructureOnly = !theObject.GetLabel().IsAttribute(SALOMEDSImpl_AttributeIOR::GetID());
1125
1126   // get component-engine
1127   SALOMEDSImpl_Study* aStudy = theObject.GetStudy();
1128
1129   // CAF document of current study usage
1130   DF_Document* aDocument = GetDocumentOfStudy(aStudy);
1131   if (!aDocument) {
1132     _errorCode = "Document is null";
1133     return false;
1134   }
1135
1136   //Clear the clipboard
1137   _clipboard->Main().Root().ForgetAllAttributes(true);
1138   _appli->Close(_clipboard);
1139   _clipboard = _appli->NewDocument("SALOME_STUDY");
1140
1141   // set component data type to the name attribute of root label
1142   if (!aStructureOnly) {
1143     SALOMEDSImpl_AttributeComment::Set(_clipboard->Main().Root(),
1144                                        theEngine->ComponentDataType());
1145   }
1146   // set to the Root label integer attribute: study id
1147   SALOMEDSImpl_AttributeInteger::Set(_clipboard->Main().Root(), aStudy->StudyId());
1148   // iterate all theObject's label children
1149   DF_Label aStartLabel = theObject.GetLabel();
1150   int aSourceStartDepth = aStartLabel.Depth();
1151
1152   // copy main source label
1153   CopyLabel(aStudy, theEngine, aSourceStartDepth, aStartLabel, _clipboard->Main());
1154
1155   // copy all subchildren of the main source label (all levels)
1156   DF_ChildIterator anIterator(aStartLabel, true);
1157   for(; anIterator.More(); anIterator.Next()) {
1158     CopyLabel(aStudy, theEngine, aSourceStartDepth, anIterator.Value(), _clipboard->Main());
1159   }
1160
1161   return true;
1162 }
1163 //============================================================================
1164 /*! Function : CanPaste
1165  *  Purpose  :
1166  */
1167 //============================================================================
1168 bool SALOMEDSImpl_StudyManager::CanPaste(const SALOMEDSImpl_SObject& theObject,
1169                                          SALOMEDSImpl_Driver* theEngine)
1170 {
1171   _errorCode = "";
1172
1173   if (!_clipboard) {
1174     _errorCode = "Clipboard is null";
1175     return false;
1176   }
1177
1178   SALOMEDSImpl_AttributeComment* aCompName = NULL;
1179   if (!(aCompName=(SALOMEDSImpl_AttributeComment*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID()))) {
1180     _errorCode = "Clipboard has no component type";
1181     return false;
1182   }
1183   SALOMEDSImpl_AttributeInteger* anObjID;
1184   if (!(anObjID=(SALOMEDSImpl_AttributeInteger*)_clipboard->Main().Father().FindChild(2).FindAttribute(SALOMEDSImpl_AttributeInteger::GetID()))) {
1185     _errorCode = "Clipboard has no object id";
1186     return false;
1187   }
1188   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
1189   if (!aComponent) {
1190     _errorCode = "Object doesn't belong to component";
1191     return false;
1192   }
1193
1194   std::string IOREngine;
1195   if (!aComponent.ComponentIOR(IOREngine)) {
1196     _errorCode = "component has no IOR";
1197     return false;
1198   }
1199   return theEngine->CanPaste(aCompName->Value(), anObjID->Value());
1200 }
1201
1202 //============================================================================
1203 /*! Function : PasteLabel
1204  *  Purpose  :
1205  */
1206 //============================================================================
1207 DF_Label SALOMEDSImpl_StudyManager::PasteLabel(SALOMEDSImpl_Study* theDestinationStudy,
1208                                                SALOMEDSImpl_Driver* theEngine,
1209                                                const DF_Label& theSource,
1210                                                const DF_Label& theDestinationStart,
1211                                                const int theCopiedStudyID,
1212                                                const bool isFirstElement)
1213 {
1214   _errorCode = "";
1215
1216   // get corresponding source, target and auxiliary labels
1217   DF_Label aTargetLabel = theDestinationStart;
1218
1219   DF_Label aAuxSourceLabel = theSource.Root().FindChild(2);
1220   int a;
1221   if (!isFirstElement) {
1222     for(a = theSource.Depth() - 1; a > 0 ; a--) {
1223       DF_Label aSourceLabel = theSource;
1224       for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
1225       aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
1226       aAuxSourceLabel = aAuxSourceLabel.FindChild(aSourceLabel.Tag());
1227     }
1228     SALOMEDSImpl_SObject so = theDestinationStudy->GetSObject(aTargetLabel);
1229     theDestinationStudy->addSO_Notification(so);
1230   }
1231
1232   // check auxiliary label for TMPFile => IOR
1233   SALOMEDSImpl_AttributeName* aNameAttribute = NULL;
1234   if ((aNameAttribute=(SALOMEDSImpl_AttributeName*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
1235     SALOMEDSImpl_AttributeInteger* anObjID = (SALOMEDSImpl_AttributeInteger*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeInteger::GetID());
1236     SALOMEDSImpl_AttributeComment* aComponentName = (SALOMEDSImpl_AttributeComment*)theSource.Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID());
1237     std::string aCompName = aComponentName->Value();
1238
1239     if (theEngine->CanPaste(aCompName, anObjID->Value())) {
1240       std::string aTMPStr = aNameAttribute->Value();
1241       int aLen = aTMPStr.size();
1242       unsigned char* aStream = NULL;
1243       if(aLen > 0) {
1244         aStream = new unsigned char[aLen+10];
1245         for(a = 0; a < aLen; a++) {
1246           aStream[a] = aTMPStr[a];
1247         }
1248       }
1249
1250       std::string anEntry = aTargetLabel.Entry();
1251       SALOMEDSImpl_SObject aPastedSO = theDestinationStudy->FindObjectID(anEntry);
1252
1253       if (isFirstElement) {
1254         std::string aDestEntry = theEngine->PasteInto(aStream,
1255                                                  aLen,
1256                                                  anObjID->Value(),
1257                                                  aPastedSO.GetFatherComponent());
1258         aTargetLabel = DF_Label::Label(theDestinationStart, aDestEntry);
1259       } else
1260         theEngine->PasteInto(aStream, aLen, anObjID->Value(), aPastedSO);
1261
1262       if(aStream != NULL) delete []aStream;
1263     }
1264   }
1265
1266   // iterate attributes
1267   std::vector<DF_Attribute*> attrList = theSource.GetAttributes();
1268   for(int i = 0, len = attrList.size(); i<len; i++) {
1269     DF_Attribute* anAttr = attrList[i];
1270     if (aTargetLabel.FindAttribute(anAttr->ID())) {
1271       aTargetLabel.ForgetAttribute(anAttr->ID());
1272     }
1273     DF_Attribute* aNewAttribute = anAttr->NewEmpty();
1274     aTargetLabel.AddAttribute(aNewAttribute);
1275     anAttr->Paste(aNewAttribute);
1276   }
1277
1278   // check auxiliary label for Comment => reference or name attribute of the referenced object
1279   SALOMEDSImpl_AttributeComment* aCommentAttribute = NULL;
1280   if ((aCommentAttribute=(SALOMEDSImpl_AttributeComment*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeComment::GetID()))) {
1281     char * anEntry = new char[aCommentAttribute->Value().size() + 1];
1282     strcpy(anEntry, std::string(aCommentAttribute->Value()).c_str());
1283     char* aNameStart = strchr(anEntry, ' ');
1284     if (aNameStart) {
1285       *aNameStart = '\0';
1286       aNameStart++;
1287     }
1288     if (theCopiedStudyID == theDestinationStudy->StudyId()) { // if copy to the same study, reanimate reference
1289       DF_Label aRefLabel = DF_Label::Label(aTargetLabel, anEntry);
1290       SALOMEDSImpl_AttributeReference::Set(aTargetLabel, aRefLabel);
1291       // target attributes structure support
1292       SALOMEDSImpl_AttributeTarget::Set(aRefLabel)->Add(SALOMEDSImpl_Study::SObject(aTargetLabel));
1293     } else {
1294       if (aNameStart) SALOMEDSImpl_AttributeName::Set(aTargetLabel, aNameStart);
1295       else SALOMEDSImpl_AttributeName::Set(aTargetLabel, std::string("Reference to:")+anEntry);
1296     }
1297     delete [] anEntry;
1298   }
1299
1300   return aTargetLabel;
1301 }
1302
1303 //============================================================================
1304 /*! Function : Paste
1305  *  Purpose  :
1306  */
1307 //============================================================================
1308 SALOMEDSImpl_SObject SALOMEDSImpl_StudyManager::Paste(const SALOMEDSImpl_SObject& theObject,
1309                                                SALOMEDSImpl_Driver* theEngine)
1310 {
1311   _errorCode = "";
1312
1313   SALOMEDSImpl_SObject so;
1314   SALOMEDSImpl_Study* aStudy = theObject.GetStudy();
1315
1316   // if study is locked, then paste can't be done
1317   if (aStudy->GetProperties()->IsLocked()) {
1318     _errorCode = "LockProtection";
1319     throw LockProtection("LockProtection");
1320   }
1321
1322   // if there is no component name, then paste only SObjects and attributes: without component help
1323   SALOMEDSImpl_AttributeComment* aComponentName = NULL;
1324   bool aStructureOnly = !(aComponentName=(SALOMEDSImpl_AttributeComment*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID()));
1325
1326   // get copied study ID
1327   SALOMEDSImpl_AttributeInteger* aStudyIDAttribute = NULL;
1328   if (!(aStudyIDAttribute=(SALOMEDSImpl_AttributeInteger*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeInteger::GetID()))) {
1329     _errorCode = "No study ID was found";
1330     return so;
1331   }
1332   int aCStudyID = aStudyIDAttribute->Value();
1333
1334   // CAF document of current study usage
1335   DF_Document* aDocument = GetDocumentOfStudy(aStudy);
1336   if (!aDocument) {
1337     _errorCode = "Document is null";
1338     return so;
1339   }
1340
1341   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
1342
1343   // fill root inserted SObject
1344   DF_Label aStartLabel;
1345   if (aStructureOnly) {
1346     DF_Label anObjectLabel = DF_Label::Label(aDocument->Main(), theObject.GetID());
1347     aStartLabel = PasteLabel(aStudy, theEngine, _clipboard->Main(), anObjectLabel, aCStudyID, false);
1348   } else {
1349     DF_Label aComponentLabel = DF_Label::Label(aDocument->Main(), aComponent.GetID());
1350     aStartLabel = PasteLabel(aStudy, theEngine, _clipboard->Main(), aComponentLabel, aCStudyID, true);
1351   }
1352
1353   // paste all sublebels
1354   DF_ChildIterator anIterator(_clipboard->Main(), true);
1355   for(; anIterator.More(); anIterator.Next()) {
1356     PasteLabel(aStudy, theEngine, anIterator.Value(), aStartLabel, aCStudyID, false);
1357   }
1358
1359   return SALOMEDSImpl_Study::SObject(aStartLabel);
1360 }
1361
1362 //#######################################################################################################
1363 //#                                     STATIC PRIVATE FUNCTIONS
1364 //#######################################################################################################
1365
1366 //============================================================================
1367 /*! Function : SaveAttributes
1368  *  Purpose  : Save attributes for object
1369  */
1370 //============================================================================
1371 static void SaveAttributes(const SALOMEDSImpl_SObject& aSO, HDFgroup *hdf_group_sobject)
1372 {
1373   hdf_size size[1];
1374   std::vector<DF_Attribute*> attrList = aSO.GetLabel().GetAttributes();
1375   DF_Attribute* anAttr = NULL;
1376   for(int i = 0, len = attrList.size(); i<len; i++) {
1377     anAttr = attrList[i];
1378     //The following attributes are not supposed to be written to the file
1379     std::string type = SALOMEDSImpl_GenericAttribute::Impl_GetType(anAttr);
1380     if(type == std::string("AttributeIOR")) continue; //IOR attribute is not saved
1381     std::string aSaveStr =anAttr->Save();
1382     //cout << "Saving: " << aSO.GetID() << " type: "<< type<<"|" << endl;
1383     size[0] = (hdf_int32) strlen(aSaveStr.c_str()) + 1;
1384     HDFdataset *hdf_dataset = new HDFdataset((char*)type.c_str(), hdf_group_sobject, HDF_STRING,size, 1);
1385     hdf_dataset->CreateOnDisk();
1386     hdf_dataset->WriteOnDisk((char*)aSaveStr.c_str());
1387     hdf_dataset->CloseOnDisk();
1388     hdf_dataset=0; //will be deleted by hdf_sco_group destructor
1389   }
1390 }
1391
1392 //===========================================================================
1393 //Function : ReadAttributes
1394 //===========================================================================
1395 static void ReadAttributes(SALOMEDSImpl_Study* theStudy,
1396                            const SALOMEDSImpl_SObject& aSO,
1397                            HDFdataset* hdf_dataset)
1398 {
1399   hdf_dataset->OpenOnDisk();
1400
1401   DF_Attribute* anAttr = NULL;
1402   char* current_string = new char[hdf_dataset->GetSize()+1];
1403   hdf_dataset->ReadFromDisk(current_string);
1404   //cout << "Reading attr type = " << hdf_dataset->GetName() << "  SO = " << aSO.GetID() << endl;
1405   if (!strcmp(hdf_dataset->GetName(),"COMPONENTDATATYPE")) {
1406     anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, "AttributeComment");
1407   } else if (!strcmp(hdf_dataset->GetName(),"AttributeReference") ||
1408              !strcmp(hdf_dataset->GetName(),"Reference")) { // Old format maintainance
1409     theStudy->NewBuilder()->Addreference(aSO, theStudy->CreateObjectID(current_string));
1410     delete [] (current_string);
1411     hdf_dataset->CloseOnDisk();
1412     return;
1413   } else {
1414     anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, hdf_dataset->GetName());
1415   }
1416   
1417   if (anAttr) {
1418     anAttr->Load(current_string);
1419   }
1420   
1421   delete [] (current_string);
1422   hdf_dataset->CloseOnDisk();
1423 }
1424
1425 //============================================================================
1426 //Function : BuildlTree
1427 //============================================================================
1428 static void BuildTree (SALOMEDSImpl_Study* theStudy, HDFgroup* hdf_current_group)
1429 {
1430   hdf_current_group->OpenOnDisk();
1431   SALOMEDSImpl_SObject aSO;
1432   char* Entry = hdf_current_group->GetName();
1433   if (strcmp(Entry,"STUDY_STRUCTURE") == 0) {
1434     aSO = theStudy->CreateObjectID("0:1");
1435   }
1436   else {
1437     aSO = theStudy->CreateObjectID(Entry);
1438   }
1439
1440   char name[HDF_NAME_MAX_LEN+1];
1441   int nbsons = hdf_current_group->nInternalObjects();
1442   for (int i=0; i<nbsons; i++) {
1443     hdf_current_group->InternalObjectIndentify(i,name);
1444     if (strncmp(name, "INTERNAL_COMPLEX",16) == 0) continue;
1445     hdf_object_type type = hdf_current_group->InternalObjectType(name);
1446
1447     if  (type == HDF_DATASET) {
1448       HDFdataset* new_dataset = new HDFdataset(name,hdf_current_group);
1449       ReadAttributes(theStudy,aSO,new_dataset);
1450       new_dataset = 0; // will be deleted by father destructor
1451
1452     }
1453     else if (type == HDF_GROUP)   {
1454       HDFgroup* new_group = new HDFgroup(name,hdf_current_group);
1455       BuildTree (theStudy, new_group);
1456       new_group = 0; // will be deleted by father destructor
1457     }
1458   }
1459   hdf_current_group->CloseOnDisk();
1460 }
1461
1462
1463 //============================================================================
1464 //Function : Translate_IOR_to_persistentID
1465 //============================================================================
1466 static void Translate_IOR_to_persistentID (const SALOMEDSImpl_SObject& so,
1467                                            SALOMEDSImpl_Driver*                engine,
1468                                            bool                                isMultiFile,
1469                                            bool                                isASCII)
1470 {
1471   DF_ChildIterator itchild(so.GetLabel());
1472   std::string ior_string,  persistent_string, curid;
1473
1474   for (; itchild.More(); itchild.Next()) {
1475     SALOMEDSImpl_SObject current = SALOMEDSImpl_Study::SObject(itchild.Value());
1476     SALOMEDSImpl_AttributeIOR* IOR = NULL;
1477     if ((IOR=(SALOMEDSImpl_AttributeIOR*)current.GetLabel().FindAttribute(SALOMEDSImpl_AttributeIOR::GetID()))) {
1478       ior_string = IOR->Value();
1479
1480       persistent_string = engine->IORToLocalPersistentID (current, ior_string, isMultiFile, isASCII);
1481       SALOMEDSImpl_AttributePersistentRef::Set(current.GetLabel(), persistent_string);
1482     }
1483     Translate_IOR_to_persistentID (current, engine, isMultiFile, isASCII);
1484   }
1485 }
1486
1487 void ReadNoteBookVariables(SALOMEDSImpl_Study* theStudy, HDFgroup* theGroup)
1488 {
1489   if(!theGroup)
1490     return;
1491
1492   HDFgroup* new_group =0;
1493   HDFdataset* new_dataset =0;
1494   
1495   char aVarName[HDF_NAME_MAX_LEN+1];
1496   char *currentVarType = 0;
1497   char *currentVarValue = 0;
1498   char *currentVarIndex = 0;
1499   int order = 0;
1500   //Open HDF group with notebook variables
1501   theGroup->OpenOnDisk();
1502
1503   //Get Nb of variables
1504   int aNbVars = theGroup->nInternalObjects();
1505
1506   std::map<int,SALOMEDSImpl_GenericVariable*> aVarsMap;
1507
1508   for( int iVar=0;iVar < aNbVars;iVar++ ) {
1509     theGroup->InternalObjectIndentify(iVar,aVarName);
1510     hdf_object_type type = theGroup->InternalObjectType(aVarName);
1511     if(type == HDF_GROUP) {
1512
1513       //Read Variable
1514       new_group = new HDFgroup(aVarName,theGroup);
1515       new_group->OpenOnDisk();
1516
1517       //Read Type
1518       new_dataset = new HDFdataset("VARIABLE_TYPE",new_group);
1519       new_dataset->OpenOnDisk();
1520       currentVarType = new char[new_dataset->GetSize()+1];
1521       new_dataset->ReadFromDisk(currentVarType);
1522       new_dataset->CloseOnDisk();
1523       new_dataset = 0; //will be deleted by hdf_sco_group destructor
1524
1525       //Read Order
1526       if(new_group->ExistInternalObject("VARIABLE_INDEX")) {
1527         new_dataset = new HDFdataset("VARIABLE_INDEX",new_group);
1528         new_dataset->OpenOnDisk();
1529         currentVarIndex = new char[new_dataset->GetSize()+1];
1530         new_dataset->ReadFromDisk(currentVarIndex);
1531         new_dataset->CloseOnDisk();
1532         new_dataset = 0; //will be deleted by hdf_sco_group destructor
1533         order = atoi(currentVarIndex);
1534         delete [] currentVarIndex;
1535       }
1536       else
1537         order = iVar;
1538       
1539       //Read Value
1540       new_dataset = new HDFdataset("VARIABLE_VALUE",new_group);
1541       new_dataset->OpenOnDisk();
1542       currentVarValue = new char[new_dataset->GetSize()+1];
1543       new_dataset->ReadFromDisk(currentVarValue);
1544       new_dataset->CloseOnDisk();
1545       new_dataset = 0; //will be deleted by hdf_sco_group destructor
1546
1547       new_group->CloseOnDisk();
1548       new_group = 0;  //will be deleted by hdf_sco_group destructor
1549       
1550       SALOMEDSImpl_GenericVariable::VariableTypes aVarType =
1551         SALOMEDSImpl_GenericVariable::String2VariableType(std::string(currentVarType));
1552       delete [] currentVarType;
1553
1554       //Create variable and add it in the study
1555       SALOMEDSImpl_GenericVariable* aVariable = 
1556         new SALOMEDSImpl_ScalarVariable(aVarType,std::string(aVarName));
1557       aVariable->Load(std::string(currentVarValue));
1558           aVarsMap.insert(std::make_pair<int,SALOMEDSImpl_GenericVariable*>(order,aVariable));
1559       delete [] currentVarValue;
1560         }
1561   }
1562   
1563   std::map<int,SALOMEDSImpl_GenericVariable*>::const_iterator it= aVarsMap.begin();
1564   for(;it!=aVarsMap.end();it++)
1565     theStudy->AddVariable((*it).second);
1566   
1567   theGroup->CloseOnDisk();
1568 }