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_Application.h>
9 #include <Model_PluginManager.h>
10 #include <Model_Events.h>
11 #include <Events_Loop.h>
12 #include <Events_Error.h>
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>
23 # define _separator_ '\\'
25 # define _separator_ '/'
28 static const int UNDO_LIMIT = 10; // number of possible undo operations
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)
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)
39 TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
41 aPath += theID.c_str();
42 aPath += ".cbf"; // standard binary file extension
46 bool Model_Document::load(const char* theFileName)
48 Handle(Model_Application) anApp = Model_Application::getApplication();
49 if (this == Model_PluginManager::get()->rootDocument().get()) {
50 anApp->setLoadPath(theFileName);
52 TCollection_ExtendedString aPath (DocFileName(theFileName, myID));
53 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
56 aStatus = anApp->Open(aPath, myDoc);
58 catch (Standard_Failure)
60 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
61 Events_Error::send(string("Exception in opening of document: ") + aFail->GetMessageString());
64 bool isError = aStatus != PCDM_RS_OK;
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;
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;
100 Events_Error::send(string("Can not open document: unknown error")); break;
104 myDoc->SetUndoLimit(UNDO_LIMIT);
105 synchronizeFeatures();
110 bool Model_Document::save(const char* theFileName)
112 // create a directory in the root document if it is not yet exist
113 if (this == Model_PluginManager::get()->rootDocument().get()) {
115 CreateDirectory(theFileName, NULL);
117 mkdir(theFileName, 0x1ff);
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;
124 aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
126 catch (Standard_Failure) {
127 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
128 Events_Error::send(string("Exception in saving of document: ") + aFail->GetMessageString());
131 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
136 case PCDM_SS_DriverFailure:
137 Events_Error::send(string("Can not save document: PCDM_SS_DriverFailure"));
139 case PCDM_SS_WriteFailure:
140 Events_Error::send(string("Can not save document: PCDM_SS_WriteFailure"));
142 case PCDM_SS_Failure:
144 Events_Error::send(string("Can not save document: PCDM_SS_Failure"));
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);
157 void Model_Document::close()
160 set<string>::iterator aSubIter = mySubs.begin();
161 for(; aSubIter != mySubs.end(); aSubIter++)
162 subDocument(*aSubIter)->close();
166 Model_Application::getApplication()->deleteDocument(myID);
169 void Model_Document::startOperation()
171 // check is it nested or not
172 if (myDoc->HasOpenCommand()) {
175 // new command for this
177 // new command for all subs
178 set<string>::iterator aSubIter = mySubs.begin();
179 for(; aSubIter != mySubs.end(); aSubIter++)
180 subDocument(*aSubIter)->startOperation();
183 void Model_Document::finishOperation()
185 // returns false if delta is empty and no transaction was made
186 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();
187 myTransactionsAfterSave++;
189 // finish for all subs
190 set<string>::iterator aSubIter = mySubs.begin();
191 for(; aSubIter != mySubs.end(); aSubIter++)
192 subDocument(*aSubIter)->finishOperation();
195 void Model_Document::abortOperation()
197 myDoc->AbortCommand();
198 // abort for all subs
199 set<string>::iterator aSubIter = mySubs.begin();
200 for(; aSubIter != mySubs.end(); aSubIter++)
201 subDocument(*aSubIter)->abortOperation();
204 bool Model_Document::isOperation()
206 // operation is opened for all documents: no need to check subs
207 return myDoc->HasOpenCommand() == Standard_True ;
210 bool Model_Document::isModified()
212 // is modified if at least one operation was commited and not undoed
213 return myTransactionsAfterSave > 0;
216 bool Model_Document::canUndo()
218 if (myDoc->GetAvailableUndos() > 0)
220 // check other subs contains operation that can be undoed
221 set<string>::iterator aSubIter = mySubs.begin();
222 for(; aSubIter != mySubs.end(); aSubIter++)
223 if (subDocument(*aSubIter)->canUndo())
228 void Model_Document::undo()
230 myTransactionsAfterSave--;
231 if (!myIsEmptyTr[myTransactionsAfterSave])
233 synchronizeFeatures();
235 set<string>::iterator aSubIter = mySubs.begin();
236 for(; aSubIter != mySubs.end(); aSubIter++)
237 subDocument(*aSubIter)->undo();
240 bool Model_Document::canRedo()
242 if (myDoc->GetAvailableRedos() > 0)
244 // check other subs contains operation that can be redoed
245 set<string>::iterator aSubIter = mySubs.begin();
246 for(; aSubIter != mySubs.end(); aSubIter++)
247 if (subDocument(*aSubIter)->canRedo())
252 void Model_Document::redo()
254 if (!myIsEmptyTr[myTransactionsAfterSave])
256 myTransactionsAfterSave++;
257 synchronizeFeatures();
259 set<string>::iterator aSubIter = mySubs.begin();
260 for(; aSubIter != mySubs.end(); aSubIter++)
261 subDocument(*aSubIter)->redo();
264 boost::shared_ptr<ModelAPI_Feature> Model_Document::addFeature(string theID)
266 boost::shared_ptr<ModelAPI_Feature> aFeature =
267 ModelAPI_PluginManager::get()->createFeature(theID);
269 boost::dynamic_pointer_cast<Model_Document>(aFeature->documentToAdd())->addFeature(aFeature);
271 // TODO: generate error that feature is not created
276 void Model_Document::addFeature(const boost::shared_ptr<ModelAPI_Feature> theFeature)
278 const std::string& aGroup = theFeature->getGroup();
279 TDF_Label aGroupLab = groupLabel(aGroup);
280 TDF_Label anObjLab = aGroupLab.NewChild();
281 boost::shared_ptr<Model_Data> aData(new Model_Data);
282 aData->setFeature(theFeature);
283 aData->setLabel(anObjLab);
284 boost::shared_ptr<ModelAPI_Document> aThis =
285 Model_Application::getApplication()->getDocument(myID);
286 theFeature->setData(aData);
287 theFeature->setDoc(aThis);
288 setUniqueName(theFeature);
289 theFeature->initAttributes();
290 // keep the feature ID to restore document later correctly
291 TDataStd_Comment::Set(anObjLab, theFeature->getKind().c_str());
292 // put index of the feature in the group in the tree
293 TDataStd_Integer::Set(anObjLab, myFeatures[aGroup].size());
294 myFeatures[aGroup].push_back(theFeature);
295 // store feature in the history of features array
296 if (theFeature->isInHistory()) {
297 Handle(TDataStd_ReferenceArray) aRefs;
298 if (!groupLabel(FEATURES_GROUP).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
299 aRefs = TDataStd_ReferenceArray::Set(groupLabel(FEATURES_GROUP), 0, 0);
300 aRefs->SetValue(0, anObjLab);
301 } else { // extend array by one more element
302 Handle(TDataStd_HLabelArray1) aNewArray =
303 new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() + 1);
304 for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
305 aNewArray->SetValue(a, aRefs->Value(a));
307 aNewArray->SetValue(aRefs->Upper() + 1, anObjLab);
308 aRefs->SetInternalArray(aNewArray);
312 // event: feature is added
313 static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
314 Model_FeatureUpdatedMessage aMsg(theFeature, anEvent);
315 Events_Loop::loop()->send(aMsg);
318 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
320 Handle(TDataStd_Integer) aFeatureIndex;
321 if (theLabel.FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
322 Handle(TDataStd_Comment) aGroupID;
323 if (theLabel.Father().FindAttribute(TDataStd_Comment::GetID(), aGroupID)) {
324 string aGroup = TCollection_AsciiString(aGroupID->Get()).ToCString();
325 return myFeatures[aGroup][aFeatureIndex->Get()];
328 return boost::shared_ptr<ModelAPI_Feature>(); // not found
331 int Model_Document::featureIndex(boost::shared_ptr<ModelAPI_Feature> theFeature)
333 if (theFeature->document().get() != this) {
334 return theFeature->document()->featureIndex(theFeature);
336 boost::shared_ptr<Model_Data> aData =
337 boost::dynamic_pointer_cast<Model_Data>(theFeature->data());
338 Handle(TDataStd_Integer) aFeatureIndex;
339 if (aData->label().FindAttribute(TDataStd_Integer::GetID(), aFeatureIndex)) {
340 return aFeatureIndex->Get();
342 return -1; // not found
345 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
347 // just store sub-document identifier here to manage it later
348 if (mySubs.find(theDocID) == mySubs.end())
349 mySubs.insert(theDocID);
350 return Model_Application::getApplication()->getDocument(theDocID);
353 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
354 const string& theGroupID, const int theIndex)
356 if (theGroupID == FEATURES_GROUP) { // history is just a references array
357 Handle(TDataStd_ReferenceArray) aRefs;
358 if (groupLabel(FEATURES_GROUP).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
359 if (aRefs->Lower() <= theIndex && aRefs->Upper() >= theIndex) {
360 TDF_Label aFeatureLab = aRefs->Value(theIndex);
361 return feature(aFeatureLab);
364 } else { // one of the group
365 map<string, vector<boost::shared_ptr<ModelAPI_Feature> > >::iterator aGroup =
366 myFeatures.find(theGroupID);
367 if (aGroup != myFeatures.end() && (int)(aGroup->second.size()) > theIndex) {
368 return aGroup->second[theIndex];
372 return boost::shared_ptr<ModelAPI_Feature>();
375 int Model_Document::size(const string& theGroupID)
377 if (theGroupID == FEATURES_GROUP) { // history is just a references array
378 Handle(TDataStd_ReferenceArray) aRefs;
379 if (groupLabel(FEATURES_GROUP).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
380 return aRefs->Length();
381 } else { // one of the group
382 map<string, vector<boost::shared_ptr<ModelAPI_Feature> > >::iterator aGroup =
383 myFeatures.find(theGroupID);
384 if (aGroup != myFeatures.end())
385 return aGroup->second.size();
387 // group is not found
391 const vector<string>& Model_Document::getGroups() const
393 return myGroupsNames;
396 Model_Document::Model_Document(const std::string theID)
397 : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
399 myDoc->SetUndoLimit(UNDO_LIMIT);
400 myTransactionsAfterSave = 0;
402 myDoc->SetNestedTransactionMode();
403 // to have something in the document and avoid empty doc open/save problem
404 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
407 TDF_Label Model_Document::groupLabel(const string theGroup)
409 if (myGroups.find(theGroup) == myGroups.end()) {
410 myGroups[theGroup] = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
411 myGroupsNames.push_back(theGroup);
412 // set to the group label the group idntifier to restore on "open"
413 TDataStd_Comment::Set(myGroups[theGroup], theGroup.c_str());
414 myFeatures[theGroup] = vector<boost::shared_ptr<ModelAPI_Feature> >();
416 return myGroups[theGroup];
419 void Model_Document::setUniqueName(boost::shared_ptr<ModelAPI_Feature> theFeature)
421 // first count all objects of such kind to start with index = count + 1
422 int a, aNumObjects = 0;
423 int aSize = size(theFeature->getGroup());
424 for(a = 0; a < aSize; a++) {
425 if (feature(theFeature->getGroup(), a)->getKind() == theFeature->getKind())
428 // generate candidate name
429 stringstream aNameStream;
430 aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
431 string aName = aNameStream.str();
432 // check this is unique, if not, increase index by 1
433 for(a = 0; a < aSize;) {
434 if (feature(theFeature->getGroup(), a)->data()->getName() == aName) {
436 stringstream aNameStream;
437 aNameStream<<theFeature->getKind()<<"_"<<aNumObjects + 1;
438 // reinitialize iterator to make sure a new name is unique
443 theFeature->data()->setName(aName);
446 void Model_Document::synchronizeFeatures()
448 boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(myID);
449 // iterate groups labels
450 TDF_ChildIDIterator aGroupsIter(myDoc->Main().FindChild(TAG_OBJECTS),
451 TDataStd_Comment::GetID(), Standard_False);
452 vector<string>::iterator aGroupNamesIter = myGroupsNames.begin();
453 for(; aGroupsIter.More() && aGroupNamesIter != myGroupsNames.end();
454 aGroupsIter.Next(), aGroupNamesIter++) {
455 string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
456 aGroupsIter.Value())->Get()).ToCString();
457 if (*aGroupNamesIter != aGroupName)
458 break; // all since there is a change this must be recreated from scratch
460 // delete all groups left after the data model groups iteration
461 while(aGroupNamesIter != myGroupsNames.end()) {
462 string aGroupName = *aGroupNamesIter;
463 myFeatures.erase(aGroupName);
464 myGroups.erase(aGroupName);
465 aGroupNamesIter = myGroupsNames.erase(aGroupNamesIter);
466 // say that features were deleted from group
467 Model_FeatureDeletedMessage aMsg(aThis, aGroupName);
468 Events_Loop::loop()->send(aMsg);
470 // create new groups basing on the following data model update
471 for(; aGroupsIter.More(); aGroupsIter.Next()) {
472 string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
473 aGroupsIter.Value())->Get()).ToCString();
474 myGroupsNames.push_back(aGroupName);
475 myGroups[aGroupName] = aGroupsIter.Value()->Label();
476 myFeatures[aGroupName] = vector<boost::shared_ptr<ModelAPI_Feature> >();
478 // update features group by group
479 aGroupsIter.Initialize(myDoc->Main().FindChild(TAG_OBJECTS),
480 TDataStd_Comment::GetID(), Standard_False);
481 for(; aGroupsIter.More(); aGroupsIter.Next()) {
482 string aGroupName = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
483 aGroupsIter.Value())->Get()).ToCString();
484 // iterate features in internal container
485 vector<boost::shared_ptr<ModelAPI_Feature> >& aFeatures = myFeatures[aGroupName];
486 vector<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = aFeatures.begin();
487 // and in parallel iterate labels of features
488 TDF_ChildIDIterator aFLabIter(
489 aGroupsIter.Value()->Label(), TDataStd_Comment::GetID(), Standard_False);
490 while(aFIter != aFeatures.end() || aFLabIter.More()) {
491 static const int INFINITE_TAG = INT_MAX; // no label means that it exists somwhere in infinite
492 int aFeatureTag = INFINITE_TAG;
493 if (aFIter != aFeatures.end()) { // existing tag for feature
494 boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>((*aFIter)->data());
495 aFeatureTag = aData->label().Tag();
497 int aDSTag = INFINITE_TAG;
498 if (aFLabIter.More()) { // next label in DS is existing
499 aDSTag = aFLabIter.Value()->Label().Tag();
501 if (aDSTag > aFeatureTag) { // feature is removed
502 aFIter = aFeatures.erase(aFIter);
503 // event: model is updated
504 Model_FeatureDeletedMessage aMsg(aThis, aGroupName);
505 Events_Loop::loop()->send(aMsg);
506 } else if (aDSTag < aFeatureTag) { // a new feature is inserted
508 boost::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
509 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
510 aFLabIter.Value())->Get()).ToCString());
512 boost::shared_ptr<Model_Data> aData(new Model_Data);
513 TDF_Label aLab = aFLabIter.Value()->Label();
514 aData->setLabel(aLab);
515 aData->setFeature(aFeature);
516 aFeature->setDoc(aThis);
517 aFeature->setData(aData);
518 aFeature->initAttributes();
520 if (aFIter == aFeatures.end()) {
521 aFeatures.push_back(aFeature);
522 aFIter = aFeatures.end();
525 aFeatures.insert(aFIter, aFeature);
527 // event: model is updated
528 static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
529 Model_FeatureUpdatedMessage aMsg(aFeature, anEvent);
530 Events_Loop::loop()->send(aMsg);
532 // feature for this label is added, so go to the next label
534 } else { // nothing is changed, both iterators are incremented