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