1 // File: Model_Document.cxx
2 // Created: 28 Feb 2014
3 // Author: Mikhail PONIKAROV
5 #include <Model_Document.h>
6 #include <ModelAPI_Feature.h>
7 #include <Model_Data.h>
8 #include <Model_Object.h>
9 #include <Model_Application.h>
10 #include <Model_PluginManager.h>
11 #include <Model_Events.h>
12 #include <Events_Loop.h>
13 #include <Events_Error.h>
15 #include <TDataStd_Integer.hxx>
16 #include <TDataStd_Comment.hxx>
17 #include <TDF_ChildIDIterator.hxx>
18 #include <TDataStd_ReferenceArray.hxx>
19 #include <TDataStd_HLabelArray1.hxx>
20 #include <TDataStd_Name.hxx>
28 # define _separator_ '\\'
30 # define _separator_ '/'
33 static const int UNDO_LIMIT = 10; // number of possible undo operations
35 static const int TAG_GENERAL = 1; // general properties tag
36 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree (features)
37 static const int TAG_HISTORY = 3; // tag of the history sub-tree (python dump)
41 /// Returns the file name of this document by the nameof directory and identifuer of a document
42 static TCollection_ExtendedString DocFileName(const char* theFileName, const string& theID)
44 TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
46 aPath += theID.c_str();
47 aPath += ".cbf"; // standard binary file extension
51 bool Model_Document::load(const char* theFileName)
53 Handle(Model_Application) anApp = Model_Application::getApplication();
54 if (this == Model_PluginManager::get()->rootDocument().get()) {
55 anApp->setLoadPath(theFileName);
57 TCollection_ExtendedString aPath (DocFileName(theFileName, myID));
58 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
61 aStatus = anApp->Open(aPath, myDoc);
63 catch (Standard_Failure)
65 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
66 Events_Error::send(string("Exception in opening of document: ") + aFail->GetMessageString());
69 bool isError = aStatus != PCDM_RS_OK;
74 case PCDM_RS_UnknownDocument:
75 Events_Error::send(string("Can not open document: PCDM_RS_UnknownDocument")); break;
76 case PCDM_RS_AlreadyRetrieved:
77 Events_Error::send(string("Can not open document: PCDM_RS_AlreadyRetrieved")); break;
78 case PCDM_RS_AlreadyRetrievedAndModified:
79 Events_Error::send(string("Can not open document: PCDM_RS_AlreadyRetrievedAndModified")); break;
80 case PCDM_RS_NoDriver:
81 Events_Error::send(string("Can not open document: PCDM_RS_NoDriver")); break;
82 case PCDM_RS_UnknownFileDriver:
83 Events_Error::send(string("Can not open document: PCDM_RS_UnknownFileDriver")); break;
84 case PCDM_RS_OpenError:
85 Events_Error::send(string("Can not open document: PCDM_RS_OpenError")); break;
86 case PCDM_RS_NoVersion:
87 Events_Error::send(string("Can not open document: PCDM_RS_NoVersion")); break;
89 Events_Error::send(string("Can not open document: PCDM_RS_NoModel")); break;
90 case PCDM_RS_NoDocument:
91 Events_Error::send(string("Can not open document: PCDM_RS_NoDocument")); break;
92 case PCDM_RS_FormatFailure:
93 Events_Error::send(string("Can not open document: PCDM_RS_FormatFailure")); break;
94 case PCDM_RS_TypeNotFoundInSchema:
95 Events_Error::send(string("Can not open document: PCDM_RS_TypeNotFoundInSchema")); break;
96 case PCDM_RS_UnrecognizedFileFormat:
97 Events_Error::send(string("Can not open document: PCDM_RS_UnrecognizedFileFormat")); break;
98 case PCDM_RS_MakeFailure:
99 Events_Error::send(string("Can not open document: PCDM_RS_MakeFailure")); break;
100 case PCDM_RS_PermissionDenied:
101 Events_Error::send(string("Can not open document: PCDM_RS_PermissionDenied")); break;
102 case PCDM_RS_DriverFailure:
103 Events_Error::send(string("Can not open document: PCDM_RS_DriverFailure")); break;
105 Events_Error::send(string("Can not open document: unknown error")); break;
109 myDoc->SetUndoLimit(UNDO_LIMIT);
110 synchronizeFeatures();
115 bool Model_Document::save(const char* theFileName)
117 // create a directory in the root document if it is not yet exist
118 if (this == Model_PluginManager::get()->rootDocument().get()) {
120 CreateDirectory(theFileName, NULL);
122 mkdir(theFileName, 0x1ff);
125 // filename in the dir is id of document inside of the given directory
126 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
127 PCDM_StoreStatus aStatus;
129 aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
131 catch (Standard_Failure) {
132 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
133 Events_Error::send(string("Exception in saving of document: ") + aFail->GetMessageString());
136 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
141 case PCDM_SS_DriverFailure:
142 Events_Error::send(string("Can not save document: PCDM_SS_DriverFailure"));
144 case PCDM_SS_WriteFailure:
145 Events_Error::send(string("Can not save document: PCDM_SS_WriteFailure"));
147 case PCDM_SS_Failure:
149 Events_Error::send(string("Can not save document: PCDM_SS_Failure"));
153 myTransactionsAfterSave = 0;
154 if (isDone) { // save also sub-documents if any
155 set<string>::iterator aSubIter = mySubs.begin();
156 for(; aSubIter != mySubs.end() && isDone; aSubIter++)
157 isDone = subDocument(*aSubIter)->save(theFileName);
162 void Model_Document::close()
165 set<string>::iterator aSubIter = mySubs.begin();
166 for(; aSubIter != mySubs.end(); aSubIter++)
167 subDocument(*aSubIter)->close();
170 if (myDoc->CanClose() == CDM_CCS_OK)
172 Model_Application::getApplication()->deleteDocument(myID);
175 void Model_Document::startOperation()
177 // check is it nested or not
178 if (myDoc->HasOpenCommand()) {
179 myNestedStart = myTransactionsAfterSave;
181 // new command for this
183 // new command for all subs
184 set<string>::iterator aSubIter = mySubs.begin();
185 for(; aSubIter != mySubs.end(); aSubIter++)
186 subDocument(*aSubIter)->startOperation();
189 void Model_Document::finishOperation()
191 if (myNestedStart > myTransactionsAfterSave) // this nested transaction is owervritten
193 // returns false if delta is empty and no transaction was made
194 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();
195 myTransactionsAfterSave++;
196 // finish for all subs
197 set<string>::iterator aSubIter = mySubs.begin();
198 for(; aSubIter != mySubs.end(); aSubIter++)
199 subDocument(*aSubIter)->finishOperation();
202 void Model_Document::abortOperation()
204 myDoc->AbortCommand();
205 synchronizeFeatures();
206 // abort for all subs
207 set<string>::iterator aSubIter = mySubs.begin();
208 for(; aSubIter != mySubs.end(); aSubIter++)
209 subDocument(*aSubIter)->abortOperation();
212 bool Model_Document::isOperation()
214 // operation is opened for all documents: no need to check subs
215 return myDoc->HasOpenCommand() == Standard_True ;
218 bool Model_Document::isModified()
220 // is modified if at least one operation was commited and not undoed
221 return myTransactionsAfterSave > 0;
224 bool Model_Document::canUndo()
226 if (myDoc->GetAvailableUndos() > 0 && myNestedStart != myTransactionsAfterSave)
228 // check other subs contains operation that can be undoed
229 set<string>::iterator aSubIter = mySubs.begin();
230 for(; aSubIter != mySubs.end(); aSubIter++)
231 if (subDocument(*aSubIter)->canUndo())
236 void Model_Document::undo()
238 myTransactionsAfterSave--;
239 if (!myIsEmptyTr[myTransactionsAfterSave])
241 synchronizeFeatures();
243 set<string>::iterator aSubIter = mySubs.begin();
244 for(; aSubIter != mySubs.end(); aSubIter++)
245 subDocument(*aSubIter)->undo();
248 bool Model_Document::canRedo()
250 if (myDoc->GetAvailableRedos() > 0)
252 // check other subs contains operation that can be redoed
253 set<string>::iterator aSubIter = mySubs.begin();
254 for(; aSubIter != mySubs.end(); aSubIter++)
255 if (subDocument(*aSubIter)->canRedo())
260 void Model_Document::redo()
262 if (!myIsEmptyTr[myTransactionsAfterSave])
264 myTransactionsAfterSave++;
265 synchronizeFeatures();
267 set<string>::iterator aSubIter = mySubs.begin();
268 for(; aSubIter != mySubs.end(); aSubIter++)
269 subDocument(*aSubIter)->redo();
272 boost::shared_ptr<ModelAPI_Feature> Model_Document::addFeature(string theID)
274 boost::shared_ptr<ModelAPI_Feature> aFeature =
275 ModelAPI_PluginManager::get()->createFeature(theID);
277 boost::dynamic_pointer_cast<Model_Document>(aFeature->documentToAdd())->addFeature(aFeature);
279 // TODO: generate error that feature is not created
284 /// Appenad to the array of references a new referenced label
285 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced) {
286 Handle(TDataStd_ReferenceArray) aRefs;
287 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
288 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
289 aRefs->SetValue(0, theReferenced);
290 } else { // extend array by one more element
291 Handle(TDataStd_HLabelArray1) aNewArray =
292 new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() + 1);
293 for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
294 aNewArray->SetValue(a, aRefs->Value(a));
296 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
297 aRefs->SetInternalArray(aNewArray);
301 void Model_Document::addFeature(const boost::shared_ptr<ModelAPI_Feature> theFeature)
303 if (theFeature->isAction()) return; // do not add action to the data model
305 boost::shared_ptr<ModelAPI_Document> aThis =
306 Model_Application::getApplication()->getDocument(myID);
307 TDF_Label aFeaturesLab = groupLabel(FEATURES_GROUP);
308 TDF_Label aFeatureLab = aFeaturesLab.NewChild();
310 // organize feature and data objects
311 boost::shared_ptr<Model_Data> aData(new Model_Data);
312 aData->setFeature(theFeature);
313 aData->setLabel(aFeatureLab);
314 theFeature->setDoc(aThis);
315 theFeature->setData(aData);
316 setUniqueName(theFeature);
317 theFeature->initAttributes();
319 // keep the feature ID to restore document later correctly
320 TDataStd_Comment::Set(aFeatureLab, theFeature->getKind().c_str());
321 myFeatures.push_back(theFeature);
322 // store feature in the history of features array
323 if (theFeature->isInHistory()) {
324 AddToRefArray(aFeaturesLab, aFeatureLab);
326 // add featue to the group
327 const std::string& aGroup = theFeature->getGroup();
328 TDF_Label aGroupLab = groupLabel(aGroup);
329 AddToRefArray(aGroupLab, aFeatureLab);
330 // new name of this feature object by default equal to name of feature
331 TDF_Label anObjLab = aGroupLab.NewChild();
332 TCollection_ExtendedString aName(theFeature->data()->getName().c_str());
333 TDataStd_Name::Set(anObjLab, aName);
334 TDF_Label aGrLabChild = aGroupLab.FindChild(1);
335 AddToRefArray(aGrLabChild, anObjLab); // reference to names is on the first sub
337 // event: feature is added
338 static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
339 Model_FeatureUpdatedMessage aMsg(theFeature, anEvent);
340 Events_Loop::loop()->send(aMsg);
343 /// Appenad to the array of references a new referenced label.
344 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
345 /// \returns the index of removed element
346 static int RemoveFromRefArray(
347 TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex = -1) {
348 int aResult = -1; // no returned
349 Handle(TDataStd_ReferenceArray) aRefs;
350 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
351 if (aRefs->Length() == 1) { // just erase an array
352 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0)
353 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
355 } else { // reduce the array
356 Handle(TDataStd_HLabelArray1) aNewArray =
357 new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() - 1);
358 int aCount = aRefs->Lower();
359 for(int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
360 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
364 aNewArray->SetValue(aCount, aRefs->Value(a));
367 aRefs->SetInternalArray(aNewArray);
373 void Model_Document::removeFeature(boost::shared_ptr<ModelAPI_Feature> theFeature)
375 boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
376 TDF_Label aFeatureLabel = aData->label();
378 TDF_Label aGroupLabel = groupLabel(theFeature->getGroup());
379 int aRemovedIndex = RemoveFromRefArray(aGroupLabel, aFeatureLabel);
380 RemoveFromRefArray(aGroupLabel.FindChild(1), TDF_Label(), aRemovedIndex);
381 // remove feature from the myFeatures list
382 std::vector<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = myFeatures.begin();
383 while(aFIter != myFeatures.end()) {
384 if (*aFIter == theFeature) {
385 aFIter = myFeatures.erase(aFIter);
390 // erase all attributes under the label of feature
391 aFeatureLabel.ForgetAllAttributes();
392 // remove it from the references array
393 RemoveFromRefArray(groupLabel(FEATURES_GROUP), aData->label());
395 // event: feature is added
396 Model_FeatureDeletedMessage aMsg(theFeature->document(), theFeature->getGroup());
397 Events_Loop::loop()->send(aMsg);
400 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
402 // iterate all features, may be optimized later by keeping labels-map
403 vector<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = myFeatures.begin();
404 for(; aFIter != myFeatures.end(); aFIter++) {
405 boost::shared_ptr<Model_Data> aData =
406 boost::dynamic_pointer_cast<Model_Data>((*aFIter)->data());
407 if (aData->label().IsEqual(theLabel))
410 return boost::shared_ptr<ModelAPI_Feature>(); // not found
413 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
415 // just store sub-document identifier here to manage it later
416 if (mySubs.find(theDocID) == mySubs.end())
417 mySubs.insert(theDocID);
418 return Model_Application::getApplication()->getDocument(theDocID);
421 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
422 const string& theGroupID, const int theIndex, const bool isOperation)
424 TDF_Label aGroupLab = groupLabel(theGroupID);
425 Handle(TDataStd_ReferenceArray) aRefs;
426 if (aGroupLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
427 if (aRefs->Lower() <= theIndex && aRefs->Upper() >= theIndex) {
428 TDF_Label aFeatureLab = aRefs->Value(theIndex);
429 boost::shared_ptr<ModelAPI_Feature> aFeature = feature(aFeatureLab);
431 if (theGroupID == FEATURES_GROUP || isOperation) { // just returns the feature from the history
433 } else { // create a new object from the group to return it
434 Handle(TDataStd_Name) aName; // name of the object
435 if (aGroupLab.FindChild(1).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
436 aRefs->Value(theIndex).FindAttribute(TDataStd_Name::GetID(), aName);
437 boost::shared_ptr<Model_Object> anObj(new Model_Object(aFeature, aName));
444 return boost::shared_ptr<ModelAPI_Feature>();
447 int Model_Document::size(const string& theGroupID)
449 Handle(TDataStd_ReferenceArray) aRefs;
450 if (groupLabel(theGroupID).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
451 return aRefs->Length();
452 // group is not found
456 Model_Document::Model_Document(const std::string theID)
457 : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
459 myDoc->SetUndoLimit(UNDO_LIMIT);
460 myTransactionsAfterSave = 0;
462 myDoc->SetNestedTransactionMode();
463 // to have something in the document and avoid empty doc open/save problem
464 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
467 TDF_Label Model_Document::groupLabel(const string theGroup)
469 // searching for existing
470 TCollection_ExtendedString aGroup(theGroup.c_str());
471 TDF_ChildIDIterator aGroupIter(myDoc->Main().FindChild(TAG_OBJECTS), TDataStd_Comment::GetID());
472 for(; aGroupIter.More(); aGroupIter.Next()) {
473 Handle(TDataStd_Comment) aName = Handle(TDataStd_Comment)::DownCast(aGroupIter.Value());
474 if (aName->Get() == aGroup)
475 return aGroupIter.Value()->Label();
478 TDF_Label aNew = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
479 TDataStd_Comment::Set(aNew, aGroup);
483 void Model_Document::setUniqueName(boost::shared_ptr<ModelAPI_Feature> theFeature)
485 string aName; // result
486 // iterate all features but also iterate group of this feature if object is not in history
487 list<string> aGroups;
488 aGroups.push_back(FEATURES_GROUP);
489 if (!theFeature->isInHistory()) {
490 aGroups.push_back(theFeature->getGroup());
492 for(list<string>::iterator aGIter = aGroups.begin(); aGIter != aGroups.end(); aGIter++) {
493 // first count all objects of such kind to start with index = count + 1
494 int a, aNumObjects = 0;
495 int aSize = size(*aGIter);
496 for(a = 0; a < aSize; a++) {
497 if (feature(*aGIter, a)->getKind() == theFeature->getKind())
500 // generate candidate name
501 stringstream aNameStream;
502 aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
503 aName = aNameStream.str();
504 // check this is unique, if not, increase index by 1
505 for(a = 0; a < aSize;) {
506 if (feature(*aGIter, a, true)->data()->getName() == aName) {
508 stringstream aNameStream;
509 aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
510 aName = aNameStream.str();
511 // reinitialize iterator to make sure a new name is unique
516 theFeature->data()->setName(aName);
519 //! Returns the object by the feature
520 boost::shared_ptr<ModelAPI_Feature> Model_Document::objectByFeature(
521 const boost::shared_ptr<ModelAPI_Feature> theFeature)
523 for(int a = 0; a < size(theFeature->getGroup()); a++) {
524 boost::shared_ptr<Model_Object> anObj =
525 boost::dynamic_pointer_cast<Model_Object>(feature(theFeature->getGroup(), a));
530 return boost::shared_ptr<ModelAPI_Feature>(); // not found
533 void Model_Document::synchronizeFeatures()
535 boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(myID);
537 vector<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = myFeatures.begin();
538 // and in parallel iterate labels of features
539 TDF_ChildIDIterator aFLabIter(groupLabel(FEATURES_GROUP), TDataStd_Comment::GetID());
540 while(aFIter != myFeatures.end() || aFLabIter.More()) {
541 static const int INFINITE_TAG = INT_MAX; // no label means that it exists somwhere in infinite
542 int aFeatureTag = INFINITE_TAG;
543 if (aFIter != myFeatures.end()) { // existing tag for feature
544 boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>((*aFIter)->data());
545 aFeatureTag = aData->label().Tag();
547 int aDSTag = INFINITE_TAG;
548 if (aFLabIter.More()) { // next label in DS is existing
549 aDSTag = aFLabIter.Value()->Label().Tag();
551 if (aDSTag > aFeatureTag) { // feature is removed
552 Model_FeatureDeletedMessage aMsg1(aThis, FEATURES_GROUP);
553 Model_FeatureDeletedMessage aMsg2(aThis, (*aFIter)->getGroup());
554 aFIter = myFeatures.erase(aFIter);
555 // event: model is updated
556 Events_Loop::loop()->send(aMsg1);
557 Events_Loop::loop()->send(aMsg2);
558 } else if (aDSTag < aFeatureTag) { // a new feature is inserted
560 boost::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
561 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
562 aFLabIter.Value())->Get()).ToCString());
564 if (aFIter == myFeatures.end()) { // must be before "setData" to redo the sketch line correctly
565 myFeatures.push_back(aFeature);
566 aFIter = myFeatures.end();
569 myFeatures.insert(aFIter, aFeature);
571 boost::shared_ptr<Model_Data> aData(new Model_Data);
572 TDF_Label aLab = aFLabIter.Value()->Label();
573 aData->setLabel(aLab);
574 aData->setFeature(aFeature);
575 aFeature->setDoc(aThis);
576 aFeature->setData(aData);
577 aFeature->initAttributes();
579 // event: model is updated
580 static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
581 Model_FeatureUpdatedMessage aMsg1(aFeature, anEvent);
582 Events_Loop::loop()->send(aMsg1);
583 boost::shared_ptr<ModelAPI_Feature> anObj = objectByFeature(aFeature);
585 Model_FeatureUpdatedMessage aMsg2(anObj, anEvent);
586 Events_Loop::loop()->send(aMsg2);
589 // feature for this label is added, so go to the next label
591 } else { // nothing is changed, both iterators are incremented
596 // after all updates, sends a message that groups of features were created or updated
597 boost::static_pointer_cast<Model_PluginManager>(Model_PluginManager::get())->
598 setCheckTransactions(false);
599 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_CREATED));
600 Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_FEATURE_DELETED));
601 boost::static_pointer_cast<Model_PluginManager>(Model_PluginManager::get())->
602 setCheckTransactions(true);