Salome HOME
943992055a274818587808ac2ff7e0542ceb6c50
[modules/shaper.git] / src / Model / Model_Document.cpp
1 // File:        Model_Document.cxx
2 // Created:     28 Feb 2014
3 // Author:      Mikhail PONIKAROV
4
5 #include <Model_Document.h>
6 #include <ModelAPI_Feature.h>
7 #include <Model_Data.h>
8 #include <Model_Application.h>
9 #include <Model_PluginManager.h>
10 #include <Model_Events.h>
11 #include <Events_Loop.h>
12 #include <Events_Error.h>
13
14 #include <TDataStd_Integer.hxx>
15 #include <TDataStd_Comment.hxx>
16 #include <TDF_ChildIDIterator.hxx>
17 #include <TDataStd_ReferenceArray.hxx>
18 #include <TDataStd_HLabelArray1.hxx>
19
20 #include <climits>
21
22 #ifdef WIN32
23 # define _separator_ '\\'
24 #else
25 # define _separator_ '/'
26 #endif
27
28 static const int UNDO_LIMIT = 10; // number of possible undo operations
29
30 static const int TAG_GENERAL = 1; // general properties tag
31 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree (features)
32 static const int TAG_HISTORY = 3; // tag of the history sub-tree (python dump)
33
34 using namespace std;
35
36 /// Returns the file name of this document by the nameof directory and identifuer of a document
37 static TCollection_ExtendedString DocFileName(const char* theFileName, const string& theID)
38 {
39   TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
40   aPath += _separator_;
41   aPath += theID.c_str();
42   aPath += ".cbf"; // standard binary file extension
43   return aPath;
44 }
45
46 bool Model_Document::load(const char* theFileName)
47 {
48   Handle(Model_Application) anApp = Model_Application::getApplication();
49   if (this == Model_PluginManager::get()->rootDocument().get()) {
50     anApp->setLoadPath(theFileName);
51   }
52   TCollection_ExtendedString aPath (DocFileName(theFileName, myID));
53   PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
54   try
55   {
56     aStatus = anApp->Open(aPath, myDoc);
57   }
58   catch (Standard_Failure)
59   {
60     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
61     Events_Error::send(string("Exception in opening of document: ") + aFail->GetMessageString());
62     return false;
63   }
64   bool isError = aStatus != PCDM_RS_OK;
65   if (isError)
66   {
67     switch (aStatus)
68     {
69     case PCDM_RS_UnknownDocument: 
70       Events_Error::send(string("Can not open document: PCDM_RS_UnknownDocument")); break;
71     case PCDM_RS_AlreadyRetrieved: 
72       Events_Error::send(string("Can not open document: PCDM_RS_AlreadyRetrieved")); break;
73     case PCDM_RS_AlreadyRetrievedAndModified:
74       Events_Error::send(string("Can not open document: PCDM_RS_AlreadyRetrievedAndModified")); break;
75     case PCDM_RS_NoDriver:
76       Events_Error::send(string("Can not open document: PCDM_RS_NoDriver")); break;
77     case PCDM_RS_UnknownFileDriver:
78       Events_Error::send(string("Can not open document: PCDM_RS_UnknownFileDriver")); break;
79     case PCDM_RS_OpenError:
80       Events_Error::send(string("Can not open document: PCDM_RS_OpenError")); break;
81     case PCDM_RS_NoVersion:
82       Events_Error::send(string("Can not open document: PCDM_RS_NoVersion")); break;
83     case PCDM_RS_NoModel:
84       Events_Error::send(string("Can not open document: PCDM_RS_NoModel")); break;
85     case PCDM_RS_NoDocument:
86       Events_Error::send(string("Can not open document: PCDM_RS_NoDocument")); break;
87     case PCDM_RS_FormatFailure:
88       Events_Error::send(string("Can not open document: PCDM_RS_FormatFailure")); break;
89     case PCDM_RS_TypeNotFoundInSchema:
90       Events_Error::send(string("Can not open document: PCDM_RS_TypeNotFoundInSchema")); break;
91     case PCDM_RS_UnrecognizedFileFormat:
92       Events_Error::send(string("Can not open document: PCDM_RS_UnrecognizedFileFormat")); break;
93     case PCDM_RS_MakeFailure:
94       Events_Error::send(string("Can not open document: PCDM_RS_MakeFailure")); break;
95     case PCDM_RS_PermissionDenied:
96       Events_Error::send(string("Can not open document: PCDM_RS_PermissionDenied")); break;
97     case PCDM_RS_DriverFailure:
98       Events_Error::send(string("Can not open document: PCDM_RS_DriverFailure")); break;
99     default:
100       Events_Error::send(string("Can not open document: unknown error")); break;
101     }
102   }
103   if (!isError) {
104     myDoc->SetUndoLimit(UNDO_LIMIT);
105     synchronizeFeatures();
106   }
107   return !isError;
108 }
109
110 bool Model_Document::save(const char* theFileName)
111 {
112   // create a directory in the root document if it is not yet exist
113   if (this == Model_PluginManager::get()->rootDocument().get()) {
114 #ifdef WIN32
115     CreateDirectory(theFileName, NULL);
116 #else
117     mkdir(theFileName, 0x1ff); 
118 #endif
119   }
120   // filename in the dir is id of document inside of the given directory
121   TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
122   PCDM_StoreStatus aStatus;
123   try {
124     aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
125   }
126   catch (Standard_Failure) {
127     Handle(Standard_Failure) aFail = Standard_Failure::Caught();
128     Events_Error::send(string("Exception in saving of document: ") + aFail->GetMessageString());
129     return false;
130   }
131   bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
132   if (!isDone)
133   {
134     switch (aStatus)
135     {
136     case PCDM_SS_DriverFailure:
137       Events_Error::send(string("Can not save document: PCDM_SS_DriverFailure"));
138       break;
139     case PCDM_SS_WriteFailure:
140       Events_Error::send(string("Can not save document: PCDM_SS_WriteFailure"));
141       break;
142     case PCDM_SS_Failure:
143     default:
144       Events_Error::send(string("Can not save document: PCDM_SS_Failure"));
145       break;
146     }
147   }
148   myTransactionsAfterSave = 0;
149   if (isDone) { // save also sub-documents if any
150     set<string>::iterator aSubIter = mySubs.begin();
151     for(; aSubIter != mySubs.end() && isDone; aSubIter++)
152       isDone = subDocument(*aSubIter)->save(theFileName);
153   }
154   return isDone;
155 }
156
157 void Model_Document::close()
158 {
159   // close all subs
160   set<string>::iterator aSubIter = mySubs.begin();
161   for(; aSubIter != mySubs.end(); aSubIter++)
162     subDocument(*aSubIter)->close();
163   mySubs.clear();
164   // close this
165   myDoc->Close();
166   Model_Application::getApplication()->deleteDocument(myID);
167 }
168
169 void Model_Document::startOperation()
170 {
171   // check is it nested or not
172   if (myDoc->HasOpenCommand()) {
173     myNestedStart = myTransactionsAfterSave;
174   }
175   // new command for this
176   myDoc->NewCommand();
177   // new command for all subs
178   set<string>::iterator aSubIter = mySubs.begin();
179   for(; aSubIter != mySubs.end(); aSubIter++)
180     subDocument(*aSubIter)->startOperation();
181 }
182
183 void Model_Document::finishOperation()
184 {
185   if (myNestedStart > myTransactionsAfterSave) // this nested transaction is owervritten
186     myNestedStart = 0;
187   // returns false if delta is empty and no transaction was made
188   myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();
189   myTransactionsAfterSave++;
190   // finish for all subs
191   set<string>::iterator aSubIter = mySubs.begin();
192   for(; aSubIter != mySubs.end(); aSubIter++)
193     subDocument(*aSubIter)->finishOperation();
194 }
195
196 void Model_Document::abortOperation()
197 {
198   myDoc->AbortCommand();
199   synchronizeFeatures();
200   // abort for all subs
201   set<string>::iterator aSubIter = mySubs.begin();
202   for(; aSubIter != mySubs.end(); aSubIter++)
203     subDocument(*aSubIter)->abortOperation();
204 }
205
206 bool Model_Document::isOperation()
207 {
208   // operation is opened for all documents: no need to check subs
209   return myDoc->HasOpenCommand() == Standard_True ;
210 }
211
212 bool Model_Document::isModified()
213 {
214   // is modified if at least one operation was commited and not undoed
215   return myTransactionsAfterSave > 0;
216 }
217
218 bool Model_Document::canUndo()
219 {
220   if (myDoc->GetAvailableUndos() > 0 && myNestedStart != myTransactionsAfterSave)
221     return true;
222   // check other subs contains operation that can be undoed
223   set<string>::iterator aSubIter = mySubs.begin();
224   for(; aSubIter != mySubs.end(); aSubIter++)
225     if (subDocument(*aSubIter)->canUndo())
226       return true;
227   return false;
228 }
229
230 void Model_Document::undo()
231 {
232   myTransactionsAfterSave--;
233   if (!myIsEmptyTr[myTransactionsAfterSave])
234     myDoc->Undo();
235   synchronizeFeatures();
236   // undo for all subs
237   set<string>::iterator aSubIter = mySubs.begin();
238   for(; aSubIter != mySubs.end(); aSubIter++)
239     subDocument(*aSubIter)->undo();
240 }
241
242 bool Model_Document::canRedo()
243 {
244   if (myDoc->GetAvailableRedos() > 0)
245     return true;
246   // check other subs contains operation that can be redoed
247   set<string>::iterator aSubIter = mySubs.begin();
248   for(; aSubIter != mySubs.end(); aSubIter++)
249     if (subDocument(*aSubIter)->canRedo())
250       return true;
251   return false;
252 }
253
254 void Model_Document::redo()
255 {
256   if (!myIsEmptyTr[myTransactionsAfterSave])
257     myDoc->Redo();
258   myTransactionsAfterSave++;
259   synchronizeFeatures();
260   // redo for all subs
261   set<string>::iterator aSubIter = mySubs.begin();
262   for(; aSubIter != mySubs.end(); aSubIter++)
263     subDocument(*aSubIter)->redo();
264 }
265
266 boost::shared_ptr<ModelAPI_Feature> Model_Document::addFeature(string theID)
267 {
268   boost::shared_ptr<ModelAPI_Feature> aFeature = 
269     ModelAPI_PluginManager::get()->createFeature(theID);
270   if (aFeature) {
271     boost::dynamic_pointer_cast<Model_Document>(aFeature->documentToAdd())->addFeature(aFeature);
272   } else {
273     // TODO: generate error that feature is not created
274   }
275   return aFeature;
276 }
277
278 void Model_Document::addFeature(const boost::shared_ptr<ModelAPI_Feature> theFeature)
279 {
280   const std::string& aGroup = theFeature->getGroup();
281   TDF_Label aGroupLab = groupLabel(aGroup);
282   TDF_Label anObjLab = aGroupLab.NewChild();
283   boost::shared_ptr<Model_Data> aData(new Model_Data);
284   aData->setFeature(theFeature);
285   aData->setLabel(anObjLab);
286   boost::shared_ptr<ModelAPI_Document> aThis = 
287     Model_Application::getApplication()->getDocument(myID);
288   theFeature->setDoc(aThis);
289   theFeature->setData(aData);
290   setUniqueName(theFeature);
291   theFeature->initAttributes();
292   // keep the feature ID to restore document later correctly
293   TDataStd_Comment::Set(anObjLab, theFeature->getKind().c_str());
294   // put index of the feature in the group in the tree
295   TDataStd_Integer::Set(anObjLab, myFeatures[aGroup].size());
296   myFeatures[aGroup].push_back(theFeature);
297   // store feature in the history of features array
298   if (theFeature->isInHistory()) {
299     Handle(TDataStd_ReferenceArray) aRefs;
300     if (!groupLabel(FEATURES_GROUP).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
301       aRefs = TDataStd_ReferenceArray::Set(groupLabel(FEATURES_GROUP), 0, 0);
302       aRefs->SetValue(0, anObjLab);
303     } else { // extend array by one more element
304       Handle(TDataStd_HLabelArray1) aNewArray = 
305         new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() + 1);
306       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
307         aNewArray->SetValue(a, aRefs->Value(a));
308       }
309       aNewArray->SetValue(aRefs->Upper() + 1, anObjLab);
310       aRefs->SetInternalArray(aNewArray);
311     }
312   }
313
314   // event: feature is added
315   static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
316   Model_FeatureUpdatedMessage aMsg(theFeature, anEvent);
317   Events_Loop::loop()->send(aMsg);
318 }
319
320 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
321 {
322   Handle(TDataStd_Integer) aFeatureIndex;
323   if (theLabel.FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
324     Handle(TDataStd_Comment) aGroupID;
325     if (theLabel.Father().FindAttribute(TDataStd_Comment::GetID(), aGroupID)) {
326       string aGroup = TCollection_AsciiString(aGroupID->Get()).ToCString();
327       if (myFeatures[aGroup].size() > aFeatureIndex->Get())
328         return myFeatures[aGroup][aFeatureIndex->Get()];
329     }
330   }
331   return boost::shared_ptr<ModelAPI_Feature>(); // not found
332 }
333
334 int Model_Document::featureIndex(boost::shared_ptr<ModelAPI_Feature> theFeature)
335 {
336   if (theFeature->document().get() != this) {
337     return theFeature->document()->featureIndex(theFeature);
338   }
339   boost::shared_ptr<Model_Data> aData =
340     boost::dynamic_pointer_cast<Model_Data>(theFeature->data());
341   Handle(TDataStd_Integer) aFeatureIndex;
342   if (aData->label().FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
343     return aFeatureIndex->Get();
344   }
345   return -1; // not found
346 }
347
348 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
349 {
350   // just store sub-document identifier here to manage it later
351   if (mySubs.find(theDocID) == mySubs.end())
352     mySubs.insert(theDocID);
353   return Model_Application::getApplication()->getDocument(theDocID);
354 }
355
356 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
357   const string& theGroupID, const int theIndex)
358 {
359   if (theGroupID == FEATURES_GROUP) { // history is just a references array
360     Handle(TDataStd_ReferenceArray) aRefs;
361     if (groupLabel(FEATURES_GROUP).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
362       if (aRefs->Lower() <= theIndex && aRefs->Upper() >= theIndex) {
363         TDF_Label aFeatureLab = aRefs->Value(theIndex);
364         return feature(aFeatureLab);
365       }
366     }
367   } else { // one of the group
368     map<string, vector<boost::shared_ptr<ModelAPI_Feature> > >::iterator aGroup = 
369       myFeatures.find(theGroupID);
370     if (aGroup != myFeatures.end() && (int)(aGroup->second.size()) > theIndex) {
371       return aGroup->second[theIndex];
372     }
373   }
374   // not found
375   return boost::shared_ptr<ModelAPI_Feature>();
376 }
377
378 int Model_Document::size(const string& theGroupID) 
379 {
380   if (theGroupID == FEATURES_GROUP) { // history is just a references array
381     Handle(TDataStd_ReferenceArray) aRefs;
382     if (groupLabel(FEATURES_GROUP).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
383       return aRefs->Length();
384   } else { // one of the group
385     map<string, vector<boost::shared_ptr<ModelAPI_Feature> > >::iterator aGroup = 
386       myFeatures.find(theGroupID);
387     if (aGroup != myFeatures.end())
388       return aGroup->second.size();
389   }
390   // group is not found
391   return 0;
392 }
393
394 const vector<string>& Model_Document::getGroups() const
395 {
396   return myGroupsNames;
397 }
398
399 Model_Document::Model_Document(const std::string theID)
400     : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
401 {
402   myDoc->SetUndoLimit(UNDO_LIMIT);
403   myTransactionsAfterSave = 0;
404   myNestedStart = 0;
405   myDoc->SetNestedTransactionMode();
406   // to have something in the document and avoid empty doc open/save problem
407   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
408 }
409
410 TDF_Label Model_Document::groupLabel(const string theGroup)
411 {
412   if (myGroups.find(theGroup) == myGroups.end()) {
413     myGroups[theGroup] = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
414     myGroupsNames.push_back(theGroup);
415     // set to the group label the group idntifier to restore on "open"
416     TDataStd_Comment::Set(myGroups[theGroup], theGroup.c_str());
417     myFeatures[theGroup] = vector<boost::shared_ptr<ModelAPI_Feature> >();
418   }
419   return myGroups[theGroup];
420 }
421
422 void Model_Document::setUniqueName(boost::shared_ptr<ModelAPI_Feature> theFeature)
423 {
424   // first count all objects of such kind to start with index = count + 1
425   int a, aNumObjects = 0;
426   int aSize = size(theFeature->getGroup());
427   for(a = 0; a < aSize; a++) {
428     if (feature(theFeature->getGroup(), a)->getKind() == theFeature->getKind())
429       aNumObjects++;
430   }
431   // generate candidate name
432   stringstream aNameStream;
433   aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
434   string aName = aNameStream.str();
435   // check this is unique, if not, increase index by 1
436   for(a = 0; a < aSize;) {
437     if (feature(theFeature->getGroup(), a)->data()->getName() == aName) {
438       aNumObjects++;
439       stringstream aNameStream;
440       aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
441       // reinitialize iterator to make sure a new name is unique
442       a = 0;
443     } else a++;
444   }
445
446   theFeature->data()->setName(aName);
447 }
448
449 void Model_Document::synchronizeFeatures()
450 {
451   boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(myID);
452   // iterate groups labels
453   TDF_ChildIDIterator aGroupsIter(myDoc->Main().FindChild(TAG_OBJECTS),
454     TDataStd_Comment::GetID(), Standard_False);
455   vector<string>::iterator aGroupNamesIter = myGroupsNames.begin();
456   for(; aGroupsIter.More() && aGroupNamesIter != myGroupsNames.end();
457         aGroupsIter.Next(), aGroupNamesIter++) {
458     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
459       aGroupsIter.Value())->Get()).ToCString();
460     if (*aGroupNamesIter != aGroupName) 
461       break; // all since there is a change this must be recreated from scratch
462   }
463   // delete all groups left after the data model groups iteration
464   while(aGroupNamesIter != myGroupsNames.end()) {
465     string aGroupName = *aGroupNamesIter;
466     myFeatures.erase(aGroupName);
467     myGroups.erase(aGroupName);
468     aGroupNamesIter = myGroupsNames.erase(aGroupNamesIter);
469     // say that features were deleted from group
470     Model_FeatureDeletedMessage aMsg(aThis, aGroupName);
471     Events_Loop::loop()->send(aMsg);
472   }
473   // create new groups basing on the following data model update
474   for(; aGroupsIter.More(); aGroupsIter.Next()) {
475     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
476       aGroupsIter.Value())->Get()).ToCString();
477     myGroupsNames.push_back(aGroupName);
478     myGroups[aGroupName] = aGroupsIter.Value()->Label();
479     myFeatures[aGroupName] = vector<boost::shared_ptr<ModelAPI_Feature> >();
480   }
481   // update features group by group
482   aGroupsIter.Initialize(myDoc->Main().FindChild(TAG_OBJECTS),
483     TDataStd_Comment::GetID(), Standard_False);
484   for(; aGroupsIter.More(); aGroupsIter.Next()) {
485     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
486       aGroupsIter.Value())->Get()).ToCString();
487     // iterate features in internal container
488     vector<boost::shared_ptr<ModelAPI_Feature> >& aFeatures = myFeatures[aGroupName];
489     vector<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = aFeatures.begin();
490     // and in parallel iterate labels of features
491     TDF_ChildIDIterator aFLabIter(
492       aGroupsIter.Value()->Label(), TDataStd_Comment::GetID(), Standard_False);
493     while(aFIter != aFeatures.end() || aFLabIter.More()) {
494       static const int INFINITE_TAG = INT_MAX; // no label means that it exists somwhere in infinite
495       int aFeatureTag = INFINITE_TAG; 
496       if (aFIter != aFeatures.end()) { // existing tag for feature
497         boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>((*aFIter)->data());
498         aFeatureTag = aData->label().Tag();
499       }
500       int aDSTag = INFINITE_TAG; 
501       if (aFLabIter.More()) { // next label in DS is existing
502         aDSTag = aFLabIter.Value()->Label().Tag();
503       }
504       if (aDSTag > aFeatureTag) { // feature is removed
505         aFIter = aFeatures.erase(aFIter);
506         // event: model is updated
507         Model_FeatureDeletedMessage aMsg(aThis, aGroupName);
508         Events_Loop::loop()->send(aMsg);
509       } else if (aDSTag < aFeatureTag) { // a new feature is inserted
510         // create a feature
511         boost::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
512           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
513           aFLabIter.Value())->Get()).ToCString());
514
515         if (aFIter == aFeatures.end()) { // must be before "setData" to redo the sketch line correctly
516           aFeatures.push_back(aFeature);
517           aFIter = aFeatures.end();
518         } else {
519           aFIter++;
520           aFeatures.insert(aFIter, aFeature);
521         }
522         boost::shared_ptr<Model_Data> aData(new Model_Data);
523         TDF_Label aLab = aFLabIter.Value()->Label();
524         aData->setLabel(aLab);
525         aData->setFeature(aFeature);
526         aFeature->setDoc(aThis);
527         aFeature->setData(aData);
528         aFeature->initAttributes();
529
530         // event: model is updated
531         static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
532         Model_FeatureUpdatedMessage aMsg(aFeature, anEvent);
533         Events_Loop::loop()->send(aMsg);
534
535         // feature for this label is added, so go to the next label
536         aFLabIter.Next();
537       } else { // nothing is changed, both iterators are incremented
538         aFIter++;
539         aFLabIter.Next();
540       }
541     }
542   }
543 }