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