]> SALOME platform Git repositories - modules/kernel.git/blob - src/SALOMEDSImpl/SALOMEDSImpl_StudyManager.cxx
Salome HOME
Implement Shutdown() method for the SALOME Session server
[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 //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   //Create a temporary url to which the study is saved 
532   std::string aUrl = SALOMEDSImpl_Tool::GetTmpDir() + SALOMEDSImpl_Tool::GetNameFromPath(aStudyUrl);
533
534   int aLocked = aStudy->GetProperties()->IsLocked();
535   if (aLocked) aStudy->GetProperties()->SetLocked(false);
536
537   SALOMEDSImpl_StudyBuilder* SB= aStudy->NewBuilder();
538   std::map<std::string, SALOMEDSImpl_Driver*> aMapTypeDriver;
539
540   try
541     {
542       // mpv 15.12.2003: for saving components we have to load all data from all modules
543       SALOMEDSImpl_SComponentIterator itcomponent1 = aStudy->NewComponentIterator();
544       for (; itcomponent1.More(); itcomponent1.Next())
545         {
546           SALOMEDSImpl_SComponent sco = itcomponent1.Value();
547           // if there is an associated Engine call its method for saving
548           std::string IOREngine;
549           try {
550             if (!sco.ComponentIOR(IOREngine)) {
551               std::string aCompType = sco.GetComment();
552               if (!aCompType.empty()) {
553
554                 SALOMEDSImpl_Driver* aDriver = aFactory->GetDriverByType(aCompType);
555                 aMapTypeDriver[aCompType] = aDriver;
556
557                 if (aDriver != NULL) {
558                   if(!SB->LoadWith(sco, aDriver)) {
559                     _errorCode = SB->GetErrorCode();
560                     return false;
561                   }
562                 }
563               }
564             }
565           } catch(...) {
566             _errorCode = "Can not restore information to resave it";
567             return false;
568           }
569         }
570
571       //std::string anOldName = aStudy->Name();
572
573       // To change for Save
574       // Do not have to do a new file but just a Open??? Rewrite all informations after erasing evrything??
575       hdf_file = new HDFfile((char*)aUrl.c_str());
576       hdf_file->CreateOnDisk();
577
578       //-----------------------------------------------------------------------
579       // 1 - Create a groupe for each SComponent and Update the PersistanceRef
580       //-----------------------------------------------------------------------
581       hdf_group_datacomponent = new HDFgroup("DATACOMPONENT",hdf_file);
582       hdf_group_datacomponent->CreateOnDisk();
583
584       SALOMEDSImpl_SComponentIterator itcomponent = aStudy->NewComponentIterator();
585
586       for (; itcomponent.More(); itcomponent.Next())
587         {
588           SALOMEDSImpl_SComponent sco = itcomponent.Value();
589
590           std::string scoid = sco.GetID();
591           hdf_sco_group = new HDFgroup((char*)scoid.c_str(), hdf_group_datacomponent);
592           hdf_sco_group->CreateOnDisk();
593
594           std::string componentDataType = sco.ComponentDataType();
595           std::string IOREngine;
596           if (sco.ComponentIOR(IOREngine))
597             {
598               SALOMEDSImpl_Driver* Engine = NULL;
599               if(aMapTypeDriver.find(componentDataType) != aMapTypeDriver.end()) {
600                 // we have found the associated engine to write the data
601                 Engine = aMapTypeDriver[componentDataType];
602               }
603               else {
604                 Engine = aFactory->GetDriverByIOR(IOREngine);
605               }
606
607               if (Engine != NULL)
608                 {
609                   SALOMEDSImpl_TMPFile* aStream = NULL;
610                   long length = 0;
611
612                   if (theASCII) aStream = Engine->SaveASCII(sco,
613                                                             SALOMEDSImpl_Tool::GetDirFromPath(aUrl),
614                                                             length,
615                                                             theMultiFile);
616                   else aStream = Engine->Save(sco,
617                                               SALOMEDSImpl_Tool::GetDirFromPath(aUrl),
618                                               length,
619                                               theMultiFile);
620                   HDFdataset *hdf_dataset;
621                   hdf_size aHDFSize[1]; 
622                   if(length > 0) {  //The component saved some auxiliary files, then put them into HDF file
623
624                     aHDFSize[0] = length;
625
626                     HDFdataset *hdf_dataset = new HDFdataset("FILE_STREAM", hdf_sco_group, HDF_STRING, aHDFSize, 1);
627                     hdf_dataset->CreateOnDisk();
628                     hdf_dataset->WriteOnDisk(aStream->Data());  //Save the stream in the HDF file
629                     hdf_dataset->CloseOnDisk();
630                   }
631
632                   if(aStream) delete aStream;
633
634                   // store multifile state
635                   aHDFSize[0] = 2;
636                   hdf_dataset = new HDFdataset("MULTIFILE_STATE", hdf_sco_group, HDF_STRING, aHDFSize, 1);
637                   hdf_dataset->CreateOnDisk();
638                   hdf_dataset->WriteOnDisk((void*)(theMultiFile?"M":"S")); // save: multi or single
639                   hdf_dataset->CloseOnDisk();
640                   hdf_dataset=0; //will be deleted by hdf_sco_AuxFiles destructor
641                   // store ASCII state
642                   aHDFSize[0] = 2;
643                   hdf_dataset = new HDFdataset("ASCII_STATE", hdf_sco_group, HDF_STRING, aHDFSize, 1);
644                   hdf_dataset->CreateOnDisk();
645                   hdf_dataset->WriteOnDisk((void*)(theASCII?"A":"B")); // save: ASCII or BINARY
646                   hdf_dataset->CloseOnDisk();
647                   hdf_dataset=0; //will be deleted by hdf_sco_AuxFiles destructor
648                   // Creation of the persistance reference  attribute
649                   Translate_IOR_to_persistentID (sco, Engine, theMultiFile, theASCII);
650                 }
651             }
652           hdf_sco_group->CloseOnDisk();
653           hdf_sco_group=0; // will be deleted by hdf_group_datacomponent destructor
654         }
655       hdf_group_datacomponent->CloseOnDisk();
656       hdf_group_datacomponent =0;  // will be deleted by hdf_file destructor
657
658       //-----------------------------------------------------------------------
659       //3 - Write the Study Structure
660       //-----------------------------------------------------------------------
661       hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
662       hdf_group_study_structure->CreateOnDisk();
663       // save component attributes
664       SALOMEDSImpl_SComponentIterator itcomp = aStudy->NewComponentIterator();
665       for (; itcomp.More(); itcomp.Next())
666         {
667           SALOMEDSImpl_SComponent SC = itcomp.Value();
668           std::string scid = SC.GetID();
669           hdf_sco_group2 = new HDFgroup((char*)scid.c_str(), hdf_group_study_structure);
670           hdf_sco_group2->CreateOnDisk();
671           SaveAttributes(SC, hdf_sco_group2);
672           // ComponentDataType treatment
673           component_name = SC.ComponentDataType();
674           name_len = (hdf_int32)component_name.length();
675           size[0] = name_len +1 ;
676           hdf_dataset = new HDFdataset("COMPONENTDATATYPE",hdf_sco_group2,HDF_STRING,size,1);
677           hdf_dataset->CreateOnDisk();
678           hdf_dataset->WriteOnDisk((char*)component_name.c_str());
679           hdf_dataset->CloseOnDisk();
680           hdf_dataset=0; //will be deleted by hdf_sco_group destructor
681           Impl_SaveObject(SC, hdf_sco_group2);
682           hdf_sco_group2->CloseOnDisk();
683           hdf_sco_group2=0; // will be deleted by hdf_group_study_structure destructor
684         }
685       //-----------------------------------------------------------------------
686       //4 - Write the Study UseCases Structure
687       //-----------------------------------------------------------------------
688       SALOMEDSImpl_SObject aSO = aStudy->FindObjectID(USE_CASE_LABEL_ID);
689       if (aSO) {
690         HDFgroup *hdf_soo_group = new HDFgroup(USE_CASE_LABEL_ID,hdf_group_study_structure);
691         hdf_soo_group->CreateOnDisk();
692         SaveAttributes(aSO, hdf_soo_group);
693         Impl_SaveObject(aSO, hdf_soo_group);
694         hdf_soo_group->CloseOnDisk();
695         hdf_soo_group=0; // will be deleted by hdf_group_study_structure destructor
696       }
697       //-----------------------------------------------------------------------
698       //5 - Write the NoteBook Variables
699       //-----------------------------------------------------------------------
700
701       //5.1 Create group to store all note book variables
702       hdf_notebook_vars = new HDFgroup("NOTEBOOK_VARIABLES",hdf_file);
703       hdf_notebook_vars->CreateOnDisk();
704       
705       std::string varValue;
706       std::string varType;
707       std::string varIndex;
708
709       for(int i=0 ;i < aStudy->myNoteBookVars.size(); i++ ){
710         // For each variable create HDF group
711         hdf_notebook_var = new HDFgroup((char*)aStudy->myNoteBookVars[i]->Name().c_str(),hdf_notebook_vars);
712         hdf_notebook_var->CreateOnDisk();
713
714         // Save Variable type
715         varType = aStudy->myNoteBookVars[i]->SaveType();
716         name_len = (hdf_int32) varType.length();
717         size[0] = name_len +1 ;
718         hdf_dataset = new HDFdataset("VARIABLE_TYPE",hdf_notebook_var,HDF_STRING,size,1);
719         hdf_dataset->CreateOnDisk();
720         hdf_dataset->WriteOnDisk((char*)varType.c_str());
721         hdf_dataset->CloseOnDisk();
722         hdf_dataset=0; //will be deleted by hdf_sco_group destructor
723         
724         char buffer[256];
725         sprintf(buffer,"%d",i);
726         varIndex= std::string(buffer);
727         name_len = (hdf_int32) varIndex.length();
728         size[0] = name_len +1 ;
729         hdf_dataset = new HDFdataset("VARIABLE_INDEX",hdf_notebook_var,HDF_STRING,size,1);
730         hdf_dataset->CreateOnDisk();
731         hdf_dataset->WriteOnDisk((char*)varIndex.c_str());
732         hdf_dataset->CloseOnDisk();
733         hdf_dataset=0; //will be deleted by hdf_sco_group destructor
734         
735         
736         // Save Variable value
737         varValue = aStudy->myNoteBookVars[i]->Save();
738         name_len = (hdf_int32) varValue.length();
739         size[0] = name_len +1 ;
740         hdf_dataset = new HDFdataset("VARIABLE_VALUE",hdf_notebook_var,HDF_STRING,size,1);
741         hdf_dataset->CreateOnDisk();
742         hdf_dataset->WriteOnDisk((char*)varValue.c_str());
743         hdf_dataset->CloseOnDisk();
744         hdf_dataset=0; //will be deleted by hdf_sco_group destructor
745         hdf_notebook_var->CloseOnDisk();
746         hdf_notebook_var = 0; //will be deleted by hdf_sco_group destructor
747       }
748       hdf_notebook_vars->CloseOnDisk();
749       hdf_notebook_vars = 0; //will be deleted by hdf_sco_group destructor
750         
751       if (aLocked) aStudy->GetProperties()->SetLocked(true);
752       //-----------------------------------------------------------------------
753       //6 - Write the Study Properties
754       //-----------------------------------------------------------------------
755       std::string study_name = aStudy->Name();
756       name_len = (hdf_int32) study_name.size();
757       size[0] = name_len +1 ;
758       hdf_dataset = new HDFdataset("STUDY_NAME",hdf_group_study_structure,HDF_STRING,size,1);
759       hdf_dataset->CreateOnDisk();
760       hdf_dataset->WriteOnDisk((char*)study_name.c_str());
761       hdf_dataset->CloseOnDisk();
762       hdf_dataset=0; // will be deleted by hdf_group_study_structure destructor
763
764       Impl_SaveProperties(aStudy, hdf_group_study_structure);
765       hdf_group_study_structure->CloseOnDisk();
766       hdf_file->CloseOnDisk();
767
768       hdf_group_study_structure =0; // will be deleted by hdf_file destructor
769       delete hdf_file; // recursively deletes all hdf objects...
770     }
771   catch (HDFexception)
772     {
773       _errorCode = "HDFexception ! ";
774       return false;
775     }
776   catch(std::exception& exc)
777     {
778       _errorCode = const_cast<char*>(exc.what());
779       return false;
780     }
781   catch(...)
782     {
783       _errorCode = "Unknown exception ! ";
784       return false;
785     }
786   if (theASCII) { // save file in ASCII format
787     HDFascii::ConvertFromHDFToASCII(aUrl.c_str(), true);
788   }
789   
790   //Now it's necessary to copy files from the temporary directory to the user defined directory.
791
792   //      The easiest way to get a list of file in the temporary directory
793
794   std::string aCmd, aTmpFileDir = SALOMEDSImpl_Tool::GetTmpDir();
795   std::string aTmpFile = aTmpFileDir +"files";
796   std::string aStudyTmpDir = SALOMEDSImpl_Tool::GetDirFromPath(aUrl);
797
798 #ifdef WIN32
799   aCmd = "dir /B \"" + aStudyTmpDir +"\" > " + aTmpFile;
800 #else
801   aCmd ="ls -1 \"" + aStudyTmpDir +"\" > " + aTmpFile;
802 #endif
803   system(aCmd.c_str());
804
805   //       Iterate and move files in the temporary directory
806   FILE* fp = fopen(aTmpFile.c_str(), "rb");
807   if(!fp) return false;
808   char* buffer = new char[2047];
809   int errors = 0;
810   while(!feof(fp) && !errors) {
811     if((fgets(buffer, 2046, fp)) == NULL) break;
812     size_t aLen = strlen(buffer);
813     if(buffer[aLen-1] == '\n') buffer[aLen-1] = char(0);
814 #ifdef WIN32
815     aCmd = "move /Y \"" + aStudyTmpDir + std::string(buffer) + "\" \"" + SALOMEDSImpl_Tool::GetDirFromPath(aStudyUrl) +"\"";
816 #else 
817     aCmd = "mv -f \"" + aStudyTmpDir + std::string(buffer) + "\" \"" + SALOMEDSImpl_Tool::GetDirFromPath(aStudyUrl)+"\"";
818 #endif
819     errors = system(aCmd.c_str());
820   }
821
822   delete []buffer;
823   fclose(fp);
824
825   //       Perform cleanup
826 #ifdef WIN32
827   DeleteFileA(aTmpFile.c_str());
828 #else 
829   unlink(aTmpFile.c_str());
830 #endif
831
832 #ifdef WIN32
833   RemoveDirectoryA(aTmpFileDir.c_str());
834   RemoveDirectoryA(aStudyTmpDir.c_str());
835 #else
836   rmdir(aTmpFileDir.c_str());
837   rmdir(aStudyTmpDir.c_str());
838 #endif
839
840   if ( !errors ) {
841     // and finally, if all is done without errors, store new URL and mark study as Saved
842     aStudy->URL(aStudyUrl);
843     aStudy->IsSaved(true);
844   }
845
846   return !errors;
847 }
848
849 //============================================================================
850 /*! Function : Impl_SaveObject
851  *  Purpose  :
852  */
853 //============================================================================
854 bool SALOMEDSImpl_StudyManager::Impl_SaveObject(const SALOMEDSImpl_SObject& SC,
855                                                 HDFgroup *hdf_group_datatype)
856 {
857   _errorCode = "";
858
859   // Write in group hdf_group_datatype all informations of SObject SC
860   // Iterative function to parse all SObjects under a SComponent
861
862   HDFgroup *hdf_group_sobject = 0;
863
864   DF_ChildIterator itchild(SC.GetLabel());
865   for (; itchild.More(); itchild.Next())
866     {
867
868       // mpv: don't save empty labels
869       std::vector<DF_Attribute*> attr = itchild.Value().GetAttributes();
870       if (attr.size() == 0) {  //No attributes on the label
871         DF_ChildIterator subchild(itchild.Value());
872         if (!subchild.More()) {
873           continue;
874         }
875         subchild.Init(itchild.Value(), true);
876         bool anEmpty = true;
877         for (; subchild.More() && anEmpty; subchild.Next()) {
878           std::vector<DF_Attribute*> attr2 = subchild.Value().GetAttributes();
879           if (attr2.size()) {
880             anEmpty = false;  //There are attributes on the child label
881             break;
882           }
883         }
884         if (anEmpty) continue;
885       }
886
887       SALOMEDSImpl_SObject SO = SALOMEDSImpl_Study::SObject(itchild.Value());
888
889       std::string scoid = SO.GetID();
890       hdf_group_sobject = new HDFgroup(scoid.c_str(), hdf_group_datatype);
891       hdf_group_sobject->CreateOnDisk();
892       SaveAttributes(SO, hdf_group_sobject);
893       Impl_SaveObject(SO, hdf_group_sobject);
894       hdf_group_sobject->CloseOnDisk();
895       hdf_group_sobject =0; // will be deleted by father hdf object destructor
896     }
897
898   return true;
899 }
900
901 //============================================================================
902 /*! Function : Impl_SubstituteSlash
903  *  Purpose  :
904  */
905 //============================================================================
906 std::string SALOMEDSImpl_StudyManager::Impl_SubstituteSlash(const std::string& aUrl)
907 {
908   _errorCode = "";
909
910   std::string theUrl(aUrl);
911   for(int i = 0; i<theUrl.size(); i++)
912     if(theUrl[i] == '/') theUrl[i] = ':';
913   return theUrl;
914 }
915
916 //============================================================================
917 /*! Function : GetDocumentOfStudy
918  *  Purpose  :
919  */
920 //============================================================================
921 DF_Document* SALOMEDSImpl_StudyManager::GetDocumentOfStudy(SALOMEDSImpl_Study* theStudy)
922 {
923   _errorCode = "";
924   return theStudy->_doc;
925 }
926
927 //============================================================================
928 /*! Function : CanCopy
929  *  Purpose  :
930  */
931 //============================================================================
932 bool SALOMEDSImpl_StudyManager::CanCopy(const SALOMEDSImpl_SObject& theObject,
933                                         SALOMEDSImpl_Driver* theEngine)
934 {
935   _errorCode = "";
936   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
937   if (!aComponent) return false;
938   if (aComponent.GetLabel() == theObject.GetLabel()) return false;
939   std::string IOREngine;
940   if (!aComponent.ComponentIOR(IOREngine)) return false;
941   if (theEngine == NULL) return false;
942   return theEngine->CanCopy(theObject);
943 }
944
945 //============================================================================
946 /*! Function : CopyLabel
947  *  Purpose  :
948  */
949 //============================================================================
950 bool SALOMEDSImpl_StudyManager::CopyLabel(SALOMEDSImpl_Study* theSourceStudy,
951                                           SALOMEDSImpl_Driver* theEngine,
952                                           const int theSourceStartDepth,
953                                           const DF_Label& theSource,
954                                           const DF_Label& theDestinationMain)
955 {
956   _errorCode = "";
957
958   int a;
959   DF_Label aTargetLabel = theDestinationMain;
960   DF_Label aAuxTargetLabel = theDestinationMain.Father().FindChild(2);
961   for(a = theSource.Depth() - theSourceStartDepth; a > 0 ; a--) {
962     DF_Label aSourceLabel = theSource;
963     for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
964     aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
965     aAuxTargetLabel = aAuxTargetLabel.FindChild(aSourceLabel.Tag());
966   }
967   // iterate attributes
968   std::vector<DF_Attribute*> attrList = theSource.GetAttributes();
969   for(int i = 0, len = attrList.size(); i<len; i++) {
970     DF_Attribute* anAttr = attrList[i];
971     std::string type = SALOMEDSImpl_GenericAttribute::Impl_GetType(anAttr);
972     if (type.substr(0, 17) == std::string("AttributeTreeNode")) continue; // never copy tree node attribute
973     if (type == std::string("AttributeTarget")) continue; // and target attribute
974
975     if (type == std::string("AttributeReference")) { // reference copied as Comment in aux tree
976       DF_Label aReferenced = dynamic_cast<SALOMEDSImpl_AttributeReference*>(anAttr)->Get();
977       std::string anEntry = aReferenced.Entry();
978       // store the value of name attribute of referenced label
979       SALOMEDSImpl_AttributeName* aNameAttribute;
980       if ((aNameAttribute=(SALOMEDSImpl_AttributeName*)aReferenced.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
981         anEntry += " ";
982         anEntry += aNameAttribute->Value();
983       }
984       SALOMEDSImpl_AttributeComment::Set(aAuxTargetLabel, anEntry);
985       continue;
986     }
987
988     if (type == std::string("AttributeIOR")) { // IOR => ID and TMPFile of Engine
989       std::string anEntry = theSource.Entry();
990       SALOMEDSImpl_SObject aSO = theSourceStudy->FindObjectID(anEntry);
991       int anObjID;
992       long aLen;
993       SALOMEDSImpl_TMPFile* aStream = theEngine->CopyFrom(aSO, anObjID, aLen);
994       std::string aResStr("");
995       for(a = 0; a < aLen; a++) {
996         aResStr += (char)(aStream->Get(a));
997       }
998
999       if(aStream) delete aStream;
1000
1001       SALOMEDSImpl_AttributeInteger::Set(aAuxTargetLabel, anObjID);
1002       SALOMEDSImpl_AttributeName::Set(aAuxTargetLabel, aResStr);
1003       continue;
1004     }
1005     DF_Attribute* aNewAttribute = anAttr->NewEmpty();
1006     aTargetLabel.AddAttribute(aNewAttribute);
1007     anAttr->Paste(aNewAttribute);
1008   }
1009
1010   return true;
1011 }
1012
1013 //============================================================================
1014 /*! Function : Copy
1015  *  Purpose  :
1016  */
1017 //============================================================================
1018 bool SALOMEDSImpl_StudyManager::Copy(const SALOMEDSImpl_SObject& theObject,
1019                                      SALOMEDSImpl_Driver* theEngine)
1020 {
1021   _errorCode = "";
1022
1023   // adoptation for alliances datamodel copy: without IOR attributes !!!
1024   bool aStructureOnly; // copy only SObjects and attributes without component help
1025   aStructureOnly = !theObject.GetLabel().IsAttribute(SALOMEDSImpl_AttributeIOR::GetID());
1026
1027   // get component-engine
1028   SALOMEDSImpl_Study* aStudy = theObject.GetStudy();
1029
1030   // CAF document of current study usage
1031   DF_Document* aDocument = GetDocumentOfStudy(aStudy);
1032   if (!aDocument) {
1033     _errorCode = "Document is null";
1034     return false;
1035   }
1036
1037   //Clear the clipboard
1038   _clipboard->Main().Root().ForgetAllAttributes(true);
1039   _appli->Close(_clipboard);
1040   _clipboard = _appli->NewDocument("SALOME_STUDY");
1041
1042   // set component data type to the name attribute of root label
1043   if (!aStructureOnly) {
1044     SALOMEDSImpl_AttributeComment::Set(_clipboard->Main().Root(),
1045                                        theEngine->ComponentDataType());
1046   }
1047   // set to the Root label integer attribute: study id
1048   SALOMEDSImpl_AttributeInteger::Set(_clipboard->Main().Root(), aStudy->StudyId());
1049   // iterate all theObject's label children
1050   DF_Label aStartLabel = theObject.GetLabel();
1051   int aSourceStartDepth = aStartLabel.Depth();
1052
1053   // copy main source label
1054   CopyLabel(aStudy, theEngine, aSourceStartDepth, aStartLabel, _clipboard->Main());
1055
1056   // copy all subchildren of the main source label (all levels)
1057   DF_ChildIterator anIterator(aStartLabel, true);
1058   for(; anIterator.More(); anIterator.Next()) {
1059     CopyLabel(aStudy, theEngine, aSourceStartDepth, anIterator.Value(), _clipboard->Main());
1060   }
1061
1062   return true;
1063 }
1064 //============================================================================
1065 /*! Function : CanPaste
1066  *  Purpose  :
1067  */
1068 //============================================================================
1069 bool SALOMEDSImpl_StudyManager::CanPaste(const SALOMEDSImpl_SObject& theObject,
1070                                          SALOMEDSImpl_Driver* theEngine)
1071 {
1072   _errorCode = "";
1073
1074   if (!_clipboard) {
1075     _errorCode = "Clipboard is null";
1076     return false;
1077   }
1078
1079   SALOMEDSImpl_AttributeComment* aCompName = NULL;
1080   if (!(aCompName=(SALOMEDSImpl_AttributeComment*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID()))) {
1081     _errorCode = "Clipboard has no component type";
1082     return false;
1083   }
1084   SALOMEDSImpl_AttributeInteger* anObjID;
1085   if (!(anObjID=(SALOMEDSImpl_AttributeInteger*)_clipboard->Main().Father().FindChild(2).FindAttribute(SALOMEDSImpl_AttributeInteger::GetID()))) {
1086     _errorCode = "Clipboard has no object id";
1087     return false;
1088   }
1089   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
1090   if (!aComponent) {
1091     _errorCode = "Object doesn't belong to component";
1092     return false;
1093   }
1094
1095   std::string IOREngine;
1096   if (!aComponent.ComponentIOR(IOREngine)) {
1097     _errorCode = "component has no IOR";
1098     return false;
1099   }
1100   return theEngine->CanPaste(aCompName->Value(), anObjID->Value());
1101 }
1102
1103 //============================================================================
1104 /*! Function : PasteLabel
1105  *  Purpose  :
1106  */
1107 //============================================================================
1108 DF_Label SALOMEDSImpl_StudyManager::PasteLabel(SALOMEDSImpl_Study* theDestinationStudy,
1109                                                SALOMEDSImpl_Driver* theEngine,
1110                                                const DF_Label& theSource,
1111                                                const DF_Label& theDestinationStart,
1112                                                const int theCopiedStudyID,
1113                                                const bool isFirstElement)
1114 {
1115   _errorCode = "";
1116
1117   // get corresponding source, target and auxiliary labels
1118   DF_Label aTargetLabel = theDestinationStart;
1119
1120   DF_Label aAuxSourceLabel = theSource.Root().FindChild(2);
1121   int a;
1122   if (!isFirstElement) {
1123     for(a = theSource.Depth() - 1; a > 0 ; a--) {
1124       DF_Label aSourceLabel = theSource;
1125       for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
1126       aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
1127       aAuxSourceLabel = aAuxSourceLabel.FindChild(aSourceLabel.Tag());
1128     }
1129     SALOMEDSImpl_SObject so = theDestinationStudy->GetSObject(aTargetLabel);
1130     theDestinationStudy->addSO_Notification(so);
1131   }
1132
1133   // check auxiliary label for TMPFile => IOR
1134   SALOMEDSImpl_AttributeName* aNameAttribute = NULL;
1135   if ((aNameAttribute=(SALOMEDSImpl_AttributeName*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
1136     SALOMEDSImpl_AttributeInteger* anObjID = (SALOMEDSImpl_AttributeInteger*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeInteger::GetID());
1137     SALOMEDSImpl_AttributeComment* aComponentName = (SALOMEDSImpl_AttributeComment*)theSource.Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID());
1138     std::string aCompName = aComponentName->Value();
1139
1140     if (theEngine->CanPaste(aCompName, anObjID->Value())) {
1141       std::string aTMPStr = aNameAttribute->Value();
1142       int aLen = aTMPStr.size();
1143       unsigned char* aStream = NULL;
1144       if(aLen > 0) {
1145         aStream = new unsigned char[aLen+10];
1146         for(a = 0; a < aLen; a++) {
1147           aStream[a] = aTMPStr[a];
1148         }
1149       }
1150
1151       std::string anEntry = aTargetLabel.Entry();
1152       SALOMEDSImpl_SObject aPastedSO = theDestinationStudy->FindObjectID(anEntry);
1153
1154       if (isFirstElement) {
1155         std::string aDestEntry = theEngine->PasteInto(aStream,
1156                                                  aLen,
1157                                                  anObjID->Value(),
1158                                                  aPastedSO.GetFatherComponent());
1159         aTargetLabel = DF_Label::Label(theDestinationStart, aDestEntry);
1160       } else
1161         theEngine->PasteInto(aStream, aLen, anObjID->Value(), aPastedSO);
1162
1163       if(aStream != NULL) delete []aStream;
1164     }
1165   }
1166
1167   // iterate attributes
1168   std::vector<DF_Attribute*> attrList = theSource.GetAttributes();
1169   for(int i = 0, len = attrList.size(); i<len; i++) {
1170     DF_Attribute* anAttr = attrList[i];
1171     if (aTargetLabel.FindAttribute(anAttr->ID())) {
1172       aTargetLabel.ForgetAttribute(anAttr->ID());
1173     }
1174     DF_Attribute* aNewAttribute = anAttr->NewEmpty();
1175     aTargetLabel.AddAttribute(aNewAttribute);
1176     anAttr->Paste(aNewAttribute);
1177   }
1178
1179   // check auxiliary label for Comment => reference or name attribute of the referenced object
1180   SALOMEDSImpl_AttributeComment* aCommentAttribute = NULL;
1181   if ((aCommentAttribute=(SALOMEDSImpl_AttributeComment*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeComment::GetID()))) {
1182     char * anEntry = new char[aCommentAttribute->Value().size() + 1];
1183     strcpy(anEntry, std::string(aCommentAttribute->Value()).c_str());
1184     char* aNameStart = strchr(anEntry, ' ');
1185     if (aNameStart) {
1186       *aNameStart = '\0';
1187       aNameStart++;
1188     }
1189     if (theCopiedStudyID == theDestinationStudy->StudyId()) { // if copy to the same study, reanimate reference
1190       DF_Label aRefLabel = DF_Label::Label(aTargetLabel, anEntry);
1191       SALOMEDSImpl_AttributeReference::Set(aTargetLabel, aRefLabel);
1192       // target attributes structure support
1193       SALOMEDSImpl_AttributeTarget::Set(aRefLabel)->Add(SALOMEDSImpl_Study::SObject(aTargetLabel));
1194     } else {
1195       if (aNameStart) SALOMEDSImpl_AttributeName::Set(aTargetLabel, aNameStart);
1196       else SALOMEDSImpl_AttributeName::Set(aTargetLabel, std::string("Reference to:")+anEntry);
1197     }
1198     delete [] anEntry;
1199   }
1200
1201   return aTargetLabel;
1202 }
1203
1204 //============================================================================
1205 /*! Function : Paste
1206  *  Purpose  :
1207  */
1208 //============================================================================
1209 SALOMEDSImpl_SObject SALOMEDSImpl_StudyManager::Paste(const SALOMEDSImpl_SObject& theObject,
1210                                                SALOMEDSImpl_Driver* theEngine)
1211 {
1212   _errorCode = "";
1213
1214   SALOMEDSImpl_SObject so;
1215   SALOMEDSImpl_Study* aStudy = theObject.GetStudy();
1216
1217   // if study is locked, then paste can't be done
1218   if (aStudy->GetProperties()->IsLocked()) {
1219     _errorCode = "LockProtection";
1220     throw LockProtection("LockProtection");
1221   }
1222
1223   // if there is no component name, then paste only SObjects and attributes: without component help
1224   SALOMEDSImpl_AttributeComment* aComponentName = NULL;
1225   bool aStructureOnly = !(aComponentName=(SALOMEDSImpl_AttributeComment*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID()));
1226
1227   // get copied study ID
1228   SALOMEDSImpl_AttributeInteger* aStudyIDAttribute = NULL;
1229   if (!(aStudyIDAttribute=(SALOMEDSImpl_AttributeInteger*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeInteger::GetID()))) {
1230     _errorCode = "No study ID was found";
1231     return so;
1232   }
1233   int aCStudyID = aStudyIDAttribute->Value();
1234
1235   // CAF document of current study usage
1236   DF_Document* aDocument = GetDocumentOfStudy(aStudy);
1237   if (!aDocument) {
1238     _errorCode = "Document is null";
1239     return so;
1240   }
1241
1242   SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
1243
1244   // fill root inserted SObject
1245   DF_Label aStartLabel;
1246   if (aStructureOnly) {
1247     DF_Label anObjectLabel = DF_Label::Label(aDocument->Main(), theObject.GetID());
1248     aStartLabel = PasteLabel(aStudy, theEngine, _clipboard->Main(), anObjectLabel, aCStudyID, false);
1249   } else {
1250     DF_Label aComponentLabel = DF_Label::Label(aDocument->Main(), aComponent.GetID());
1251     aStartLabel = PasteLabel(aStudy, theEngine, _clipboard->Main(), aComponentLabel, aCStudyID, true);
1252   }
1253
1254   // paste all sublebels
1255   DF_ChildIterator anIterator(_clipboard->Main(), true);
1256   for(; anIterator.More(); anIterator.Next()) {
1257     PasteLabel(aStudy, theEngine, anIterator.Value(), aStartLabel, aCStudyID, false);
1258   }
1259
1260   return SALOMEDSImpl_Study::SObject(aStartLabel);
1261 }
1262
1263 //#######################################################################################################
1264 //#                                     STATIC PRIVATE FUNCTIONS
1265 //#######################################################################################################
1266
1267 //============================================================================
1268 /*! Function : SaveAttributes
1269  *  Purpose  : Save attributes for object
1270  */
1271 //============================================================================
1272 static void SaveAttributes(const SALOMEDSImpl_SObject& aSO, HDFgroup *hdf_group_sobject)
1273 {
1274   hdf_size size[1];
1275   std::vector<DF_Attribute*> attrList = aSO.GetLabel().GetAttributes();
1276   DF_Attribute* anAttr = NULL;
1277   for(int i = 0, len = attrList.size(); i<len; i++) {
1278     anAttr = attrList[i];
1279     //The following attributes are not supposed to be written to the file
1280     std::string type = SALOMEDSImpl_GenericAttribute::Impl_GetType(anAttr);
1281     if(type == std::string("AttributeIOR")) continue; //IOR attribute is not saved
1282     std::string aSaveStr =anAttr->Save();
1283     //cout << "Saving: " << aSO.GetID() << " type: "<< type<<"|" << endl;
1284     size[0] = (hdf_int32) strlen(aSaveStr.c_str()) + 1;
1285     HDFdataset *hdf_dataset = new HDFdataset((char*)type.c_str(), hdf_group_sobject, HDF_STRING,size, 1);
1286     hdf_dataset->CreateOnDisk();
1287     hdf_dataset->WriteOnDisk((char*)aSaveStr.c_str());
1288     hdf_dataset->CloseOnDisk();
1289     hdf_dataset=0; //will be deleted by hdf_sco_group destructor
1290   }
1291 }
1292
1293 //===========================================================================
1294 //Function : ReadAttributes
1295 //===========================================================================
1296 static void ReadAttributes(SALOMEDSImpl_Study* theStudy,
1297                            const SALOMEDSImpl_SObject& aSO,
1298                            HDFdataset* hdf_dataset)
1299 {
1300   hdf_dataset->OpenOnDisk();
1301
1302   DF_Attribute* anAttr = NULL;
1303   char* current_string = new char[hdf_dataset->GetSize()+1];
1304   hdf_dataset->ReadFromDisk(current_string);
1305   //cout << "Reading attr type = " << hdf_dataset->GetName() << "  SO = " << aSO.GetID() << endl;
1306   if (!strcmp(hdf_dataset->GetName(),"COMPONENTDATATYPE")) {
1307     anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, "AttributeComment");
1308   } else if (!strcmp(hdf_dataset->GetName(),"AttributeReference") ||
1309              !strcmp(hdf_dataset->GetName(),"Reference")) { // Old format maintainance
1310     theStudy->NewBuilder()->Addreference(aSO, theStudy->CreateObjectID(current_string));
1311     delete [] (current_string);
1312     hdf_dataset->CloseOnDisk();
1313     return;
1314   } else {
1315     anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, hdf_dataset->GetName());
1316   }
1317   
1318   if (anAttr) {
1319     anAttr->Load(current_string);
1320   }
1321   
1322   delete [] (current_string);
1323   hdf_dataset->CloseOnDisk();
1324 }
1325
1326 //============================================================================
1327 //Function : BuildlTree
1328 //============================================================================
1329 static void BuildTree (SALOMEDSImpl_Study* theStudy, HDFgroup* hdf_current_group)
1330 {
1331   hdf_current_group->OpenOnDisk();
1332   SALOMEDSImpl_SObject aSO;
1333   char* Entry = hdf_current_group->GetName();
1334   if (strcmp(Entry,"STUDY_STRUCTURE") == 0) {
1335     aSO = theStudy->CreateObjectID("0:1");
1336   }
1337   else {
1338     aSO = theStudy->CreateObjectID(Entry);
1339   }
1340
1341   char name[HDF_NAME_MAX_LEN+1];
1342   int nbsons = hdf_current_group->nInternalObjects();
1343   for (int i=0; i<nbsons; i++) {
1344     hdf_current_group->InternalObjectIndentify(i,name);
1345     if (strncmp(name, "INTERNAL_COMPLEX",16) == 0) continue;
1346     hdf_object_type type = hdf_current_group->InternalObjectType(name);
1347
1348     if  (type == HDF_DATASET) {
1349       HDFdataset* new_dataset = new HDFdataset(name,hdf_current_group);
1350       ReadAttributes(theStudy,aSO,new_dataset);
1351       new_dataset = 0; // will be deleted by father destructor
1352
1353     }
1354     else if (type == HDF_GROUP)   {
1355       HDFgroup* new_group = new HDFgroup(name,hdf_current_group);
1356       BuildTree (theStudy, new_group);
1357       new_group = 0; // will be deleted by father destructor
1358     }
1359   }
1360   hdf_current_group->CloseOnDisk();
1361 }
1362
1363
1364 //============================================================================
1365 //Function : Translate_IOR_to_persistentID
1366 //============================================================================
1367 static void Translate_IOR_to_persistentID (const SALOMEDSImpl_SObject& so,
1368                                            SALOMEDSImpl_Driver*                engine,
1369                                            bool                                isMultiFile,
1370                                            bool                                isASCII)
1371 {
1372   DF_ChildIterator itchild(so.GetLabel());
1373   std::string ior_string,  persistent_string, curid;
1374
1375   for (; itchild.More(); itchild.Next()) {
1376     SALOMEDSImpl_SObject current = SALOMEDSImpl_Study::SObject(itchild.Value());
1377     SALOMEDSImpl_AttributeIOR* IOR = NULL;
1378     if ((IOR=(SALOMEDSImpl_AttributeIOR*)current.GetLabel().FindAttribute(SALOMEDSImpl_AttributeIOR::GetID()))) {
1379       ior_string = IOR->Value();
1380
1381       persistent_string = engine->IORToLocalPersistentID (current, ior_string, isMultiFile, isASCII);
1382       SALOMEDSImpl_AttributePersistentRef::Set(current.GetLabel(), persistent_string);
1383     }
1384     Translate_IOR_to_persistentID (current, engine, isMultiFile, isASCII);
1385   }
1386 }
1387
1388 void ReadNoteBookVariables(SALOMEDSImpl_Study* theStudy, HDFgroup* theGroup)
1389 {
1390   if(!theGroup)
1391     return;
1392
1393   HDFgroup* new_group =0;
1394   HDFdataset* new_dataset =0;
1395   
1396   char aVarName[HDF_NAME_MAX_LEN+1];
1397   char *currentVarType = 0;
1398   char *currentVarValue = 0;
1399   char *currentVarIndex = 0;
1400   int order = 0;
1401   //Open HDF group with notebook variables
1402   theGroup->OpenOnDisk();
1403
1404   //Get Nb of variables
1405   int aNbVars = theGroup->nInternalObjects();
1406
1407   std::map<int,SALOMEDSImpl_GenericVariable*> aVarsMap;
1408
1409   for( int iVar=0;iVar < aNbVars;iVar++ ) {
1410     theGroup->InternalObjectIndentify(iVar,aVarName);
1411     hdf_object_type type = theGroup->InternalObjectType(aVarName);
1412     if(type == HDF_GROUP) {
1413
1414       //Read Variable
1415       new_group = new HDFgroup(aVarName,theGroup);
1416       new_group->OpenOnDisk();
1417
1418       //Read Type
1419       new_dataset = new HDFdataset("VARIABLE_TYPE",new_group);
1420       new_dataset->OpenOnDisk();
1421       currentVarType = new char[new_dataset->GetSize()+1];
1422       new_dataset->ReadFromDisk(currentVarType);
1423       new_dataset->CloseOnDisk();
1424       new_dataset = 0; //will be deleted by hdf_sco_group destructor
1425
1426       //Read Order
1427       if(new_group->ExistInternalObject("VARIABLE_INDEX")) {
1428         new_dataset = new HDFdataset("VARIABLE_INDEX",new_group);
1429         new_dataset->OpenOnDisk();
1430         currentVarIndex = new char[new_dataset->GetSize()+1];
1431         new_dataset->ReadFromDisk(currentVarIndex);
1432         new_dataset->CloseOnDisk();
1433         new_dataset = 0; //will be deleted by hdf_sco_group destructor
1434         order = atoi(currentVarIndex);
1435         delete [] currentVarIndex;
1436       }
1437       else
1438         order = iVar;
1439       
1440       //Read Value
1441       new_dataset = new HDFdataset("VARIABLE_VALUE",new_group);
1442       new_dataset->OpenOnDisk();
1443       currentVarValue = new char[new_dataset->GetSize()+1];
1444       new_dataset->ReadFromDisk(currentVarValue);
1445       new_dataset->CloseOnDisk();
1446       new_dataset = 0; //will be deleted by hdf_sco_group destructor
1447
1448       new_group->CloseOnDisk();
1449       new_group = 0;  //will be deleted by hdf_sco_group destructor
1450       
1451       SALOMEDSImpl_GenericVariable::VariableTypes aVarType =
1452         SALOMEDSImpl_GenericVariable::String2VariableType(std::string(currentVarType));
1453       delete [] currentVarType;
1454
1455       //Create variable and add it in the study
1456       SALOMEDSImpl_GenericVariable* aVariable = 
1457         new SALOMEDSImpl_ScalarVariable(aVarType,std::string(aVarName));
1458       aVariable->Load(std::string(currentVarValue));
1459           aVarsMap.insert(std::make_pair<int,SALOMEDSImpl_GenericVariable*>(order,aVariable));
1460       delete [] currentVarValue;
1461         }
1462   }
1463   
1464   std::map<int,SALOMEDSImpl_GenericVariable*>::const_iterator it= aVarsMap.begin();
1465   for(;it!=aVarsMap.end();it++)
1466     theStudy->AddVariable((*it).second);
1467   
1468   theGroup->CloseOnDisk();
1469 }