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