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