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