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