]> SALOME platform Git repositories - modules/kernel.git/blob - src/SALOMEDSImpl/SALOMEDSImpl_StudyManager.cxx
Salome HOME
To support References, stored by Salome maintainance version (2.2.x).
[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/
19 //
20 //  File   : SALOMEDSImpl_StudyManager.cxx
21 //  Author : Sergey RUIN
22 //  Module : SALOME
23
24 #include "SALOMEDSImpl_StudyManager.hxx"
25
26 using namespace std;
27
28 #include <CDF_Session.hxx>
29 #include <CDF_DirectoryIterator.hxx>
30 #include <TDF_Label.hxx>
31 #include <TDF_Tool.hxx>
32 #include <TDF_Data.hxx>
33 #include <TDF_RelocationTable.hxx>
34 #include <TDF_ChildIterator.hxx>
35 #include <TDF_AttributeIterator.hxx>
36 #include <TColStd_HSequenceOfReal.hxx>
37 #include <TColStd_HSequenceOfInteger.hxx>
38 #include <TColStd_HArray1OfCharacter.hxx>
39 #include <TColStd_HSequenceOfAsciiString.hxx>
40 #include <TColStd_HSequenceOfExtendedString.hxx>
41 #include <TCollection_ExtendedString.hxx>
42 #include <OSD_Process.hxx>
43 #include <Quantity_Date.hxx>
44 #include "HDFexplorer.hxx"
45
46 #include "SALOMEDSImpl_Attributes.hxx"
47 #include "SALOMEDSImpl_Tool.hxx"
48 #include "SALOMEDSImpl_SComponent.hxx"
49 #include <map>
50
51 #include "HDFOI.hxx"
52 #include <iostream>
53 #include <stdlib.h>
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(aHDFUrl);
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                   unsigned char* 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);  //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                   if(aStream != NULL) delete [] aStream;
668                 }
669             }
670           hdf_sco_group->CloseOnDisk();
671           hdf_sco_group=0; // will be deleted by hdf_group_datacomponent destructor
672         }
673       hdf_group_datacomponent->CloseOnDisk();
674       hdf_group_datacomponent =0;  // will be deleted by hdf_file destructor
675
676       //-----------------------------------------------------------------------
677       //3 - Write the Study Structure
678       //-----------------------------------------------------------------------
679       hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
680       hdf_group_study_structure->CreateOnDisk();
681       // save component attributes
682       SALOMEDSImpl_SComponentIterator itcomp = aStudy->NewComponentIterator();
683       for (; itcomp.More(); itcomp.Next())
684         {
685           Handle(SALOMEDSImpl_SComponent) SC = itcomp.Value();
686           TCollection_AsciiString scid = SC->GetID();
687           hdf_sco_group2 = new HDFgroup(scid.ToCString(), hdf_group_study_structure);
688           hdf_sco_group2->CreateOnDisk();
689           SaveAttributes(SC, hdf_sco_group2);
690           // ComponentDataType treatment
691           component_name = SC->ComponentDataType().ToCString();
692           name_len = (hdf_int32)strlen(component_name);
693           size[0] = name_len +1 ;
694           hdf_dataset = new HDFdataset("COMPONENTDATATYPE",hdf_sco_group2,HDF_STRING,size,1);
695           hdf_dataset->CreateOnDisk();
696           hdf_dataset->WriteOnDisk(component_name);
697           hdf_dataset->CloseOnDisk();
698           hdf_dataset=0; //will be deleted by hdf_sco_group destructor
699           Impl_SaveObject(SC, hdf_sco_group2);
700           hdf_sco_group2->CloseOnDisk();
701           hdf_sco_group2=0; // will be deleted by hdf_group_study_structure destructor
702         }
703
704       //-----------------------------------------------------------------------
705       //4 - Write the Study UseCases Structure
706       //-----------------------------------------------------------------------
707       Handle(SALOMEDSImpl_SObject) aSO = aStudy->FindObjectID(USE_CASE_LABEL_ID);
708       if (!aSO.IsNull()) {
709         HDFgroup *hdf_soo_group = new HDFgroup(USE_CASE_LABEL_ID,hdf_group_study_structure);
710         hdf_soo_group->CreateOnDisk();
711         SaveAttributes(aSO, hdf_soo_group);
712         Impl_SaveObject(aSO, hdf_soo_group);
713         hdf_soo_group->CloseOnDisk();
714         hdf_soo_group=0; // will be deleted by hdf_group_study_structure destructor
715       }
716
717       if (aLocked) aStudy->GetProperties()->SetLocked(true);
718       //-----------------------------------------------------------------------
719       //5 - Write the Study Properties
720       //-----------------------------------------------------------------------
721       name_len = (hdf_int32) aStudy->Name().Length();
722       size[0] = name_len +1 ;
723       hdf_dataset = new HDFdataset("STUDY_NAME",hdf_group_study_structure,HDF_STRING,size,1);
724       hdf_dataset->CreateOnDisk();
725       char* studid = aStudy->Name().ToCString();
726       hdf_dataset->WriteOnDisk(studid);
727       hdf_dataset->CloseOnDisk();
728       hdf_dataset=0; // will be deleted by hdf_group_study_structure destructor
729
730       Impl_SaveProperties(aStudy, hdf_group_study_structure);
731
732       hdf_group_study_structure->CloseOnDisk();
733       hdf_file->CloseOnDisk();
734
735       aStudy->IsSaved(true);
736       hdf_group_study_structure =0; // will be deleted by hdf_file destructor
737       delete hdf_file; // recursively deletes all hdf objects...
738     }
739   catch (HDFexception)
740     {
741       _errorCode = "HDFexception ! ";
742       return false;
743     }
744   if (theASCII) { // save file in ASCII format
745     HDFascii::ConvertFromHDFToASCII(aUrl.ToCString(), true);
746   }
747
748   return true;
749 }
750
751 //============================================================================
752 /*! Function : Impl_SaveObject
753  *  Purpose  :
754  */
755 //============================================================================
756 bool SALOMEDSImpl_StudyManager::Impl_SaveObject(const Handle(SALOMEDSImpl_SObject)& SC,
757                                                 HDFgroup *hdf_group_datatype)
758 {
759   _errorCode = "";
760
761   // Write in group hdf_group_datatype all informations of SObject SC
762   // Iterative function to parse all SObjects under a SComponent
763
764   HDFgroup *hdf_group_sobject = 0;
765
766   TDF_ChildIterator itchild(SC->GetLabel());
767   for (; itchild.More(); itchild.Next())
768     {
769
770       // mpv: don't save empty labels
771       TDF_AttributeIterator AI1(itchild.Value());
772       if (!AI1.More()) {  //No attributes on the label
773         TDF_ChildIterator subchild(SC->GetLabel());
774         if (!subchild.More()) {
775           continue;
776         }
777         subchild.Initialize(SC->GetLabel(), true);
778         bool anEmpty = true;
779         for (; subchild.More() && anEmpty; subchild.Next()) {
780           TDF_AttributeIterator AI2(subchild.Value());
781           if (AI2.More()) anEmpty = false;  //There are attributes on the child label
782         }
783         if (anEmpty) continue;
784       }
785
786       Handle(SALOMEDSImpl_SObject) SO = SALOMEDSImpl_Study::SObject(itchild.Value());
787
788       char* scoid = (char*) SO->GetID().ToCString();
789       hdf_group_sobject = new HDFgroup(scoid, hdf_group_datatype);
790       hdf_group_sobject->CreateOnDisk();
791       SaveAttributes(SO, hdf_group_sobject);
792       Impl_SaveObject(SO, hdf_group_sobject);
793       hdf_group_sobject->CloseOnDisk();
794       hdf_group_sobject =0; // will be deleted by father hdf object destructor
795     }
796
797   return true;
798 }
799
800 //============================================================================
801 /*! Function : Impl_SubstituteSlash
802  *  Purpose  :
803  */
804 //============================================================================
805 TCollection_AsciiString SALOMEDSImpl_StudyManager::Impl_SubstituteSlash(const TCollection_AsciiString& aUrl)
806 {
807   _errorCode = "";
808
809   TCollection_ExtendedString theUrl(aUrl);
810   Standard_ExtCharacter val1 = ToExtCharacter('/');
811   Standard_ExtCharacter val2 = ToExtCharacter(':');
812   theUrl.ChangeAll(val1,val2);
813   return theUrl;
814 }
815
816 //============================================================================
817 /*! Function : GetDocumentOfStudy
818  *  Purpose  :
819  */
820 //============================================================================
821 Handle(TDocStd_Document) SALOMEDSImpl_StudyManager::GetDocumentOfStudy(const Handle(SALOMEDSImpl_Study)& theStudy)
822 {
823   _errorCode = "";
824   return theStudy->_doc;
825 }
826
827 //============================================================================
828 /*! Function : CanCopy
829  *  Purpose  :
830  */
831 //============================================================================
832 bool SALOMEDSImpl_StudyManager::CanCopy(const Handle(SALOMEDSImpl_SObject)& theObject,
833                                         SALOMEDSImpl_Driver* theEngine)
834 {
835   _errorCode = "";
836   Handle(SALOMEDSImpl_SComponent) aComponent = theObject->GetFatherComponent();
837   if (aComponent.IsNull()) return false;
838   if (aComponent->GetLabel() == theObject->GetLabel()) return false;
839   TCollection_AsciiString IOREngine;
840   if (!aComponent->ComponentIOR(IOREngine)) return false;
841   if (theEngine == NULL) return false;
842   return theEngine->CanCopy(theObject);
843 }
844
845 //============================================================================
846 /*! Function : CopyLabel
847  *  Purpose  :
848  */
849 //============================================================================
850 bool SALOMEDSImpl_StudyManager::CopyLabel(const Handle(SALOMEDSImpl_Study)& theSourceStudy,
851                                           SALOMEDSImpl_Driver* theEngine,
852                                           const Standard_Integer theSourceStartDepth,
853                                           const TDF_Label& theSource,
854                                           const TDF_Label& theDestinationMain)
855 {
856   _errorCode = "";
857
858   int a;
859   TDF_Label aTargetLabel = theDestinationMain;
860   TDF_Label aAuxTargetLabel = theDestinationMain.Father().FindChild(2);
861   for(a = theSource.Depth() - theSourceStartDepth; a > 0 ; a--) {
862     TDF_Label aSourceLabel = theSource;
863     for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
864     aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
865     aAuxTargetLabel = aAuxTargetLabel.FindChild(aSourceLabel.Tag());
866   }
867   // iterate attributes
868   TDF_AttributeIterator anAttrIterator(theSource);
869   Handle(TDF_RelocationTable) aRT = new TDF_RelocationTable();
870   for(; anAttrIterator.More(); anAttrIterator.Next()) {
871     Handle(TDF_Attribute) anAttr = anAttrIterator.Value();
872     if (!Handle(SALOMEDSImpl_AttributeTreeNode)::DownCast(anAttr).IsNull()) continue; // never copy tree node attribute
873     if (!Handle(SALOMEDSImpl_AttributeTarget)::DownCast(anAttr).IsNull()) continue; // and target attribute
874
875     if (!Handle(SALOMEDSImpl_AttributeReference)::DownCast(anAttr).IsNull()) { // reference copied as Comment in aux tree
876       TDF_Label aReferenced = Handle(SALOMEDSImpl_AttributeReference)::DownCast(anAttr)->Get();
877       TCollection_AsciiString anEntry;
878       TDF_Tool::Entry(aReferenced, anEntry);
879       // store the value of name attribute of referenced label
880       Handle(SALOMEDSImpl_AttributeName) aNameAttribute;
881       if (aReferenced.FindAttribute(SALOMEDSImpl_AttributeName::GetID(), aNameAttribute)) {
882         anEntry += " ";
883         anEntry += aNameAttribute->Value();
884       }
885       SALOMEDSImpl_AttributeComment::Set(aAuxTargetLabel, TCollection_ExtendedString(anEntry));
886       continue;
887     }
888
889     if (!Handle(SALOMEDSImpl_AttributeIOR)::DownCast(anAttr).IsNull()) { // IOR => ID and TMPFile of Engine
890       TCollection_AsciiString anEntry;
891       TDF_Tool::Entry(theSource, anEntry);
892       Handle(SALOMEDSImpl_SObject) aSO = theSourceStudy->FindObjectID(anEntry.ToCString());
893       int anObjID;
894       long aLen;
895       unsigned char* aStream = theEngine->CopyFrom(aSO, anObjID, aLen);
896       TCollection_ExtendedString aResStr("");
897       for(a = 0; a < aLen; a++) {
898         aResStr += TCollection_ExtendedString(ToExtCharacter((Standard_Character)aStream[a]));
899       }
900       if(aStream != NULL) delete [] aStream;
901       SALOMEDSImpl_AttributeInteger::Set(aAuxTargetLabel, anObjID);
902       SALOMEDSImpl_AttributeName::Set(aAuxTargetLabel, aResStr);
903       continue;
904     }
905     Handle(TDF_Attribute) aNewAttribute = anAttr->NewEmpty();
906     aTargetLabel.AddAttribute(aNewAttribute);
907     anAttr->Paste(aNewAttribute, aRT);
908   }
909
910   return true;
911 }
912
913 //============================================================================
914 /*! Function : Copy
915  *  Purpose  :
916  */
917 //============================================================================
918 bool SALOMEDSImpl_StudyManager::Copy(const Handle(SALOMEDSImpl_SObject)& theObject,
919                                      SALOMEDSImpl_Driver* theEngine)
920 {
921   _errorCode = "";
922
923   // adoptation for alliances datamodel copy: without IOR attributes !!!
924   bool aStructureOnly; // copy only SObjects and attributes without component help
925   aStructureOnly = !theObject->GetLabel().IsAttribute(SALOMEDSImpl_AttributeIOR::GetID());
926
927   // get component-engine
928   Handle(SALOMEDSImpl_Study) aStudy = theObject->GetStudy();
929
930   // CAF document of current study usage
931   Handle(TDocStd_Document) aDocument = GetDocumentOfStudy(aStudy);
932   if (aDocument.IsNull()) {
933     _errorCode = "OCAF document is null";
934     return false;
935   }
936
937   //Clear the clipboard
938   _clipboard->Main().Root().ForgetAllAttributes(Standard_True);
939   _OCAFApp->Close(_clipboard);
940   Handle(TDocStd_Document) aDoc;
941   _OCAFApp->NewDocument("SALOME_STUDY", aDoc);
942   _clipboard = aDoc;
943
944   // set component data type to the name attribute of root label
945   if (!aStructureOnly) {
946     SALOMEDSImpl_AttributeComment::Set(_clipboard->Main().Root(),
947                                        TCollection_ExtendedString(theEngine->ComponentDataType()));
948   }
949   // set to the Root label integer attribute: study id
950   SALOMEDSImpl_AttributeInteger::Set(_clipboard->Main().Root(), aStudy->StudyId());
951   // iterate all theObject's label children
952   TDF_Label aStartLabel = theObject->GetLabel();
953   Standard_Integer aSourceStartDepth = aStartLabel.Depth();
954
955   // copy main source label
956   CopyLabel(aStudy, theEngine, aSourceStartDepth, aStartLabel, _clipboard->Main());
957
958   // copy all subchildren of the main source label (all levels)
959   TDF_ChildIterator anIterator(aStartLabel, Standard_True);
960   for(; anIterator.More(); anIterator.Next()) {
961     CopyLabel(aStudy, theEngine, aSourceStartDepth, anIterator.Value(), _clipboard->Main());
962   }
963
964   return true;
965 }
966 //============================================================================
967 /*! Function : CanPaste
968  *  Purpose  :
969  */
970 //============================================================================
971 bool SALOMEDSImpl_StudyManager::CanPaste(const Handle(SALOMEDSImpl_SObject)& theObject,
972                                          SALOMEDSImpl_Driver* theEngine)
973 {
974   _errorCode = "";
975
976   if (_clipboard.IsNull()) {
977     _errorCode = "Clipboard is null";
978     return false;
979   }
980
981   Handle(SALOMEDSImpl_AttributeComment) aCompName;
982   if (!_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID(), aCompName)) {
983     _errorCode = "Clipboard has no component type";
984     return false;
985   }
986   Handle(SALOMEDSImpl_AttributeInteger) anObjID;
987   if (!_clipboard->Main().Father().FindChild(2).FindAttribute(SALOMEDSImpl_AttributeInteger::GetID(), anObjID)) {
988     _errorCode = "Clipboard has no object id";
989     return false;
990   }
991   Handle(SALOMEDSImpl_SComponent) aComponent = theObject->GetFatherComponent();
992   if (aComponent.IsNull()) {
993     _errorCode = "Object doesn't belong to component";
994     return false;
995   }
996
997   TCollection_AsciiString IOREngine;
998   if (!aComponent->ComponentIOR(IOREngine)) {
999     _errorCode = "component has no IOR";
1000     return false;
1001   }
1002   return theEngine->CanPaste(aCompName->Value(), anObjID->Value());
1003 }
1004
1005 //============================================================================
1006 /*! Function : PasteLabel
1007  *  Purpose  :
1008  */
1009 //============================================================================
1010 TDF_Label SALOMEDSImpl_StudyManager::PasteLabel(const Handle(SALOMEDSImpl_Study)& theDestinationStudy,
1011                                                 SALOMEDSImpl_Driver* theEngine,
1012                                                 const TDF_Label& theSource,
1013                                                 const TDF_Label& theDestinationStart,
1014                                                 const int theCopiedStudyID,
1015                                                 const bool isFirstElement)
1016 {
1017   _errorCode = "";
1018
1019   // get corresponding source, target and auxiliary labels
1020   TDF_Label aTargetLabel = theDestinationStart;
1021
1022   TDF_Label aAuxSourceLabel = theSource.Root().FindChild(2);
1023   int a;
1024   if (!isFirstElement) {
1025     for(a = theSource.Depth() - 1; a > 0 ; a--) {
1026       TDF_Label aSourceLabel = theSource;
1027       for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
1028       aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
1029       aAuxSourceLabel = aAuxSourceLabel.FindChild(aSourceLabel.Tag());
1030     }
1031   }
1032
1033   // check auxiliary label for TMPFile => IOR
1034   Handle(SALOMEDSImpl_AttributeName) aNameAttribute;
1035   if (aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeName::GetID(), aNameAttribute)) {
1036     Handle(SALOMEDSImpl_AttributeInteger) anObjID;
1037
1038     aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeInteger::GetID(), anObjID);
1039     Handle(SALOMEDSImpl_AttributeComment) aComponentName;
1040     theSource.Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID(), aComponentName);
1041     TCollection_AsciiString aCompName = aComponentName->Value();
1042
1043     if (theEngine->CanPaste(aCompName, anObjID->Value())) {
1044       TCollection_ExtendedString aTMPStr = aNameAttribute->Value();
1045       int aLen = aTMPStr.Length();
1046       unsigned char* aStream = NULL;
1047       if(aLen > 0) {
1048         aStream = new unsigned char[aLen+10];
1049         for(a = 0; a < aLen; a++) {
1050           aStream[a] = ToCharacter(aTMPStr.Value(a+1));
1051         }
1052       }
1053
1054       TCollection_AsciiString anEntry;
1055       TDF_Tool::Entry(aTargetLabel, anEntry);
1056       Handle(SALOMEDSImpl_SObject) aPastedSO = theDestinationStudy->FindObjectID(anEntry);
1057
1058       if (isFirstElement) {
1059         TCollection_AsciiString aDestEntry = theEngine->PasteInto(aStream,
1060                                                                   aLen,
1061                                                                   anObjID->Value(),
1062                                                                   aPastedSO->GetFatherComponent());
1063         TDF_Tool::Label(theDestinationStart.Data(), aDestEntry, aTargetLabel);
1064       } else
1065         theEngine->PasteInto(aStream, aLen, anObjID->Value(), aPastedSO);
1066
1067       if(aStream != NULL) delete []aStream;
1068     }
1069   }
1070
1071   // iterate attributes
1072   TDF_AttributeIterator anAttrIterator(theSource);
1073   Handle(TDF_RelocationTable) aRT = new TDF_RelocationTable();
1074   for(; anAttrIterator.More(); anAttrIterator.Next()) {
1075     Handle(TDF_Attribute) anAttr = anAttrIterator.Value();
1076     if (aTargetLabel.FindAttribute(anAttr->ID(), anAttr)) {
1077       aTargetLabel.ForgetAttribute(anAttr->ID());
1078       anAttr = anAttrIterator.Value();
1079     }
1080     Handle(TDF_Attribute) aNewAttribute = anAttr->NewEmpty();
1081     aTargetLabel.AddAttribute(aNewAttribute);
1082     anAttr->Paste(aNewAttribute, aRT);
1083   }
1084
1085   // check auxiliary label for Comment => reference or name attribute of the referenced object
1086   Handle(SALOMEDSImpl_AttributeComment) aCommentAttribute;
1087   if (aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeComment::GetID(), aCommentAttribute)) {
1088     char * anEntry = new char[aCommentAttribute->Value().Length() + 1];
1089     strcpy(anEntry, TCollection_AsciiString(aCommentAttribute->Value()).ToCString());
1090     char* aNameStart = strchr(anEntry, ' ');
1091     if (aNameStart) {
1092       *aNameStart = '\0';
1093       aNameStart++;
1094     }
1095     if (theCopiedStudyID == theDestinationStudy->StudyId()) { // if copy to the same study, reanimate reference
1096       TDF_Label aRefLabel;
1097       TDF_Tool::Label(aTargetLabel.Data(), anEntry, aRefLabel);
1098       SALOMEDSImpl_AttributeReference::Set(aTargetLabel, aRefLabel);
1099       // target attributes structure support
1100       SALOMEDSImpl_AttributeTarget::Set(aRefLabel)->Add(SALOMEDSImpl_Study::SObject(aTargetLabel));
1101     } else {
1102       if (aNameStart) SALOMEDSImpl_AttributeName::Set(aTargetLabel, aNameStart);
1103       else SALOMEDSImpl_AttributeName::Set(aTargetLabel, TCollection_ExtendedString("Reference to:")+anEntry);
1104     }
1105     delete [] anEntry;
1106   }
1107
1108   return aTargetLabel;
1109 }
1110
1111 //============================================================================
1112 /*! Function : Paste
1113  *  Purpose  :
1114  */
1115 //============================================================================
1116 Handle(SALOMEDSImpl_SObject) SALOMEDSImpl_StudyManager::Paste(const Handle(SALOMEDSImpl_SObject)& theObject,
1117                                                               SALOMEDSImpl_Driver* theEngine)
1118 {
1119   _errorCode = "";
1120
1121   Handle(SALOMEDSImpl_Study) aStudy = theObject->GetStudy();
1122
1123   // if study is locked, then paste can't be done
1124   if (aStudy->GetProperties()->IsLocked()) {
1125     _errorCode = "LockProtection";
1126     throw LockProtection("LockProtection");
1127   }
1128
1129   // if there is no component name, then paste only SObjects and attributes: without component help
1130   Handle(SALOMEDSImpl_AttributeComment) aComponentName;
1131   bool aStructureOnly = !_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID(), aComponentName);
1132
1133   // get copied study ID
1134   Handle(SALOMEDSImpl_AttributeInteger) aStudyIDAttribute;
1135   if (!_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeInteger::GetID(), aStudyIDAttribute)) {
1136     _errorCode = "No study ID was found";
1137     return NULL;
1138   }
1139   int aCStudyID = aStudyIDAttribute->Value();
1140
1141   // CAF document of current study usage
1142   Handle(TDocStd_Document) aDocument = GetDocumentOfStudy(aStudy);
1143   if (aDocument.IsNull()) {
1144     _errorCode = "OCAF document is null";
1145     return NULL;
1146   }
1147
1148   Handle(SALOMEDSImpl_SComponent) aComponent = theObject->GetFatherComponent();
1149
1150   // fill root inserted SObject
1151   TDF_Label aStartLabel;
1152   if (aStructureOnly) {
1153     TDF_Label anObjectLabel;
1154     TDF_Tool::Label(aDocument->GetData(), theObject->GetID(), anObjectLabel);
1155     aStartLabel = PasteLabel(aStudy, theEngine, _clipboard->Main(), anObjectLabel, aCStudyID, false);
1156   } else {
1157     TDF_Label aComponentLabel;
1158     TDF_Tool::Label(aDocument->GetData(), aComponent->GetID(), aComponentLabel);
1159     aStartLabel = PasteLabel(aStudy, theEngine, _clipboard->Main(), aComponentLabel, aCStudyID, true);
1160   }
1161
1162   // paste all sublebels
1163   TDF_ChildIterator anIterator(_clipboard->Main(), Standard_True);
1164   for(; anIterator.More(); anIterator.Next()) {
1165     PasteLabel(aStudy, theEngine, anIterator.Value(), aStartLabel, aCStudyID, false);
1166   }
1167
1168   return SALOMEDSImpl_Study::SObject(aStartLabel);
1169 }
1170
1171 //#######################################################################################################
1172 //#                                     STATIC PRIVATE FUNCTIONS
1173 //#######################################################################################################
1174
1175 //============================================================================
1176 /*! Function : SaveAttributes
1177  *  Purpose  : Save attributes for object
1178  */
1179 //============================================================================
1180 static void SaveAttributes(Handle(SALOMEDSImpl_SObject) aSO, HDFgroup *hdf_group_sobject)
1181 {
1182   hdf_size size[1];
1183   TDF_AttributeIterator Itr(aSO->GetLabel());
1184   Handle(TDF_Attribute) anAttr;
1185   for(; Itr.More(); Itr.Next()) {
1186     anAttr = Itr.Value();
1187     //The following attributes are not supposed to be written to the file
1188     if(anAttr->DynamicType() == STANDARD_TYPE(SALOMEDSImpl_AttributeIOR)) continue; //IOR attribute is not saved
1189     Handle(SALOMEDSImpl_GenericAttribute) ga = Handle(SALOMEDSImpl_GenericAttribute)::DownCast(anAttr);
1190     TCollection_AsciiString aSaveStr = ga->Save();
1191     //cout << "Saving: " << aSO->GetID() << " "<< ga->Type() << " value: " << aSaveStr << endl;
1192     size[0] = (hdf_int32) strlen(aSaveStr.ToCString()) + 1;
1193     HDFdataset *hdf_dataset = new HDFdataset((char*)ga->Type().ToCString(), hdf_group_sobject,HDF_STRING,size,1);
1194     hdf_dataset->CreateOnDisk();
1195     hdf_dataset->WriteOnDisk((char*)aSaveStr.ToCString());
1196     hdf_dataset->CloseOnDisk();
1197     hdf_dataset=0; //will be deleted by hdf_sco_group destructor
1198   }
1199 }
1200
1201 //===========================================================================
1202 //Function : ReadAttributes
1203 //===========================================================================
1204 static void ReadAttributes(const Handle(SALOMEDSImpl_Study)& theStudy,
1205                            const Handle(SALOMEDSImpl_SObject)& aSO,
1206                            HDFdataset* hdf_dataset)
1207 {
1208   hdf_dataset->OpenOnDisk();
1209
1210   Handle(TDF_Attribute) anAttr;
1211
1212   char* current_string = new char[hdf_dataset->GetSize()];
1213   hdf_dataset->ReadFromDisk(current_string);
1214
1215   if (!strcmp(hdf_dataset->GetName(),"COMPONENTDATATYPE")) {
1216     anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, "AttributeComment");
1217   } else if (!strcmp(hdf_dataset->GetName(),"AttributeReference") ||
1218              !strcmp(hdf_dataset->GetName(),"Reference")) { // Old format maintainance
1219     theStudy->NewBuilder()->Addreference(aSO, theStudy->CreateObjectID(current_string));
1220     delete(current_string);
1221     hdf_dataset->CloseOnDisk();
1222     return;
1223   } else {
1224     anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, hdf_dataset->GetName());
1225   }
1226
1227   if (!anAttr.IsNull()) {
1228
1229     Handle(SALOMEDSImpl_GenericAttribute) ga = Handle(SALOMEDSImpl_GenericAttribute)::DownCast(anAttr);
1230     ga->Load(current_string);
1231     //cout << "Reading: " << aSO->GetID() << " "<< ga->Type() << " value: " << current_string << endl;
1232   }
1233
1234   delete(current_string);
1235   hdf_dataset->CloseOnDisk();
1236 }
1237
1238 //============================================================================
1239 //Function : BuildlTree
1240 //============================================================================
1241 static void BuildTree (const Handle(SALOMEDSImpl_Study)& theStudy, HDFgroup* hdf_current_group)
1242 {
1243   hdf_current_group->OpenOnDisk();
1244   Handle(SALOMEDSImpl_SObject) aSO;
1245   char* Entry = hdf_current_group->GetName();
1246   if (strcmp(Entry,"STUDY_STRUCTURE") == 0) {
1247     aSO = theStudy->CreateObjectID("0:1");
1248   }
1249   else {
1250     aSO = theStudy->CreateObjectID(Entry);
1251   }
1252
1253   char name[HDF_NAME_MAX_LEN+1];
1254   Standard_Integer nbsons = hdf_current_group->nInternalObjects();
1255   for (Standard_Integer i=0; i<nbsons; i++) {
1256     hdf_current_group->InternalObjectIndentify(i,name);
1257     if (strncmp(name, "INTERNAL_COMPLEX",16) == 0) continue;
1258     hdf_object_type type = hdf_current_group->InternalObjectType(name);
1259
1260     if  (type == HDF_DATASET) {
1261       HDFdataset* new_dataset = new HDFdataset(name,hdf_current_group);
1262       ReadAttributes(theStudy,aSO,new_dataset);
1263       new_dataset = 0; // will be deleted by father destructor
1264
1265     }
1266     else if (type == HDF_GROUP)   {
1267       HDFgroup* new_group = new HDFgroup(name,hdf_current_group);
1268       BuildTree (theStudy, new_group);
1269       new_group = 0; // will be deleted by father destructor
1270     }
1271   }
1272   hdf_current_group->CloseOnDisk();
1273 }
1274
1275
1276 //============================================================================
1277 //Function : Translate_IOR_to_persistentID
1278 //============================================================================
1279 static void Translate_IOR_to_persistentID (const Handle(SALOMEDSImpl_SObject)& so,
1280                                            SALOMEDSImpl_Driver*                engine,
1281                                            bool                                isMultiFile,
1282                                            bool                                isASCII)
1283 {
1284   TDF_ChildIterator itchild(so->GetLabel());
1285   TCollection_AsciiString ior_string,  persistent_string, curid;
1286
1287   for (; itchild.More(); itchild.Next()) {
1288     Handle(SALOMEDSImpl_SObject) current = SALOMEDSImpl_Study::SObject(itchild.Value());
1289     Handle(SALOMEDSImpl_AttributeIOR) IOR;
1290     if (current->GetLabel().FindAttribute(SALOMEDSImpl_AttributeIOR::GetID(), IOR)) {
1291       ior_string = IOR->Value();
1292
1293       persistent_string = engine->IORToLocalPersistentID (current, ior_string, isMultiFile, isASCII);
1294       SALOMEDSImpl_AttributePersistentRef::Set(current->GetLabel(), persistent_string);
1295     }
1296     Translate_IOR_to_persistentID (current, engine, isMultiFile, isASCII);
1297   }
1298 }