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