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