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