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