Salome HOME
Merge remote-tracking branch 'remotes/origin/SolveSpace'
[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   // abort for all subs
200   set<string>::iterator aSubIter = mySubs.begin();
201   for(; aSubIter != mySubs.end(); aSubIter++)
202     subDocument(*aSubIter)->abortOperation();
203 }
204
205 bool Model_Document::isOperation()
206 {
207   // operation is opened for all documents: no need to check subs
208   return myDoc->HasOpenCommand() == Standard_True ;
209 }
210
211 bool Model_Document::isModified()
212 {
213   // is modified if at least one operation was commited and not undoed
214   return myTransactionsAfterSave > 0;
215 }
216
217 bool Model_Document::canUndo()
218 {
219   if (myDoc->GetAvailableUndos() > 0 && myNestedStart != myTransactionsAfterSave)
220     return true;
221   // check other subs contains operation that can be undoed
222   set<string>::iterator aSubIter = mySubs.begin();
223   for(; aSubIter != mySubs.end(); aSubIter++)
224     if (subDocument(*aSubIter)->canUndo())
225       return true;
226   return false;
227 }
228
229 void Model_Document::undo()
230 {
231   myTransactionsAfterSave--;
232   if (!myIsEmptyTr[myTransactionsAfterSave])
233     myDoc->Undo();
234   synchronizeFeatures();
235   // undo for all subs
236   set<string>::iterator aSubIter = mySubs.begin();
237   for(; aSubIter != mySubs.end(); aSubIter++)
238     subDocument(*aSubIter)->undo();
239 }
240
241 bool Model_Document::canRedo()
242 {
243   if (myDoc->GetAvailableRedos() > 0)
244     return true;
245   // check other subs contains operation that can be redoed
246   set<string>::iterator aSubIter = mySubs.begin();
247   for(; aSubIter != mySubs.end(); aSubIter++)
248     if (subDocument(*aSubIter)->canRedo())
249       return true;
250   return false;
251 }
252
253 void Model_Document::redo()
254 {
255   if (!myIsEmptyTr[myTransactionsAfterSave])
256     myDoc->Redo();
257   myTransactionsAfterSave++;
258   synchronizeFeatures();
259   // redo for all subs
260   set<string>::iterator aSubIter = mySubs.begin();
261   for(; aSubIter != mySubs.end(); aSubIter++)
262     subDocument(*aSubIter)->redo();
263 }
264
265 boost::shared_ptr<ModelAPI_Feature> Model_Document::addFeature(string theID)
266 {
267   boost::shared_ptr<ModelAPI_Feature> aFeature = 
268     ModelAPI_PluginManager::get()->createFeature(theID);
269   if (aFeature) {
270     boost::dynamic_pointer_cast<Model_Document>(aFeature->documentToAdd())->addFeature(aFeature);
271   } else {
272     // TODO: generate error that feature is not created
273   }
274   return aFeature;
275 }
276
277 void Model_Document::addFeature(const boost::shared_ptr<ModelAPI_Feature> theFeature)
278 {
279   const std::string& aGroup = theFeature->getGroup();
280   TDF_Label aGroupLab = groupLabel(aGroup);
281   TDF_Label anObjLab = aGroupLab.NewChild();
282   boost::shared_ptr<Model_Data> aData(new Model_Data);
283   aData->setFeature(theFeature);
284   aData->setLabel(anObjLab);
285   boost::shared_ptr<ModelAPI_Document> aThis = 
286     Model_Application::getApplication()->getDocument(myID);
287   theFeature->setDoc(aThis);
288   theFeature->setData(aData);
289   setUniqueName(theFeature);
290   theFeature->initAttributes();
291   // keep the feature ID to restore document later correctly
292   TDataStd_Comment::Set(anObjLab, theFeature->getKind().c_str());
293   // put index of the feature in the group in the tree
294   TDataStd_Integer::Set(anObjLab, myFeatures[aGroup].size());
295   myFeatures[aGroup].push_back(theFeature);
296   // store feature in the history of features array
297   if (theFeature->isInHistory()) {
298     Handle(TDataStd_ReferenceArray) aRefs;
299     if (!groupLabel(FEATURES_GROUP).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
300       aRefs = TDataStd_ReferenceArray::Set(groupLabel(FEATURES_GROUP), 0, 0);
301       aRefs->SetValue(0, anObjLab);
302     } else { // extend array by one more element
303       Handle(TDataStd_HLabelArray1) aNewArray = 
304         new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() + 1);
305       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
306         aNewArray->SetValue(a, aRefs->Value(a));
307       }
308       aNewArray->SetValue(aRefs->Upper() + 1, anObjLab);
309       aRefs->SetInternalArray(aNewArray);
310     }
311   }
312
313   // event: feature is added
314   static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
315   Model_FeatureUpdatedMessage aMsg(theFeature, anEvent);
316   Events_Loop::loop()->send(aMsg);
317 }
318
319 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
320 {
321   Handle(TDataStd_Integer) aFeatureIndex;
322   if (theLabel.FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
323     Handle(TDataStd_Comment) aGroupID;
324     if (theLabel.Father().FindAttribute(TDataStd_Comment::GetID(), aGroupID)) {
325       string aGroup = TCollection_AsciiString(aGroupID->Get()).ToCString();
326       return myFeatures[aGroup][aFeatureIndex->Get()];
327     }
328   }
329   return boost::shared_ptr<ModelAPI_Feature>(); // not found
330 }
331
332 int Model_Document::featureIndex(boost::shared_ptr<ModelAPI_Feature> theFeature)
333 {
334   if (theFeature->document().get() != this) {
335     return theFeature->document()->featureIndex(theFeature);
336   }
337   boost::shared_ptr<Model_Data> aData =
338     boost::dynamic_pointer_cast<Model_Data>(theFeature->data());
339   Handle(TDataStd_Integer) aFeatureIndex;
340   if (aData->label().FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
341     return aFeatureIndex->Get();
342   }
343   return -1; // not found
344 }
345
346 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
347 {
348   // just store sub-document identifier here to manage it later
349   if (mySubs.find(theDocID) == mySubs.end())
350     mySubs.insert(theDocID);
351   return Model_Application::getApplication()->getDocument(theDocID);
352 }
353
354 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
355   const string& theGroupID, const int theIndex)
356 {
357   if (theGroupID == FEATURES_GROUP) { // history is just a references array
358     Handle(TDataStd_ReferenceArray) aRefs;
359     if (groupLabel(FEATURES_GROUP).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
360       if (aRefs->Lower() <= theIndex && aRefs->Upper() >= theIndex) {
361         TDF_Label aFeatureLab = aRefs->Value(theIndex);
362         return feature(aFeatureLab);
363       }
364     }
365   } else { // one of the group
366     map<string, vector<boost::shared_ptr<ModelAPI_Feature> > >::iterator aGroup = 
367       myFeatures.find(theGroupID);
368     if (aGroup != myFeatures.end() && (int)(aGroup->second.size()) > theIndex) {
369       return aGroup->second[theIndex];
370     }
371   }
372   // not found
373   return boost::shared_ptr<ModelAPI_Feature>();
374 }
375
376 int Model_Document::size(const string& theGroupID) 
377 {
378   if (theGroupID == FEATURES_GROUP) { // history is just a references array
379     Handle(TDataStd_ReferenceArray) aRefs;
380     if (groupLabel(FEATURES_GROUP).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
381       return aRefs->Length();
382   } else { // one of the group
383     map<string, vector<boost::shared_ptr<ModelAPI_Feature> > >::iterator aGroup = 
384       myFeatures.find(theGroupID);
385     if (aGroup != myFeatures.end())
386       return aGroup->second.size();
387   }
388   // group is not found
389   return 0;
390 }
391
392 const vector<string>& Model_Document::getGroups() const
393 {
394   return myGroupsNames;
395 }
396
397 Model_Document::Model_Document(const std::string theID)
398     : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
399 {
400   myDoc->SetUndoLimit(UNDO_LIMIT);
401   myTransactionsAfterSave = 0;
402   myNestedStart = 0;
403   myDoc->SetNestedTransactionMode();
404   // to have something in the document and avoid empty doc open/save problem
405   TDataStd_Integer::Set(myDoc->Main().Father(), 0);
406 }
407
408 TDF_Label Model_Document::groupLabel(const string theGroup)
409 {
410   if (myGroups.find(theGroup) == myGroups.end()) {
411     myGroups[theGroup] = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
412     myGroupsNames.push_back(theGroup);
413     // set to the group label the group idntifier to restore on "open"
414     TDataStd_Comment::Set(myGroups[theGroup], theGroup.c_str());
415     myFeatures[theGroup] = vector<boost::shared_ptr<ModelAPI_Feature> >();
416   }
417   return myGroups[theGroup];
418 }
419
420 void Model_Document::setUniqueName(boost::shared_ptr<ModelAPI_Feature> theFeature)
421 {
422   // first count all objects of such kind to start with index = count + 1
423   int a, aNumObjects = 0;
424   int aSize = size(theFeature->getGroup());
425   for(a = 0; a < aSize; a++) {
426     if (feature(theFeature->getGroup(), a)->getKind() == theFeature->getKind())
427       aNumObjects++;
428   }
429   // generate candidate name
430   stringstream aNameStream;
431   aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
432   string aName = aNameStream.str();
433   // check this is unique, if not, increase index by 1
434   for(a = 0; a < aSize;) {
435     if (feature(theFeature->getGroup(), a)->data()->getName() == aName) {
436       aNumObjects++;
437       stringstream aNameStream;
438       aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
439       // reinitialize iterator to make sure a new name is unique
440       a = 0;
441     } else a++;
442   }
443
444   theFeature->data()->setName(aName);
445 }
446
447 void Model_Document::synchronizeFeatures()
448 {
449   boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(myID);
450   // iterate groups labels
451   TDF_ChildIDIterator aGroupsIter(myDoc->Main().FindChild(TAG_OBJECTS),
452     TDataStd_Comment::GetID(), Standard_False);
453   vector<string>::iterator aGroupNamesIter = myGroupsNames.begin();
454   for(; aGroupsIter.More() && aGroupNamesIter != myGroupsNames.end();
455         aGroupsIter.Next(), aGroupNamesIter++) {
456     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
457       aGroupsIter.Value())->Get()).ToCString();
458     if (*aGroupNamesIter != aGroupName) 
459       break; // all since there is a change this must be recreated from scratch
460   }
461   // delete all groups left after the data model groups iteration
462   while(aGroupNamesIter != myGroupsNames.end()) {
463     string aGroupName = *aGroupNamesIter;
464     myFeatures.erase(aGroupName);
465     myGroups.erase(aGroupName);
466     aGroupNamesIter = myGroupsNames.erase(aGroupNamesIter);
467     // say that features were deleted from group
468     Model_FeatureDeletedMessage aMsg(aThis, aGroupName);
469     Events_Loop::loop()->send(aMsg);
470   }
471   // create new groups basing on the following data model update
472   for(; aGroupsIter.More(); aGroupsIter.Next()) {
473     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
474       aGroupsIter.Value())->Get()).ToCString();
475     myGroupsNames.push_back(aGroupName);
476     myGroups[aGroupName] = aGroupsIter.Value()->Label();
477     myFeatures[aGroupName] = vector<boost::shared_ptr<ModelAPI_Feature> >();
478   }
479   // update features group by group
480   aGroupsIter.Initialize(myDoc->Main().FindChild(TAG_OBJECTS),
481     TDataStd_Comment::GetID(), Standard_False);
482   for(; aGroupsIter.More(); aGroupsIter.Next()) {
483     string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
484       aGroupsIter.Value())->Get()).ToCString();
485     // iterate features in internal container
486     vector<boost::shared_ptr<ModelAPI_Feature> >& aFeatures = myFeatures[aGroupName];
487     vector<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = aFeatures.begin();
488     // and in parallel iterate labels of features
489     TDF_ChildIDIterator aFLabIter(
490       aGroupsIter.Value()->Label(), TDataStd_Comment::GetID(), Standard_False);
491     while(aFIter != aFeatures.end() || aFLabIter.More()) {
492       static const int INFINITE_TAG = INT_MAX; // no label means that it exists somwhere in infinite
493       int aFeatureTag = INFINITE_TAG; 
494       if (aFIter != aFeatures.end()) { // existing tag for feature
495         boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>((*aFIter)->data());
496         aFeatureTag = aData->label().Tag();
497       }
498       int aDSTag = INFINITE_TAG; 
499       if (aFLabIter.More()) { // next label in DS is existing
500         aDSTag = aFLabIter.Value()->Label().Tag();
501       }
502       if (aDSTag > aFeatureTag) { // feature is removed
503         aFIter = aFeatures.erase(aFIter);
504         // event: model is updated
505         Model_FeatureDeletedMessage aMsg(aThis, aGroupName);
506         Events_Loop::loop()->send(aMsg);
507       } else if (aDSTag < aFeatureTag) { // a new feature is inserted
508         // create a feature
509         boost::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
510           TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
511           aFLabIter.Value())->Get()).ToCString());
512
513         if (aFIter == aFeatures.end()) { // must be before "setData" to redo the sketch line correctly
514           aFeatures.push_back(aFeature);
515           aFIter = aFeatures.end();
516         } else {
517           aFIter++;
518           aFeatures.insert(aFIter, aFeature);
519         }
520         boost::shared_ptr<Model_Data> aData(new Model_Data);
521         TDF_Label aLab = aFLabIter.Value()->Label();
522         aData->setLabel(aLab);
523         aData->setFeature(aFeature);
524         aFeature->setDoc(aThis);
525         aFeature->setData(aData);
526         aFeature->initAttributes();
527
528         // event: model is updated
529         static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
530         Model_FeatureUpdatedMessage aMsg(aFeature, anEvent);
531         Events_Loop::loop()->send(aMsg);
532
533         // feature for this label is added, so go to the next label
534         aFLabIter.Next();
535       } else { // nothing is changed, both iterators are incremented
536         aFIter++;
537         aFLabIter.Next();
538       }
539     }
540   }
541 }