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