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>
25 # define _separator_ '\\'
27 # define _separator_ '/'
30 static const int UNDO_LIMIT = 10; // number of possible undo operations
32 static const int TAG_GENERAL = 1; // general properties tag
33 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree (features)
34 static const int TAG_HISTORY = 3; // tag of the history sub-tree (python dump)
38 /// Returns the file name of this document by the nameof directory and identifuer of a document
39 static TCollection_ExtendedString DocFileName(const char* theFileName, const string& theID)
41 TCollection_ExtendedString aPath ((const Standard_CString)theFileName);
43 aPath += theID.c_str();
44 aPath += ".cbf"; // standard binary file extension
48 bool Model_Document::load(const char* theFileName)
50 Handle(Model_Application) anApp = Model_Application::getApplication();
51 if (this == Model_PluginManager::get()->rootDocument().get()) {
52 anApp->setLoadPath(theFileName);
54 TCollection_ExtendedString aPath (DocFileName(theFileName, myID));
55 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
58 aStatus = anApp->Open(aPath, myDoc);
60 catch (Standard_Failure)
62 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
63 Events_Error::send(string("Exception in opening of document: ") + aFail->GetMessageString());
66 bool isError = aStatus != PCDM_RS_OK;
71 case PCDM_RS_UnknownDocument:
72 Events_Error::send(string("Can not open document: PCDM_RS_UnknownDocument")); break;
73 case PCDM_RS_AlreadyRetrieved:
74 Events_Error::send(string("Can not open document: PCDM_RS_AlreadyRetrieved")); break;
75 case PCDM_RS_AlreadyRetrievedAndModified:
76 Events_Error::send(string("Can not open document: PCDM_RS_AlreadyRetrievedAndModified")); break;
77 case PCDM_RS_NoDriver:
78 Events_Error::send(string("Can not open document: PCDM_RS_NoDriver")); break;
79 case PCDM_RS_UnknownFileDriver:
80 Events_Error::send(string("Can not open document: PCDM_RS_UnknownFileDriver")); break;
81 case PCDM_RS_OpenError:
82 Events_Error::send(string("Can not open document: PCDM_RS_OpenError")); break;
83 case PCDM_RS_NoVersion:
84 Events_Error::send(string("Can not open document: PCDM_RS_NoVersion")); break;
86 Events_Error::send(string("Can not open document: PCDM_RS_NoModel")); break;
87 case PCDM_RS_NoDocument:
88 Events_Error::send(string("Can not open document: PCDM_RS_NoDocument")); break;
89 case PCDM_RS_FormatFailure:
90 Events_Error::send(string("Can not open document: PCDM_RS_FormatFailure")); break;
91 case PCDM_RS_TypeNotFoundInSchema:
92 Events_Error::send(string("Can not open document: PCDM_RS_TypeNotFoundInSchema")); break;
93 case PCDM_RS_UnrecognizedFileFormat:
94 Events_Error::send(string("Can not open document: PCDM_RS_UnrecognizedFileFormat")); break;
95 case PCDM_RS_MakeFailure:
96 Events_Error::send(string("Can not open document: PCDM_RS_MakeFailure")); break;
97 case PCDM_RS_PermissionDenied:
98 Events_Error::send(string("Can not open document: PCDM_RS_PermissionDenied")); break;
99 case PCDM_RS_DriverFailure:
100 Events_Error::send(string("Can not open document: PCDM_RS_DriverFailure")); break;
102 Events_Error::send(string("Can not open document: unknown error")); break;
106 myDoc->SetUndoLimit(UNDO_LIMIT);
107 synchronizeFeatures();
112 bool Model_Document::save(const char* theFileName)
114 // create a directory in the root document if it is not yet exist
115 if (this == Model_PluginManager::get()->rootDocument().get()) {
117 CreateDirectory(theFileName, NULL);
119 mkdir(theFileName, 0x1ff);
122 // filename in the dir is id of document inside of the given directory
123 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
124 PCDM_StoreStatus aStatus;
126 aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
128 catch (Standard_Failure) {
129 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
130 Events_Error::send(string("Exception in saving of document: ") + aFail->GetMessageString());
133 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
138 case PCDM_SS_DriverFailure:
139 Events_Error::send(string("Can not save document: PCDM_SS_DriverFailure"));
141 case PCDM_SS_WriteFailure:
142 Events_Error::send(string("Can not save document: PCDM_SS_WriteFailure"));
144 case PCDM_SS_Failure:
146 Events_Error::send(string("Can not save document: PCDM_SS_Failure"));
150 myTransactionsAfterSave = 0;
151 if (isDone) { // save also sub-documents if any
152 set<string>::iterator aSubIter = mySubs.begin();
153 for(; aSubIter != mySubs.end() && isDone; aSubIter++)
154 isDone = subDocument(*aSubIter)->save(theFileName);
159 void Model_Document::close()
162 set<string>::iterator aSubIter = mySubs.begin();
163 for(; aSubIter != mySubs.end(); aSubIter++)
164 subDocument(*aSubIter)->close();
168 Model_Application::getApplication()->deleteDocument(myID);
171 void Model_Document::startOperation()
173 // check is it nested or not
174 if (myDoc->HasOpenCommand()) {
175 myNestedStart = myTransactionsAfterSave;
177 // new command for this
179 // new command for all subs
180 set<string>::iterator aSubIter = mySubs.begin();
181 for(; aSubIter != mySubs.end(); aSubIter++)
182 subDocument(*aSubIter)->startOperation();
185 void Model_Document::finishOperation()
187 if (myNestedStart > myTransactionsAfterSave) // this nested transaction is owervritten
189 // returns false if delta is empty and no transaction was made
190 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();
191 myTransactionsAfterSave++;
192 // finish for all subs
193 set<string>::iterator aSubIter = mySubs.begin();
194 for(; aSubIter != mySubs.end(); aSubIter++)
195 subDocument(*aSubIter)->finishOperation();
198 void Model_Document::abortOperation()
200 myDoc->AbortCommand();
201 synchronizeFeatures();
202 // abort for all subs
203 set<string>::iterator aSubIter = mySubs.begin();
204 for(; aSubIter != mySubs.end(); aSubIter++)
205 subDocument(*aSubIter)->abortOperation();
208 bool Model_Document::isOperation()
210 // operation is opened for all documents: no need to check subs
211 return myDoc->HasOpenCommand() == Standard_True ;
214 bool Model_Document::isModified()
216 // is modified if at least one operation was commited and not undoed
217 return myTransactionsAfterSave > 0;
220 bool Model_Document::canUndo()
222 if (myDoc->GetAvailableUndos() > 0 && myNestedStart != myTransactionsAfterSave)
224 // check other subs contains operation that can be undoed
225 set<string>::iterator aSubIter = mySubs.begin();
226 for(; aSubIter != mySubs.end(); aSubIter++)
227 if (subDocument(*aSubIter)->canUndo())
232 void Model_Document::undo()
234 myTransactionsAfterSave--;
235 if (!myIsEmptyTr[myTransactionsAfterSave])
237 synchronizeFeatures();
239 set<string>::iterator aSubIter = mySubs.begin();
240 for(; aSubIter != mySubs.end(); aSubIter++)
241 subDocument(*aSubIter)->undo();
244 bool Model_Document::canRedo()
246 if (myDoc->GetAvailableRedos() > 0)
248 // check other subs contains operation that can be redoed
249 set<string>::iterator aSubIter = mySubs.begin();
250 for(; aSubIter != mySubs.end(); aSubIter++)
251 if (subDocument(*aSubIter)->canRedo())
256 void Model_Document::redo()
258 if (!myIsEmptyTr[myTransactionsAfterSave])
260 myTransactionsAfterSave++;
261 synchronizeFeatures();
263 set<string>::iterator aSubIter = mySubs.begin();
264 for(; aSubIter != mySubs.end(); aSubIter++)
265 subDocument(*aSubIter)->redo();
268 boost::shared_ptr<ModelAPI_Feature> Model_Document::addFeature(string theID)
270 boost::shared_ptr<ModelAPI_Feature> aFeature =
271 ModelAPI_PluginManager::get()->createFeature(theID);
273 boost::dynamic_pointer_cast<Model_Document>(aFeature->documentToAdd())->addFeature(aFeature);
275 // TODO: generate error that feature is not created
280 /// Appenad to the array of references a new referenced label
281 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced) {
282 Handle(TDataStd_ReferenceArray) aRefs;
283 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
284 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
285 aRefs->SetValue(0, theReferenced);
286 } else { // extend array by one more element
287 Handle(TDataStd_HLabelArray1) aNewArray =
288 new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper() + 1);
289 for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
290 aNewArray->SetValue(a, aRefs->Value(a));
292 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
293 aRefs->SetInternalArray(aNewArray);
297 void Model_Document::addFeature(const boost::shared_ptr<ModelAPI_Feature> theFeature)
299 boost::shared_ptr<ModelAPI_Document> aThis =
300 Model_Application::getApplication()->getDocument(myID);
301 TDF_Label aFeaturesLab = groupLabel(FEATURES_GROUP);
302 TDF_Label aFeatureLab = aFeaturesLab.NewChild();
304 // organize feature and data objects
305 boost::shared_ptr<Model_Data> aData(new Model_Data);
306 aData->setFeature(theFeature);
307 aData->setLabel(aFeatureLab);
308 theFeature->setDoc(aThis);
309 theFeature->setData(aData);
310 setUniqueName(theFeature);
311 theFeature->initAttributes();
313 // keep the feature ID to restore document later correctly
314 TDataStd_Comment::Set(aFeatureLab, theFeature->getKind().c_str());
315 myFeatures.push_back(theFeature);
316 // store feature in the history of features array
317 if (theFeature->isInHistory()) {
318 AddToRefArray(aFeaturesLab, aFeatureLab);
320 // add featue to the group
321 const std::string& aGroup = theFeature->getGroup();
322 TDF_Label aGroupLab = groupLabel(aGroup);
323 AddToRefArray(aGroupLab, aFeatureLab);
324 // new name of this feature object by default equal to name of feature
325 TDF_Label anObjLab = aGroupLab.NewChild();
326 TCollection_ExtendedString aName(theFeature->data()->getName().c_str());
327 TDataStd_Name::Set(anObjLab, aName);
328 AddToRefArray(aGroupLab.FindChild(1), anObjLab); // reference to names is on the first sub
330 // event: feature is added
331 static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
332 Model_FeatureUpdatedMessage aMsg(theFeature, anEvent);
333 Events_Loop::loop()->send(aMsg);
336 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(TDF_Label& theLabel)
338 // iterate all features, may be optimized later by keeping labels-map
339 vector<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = myFeatures.begin();
340 for(; aFIter != myFeatures.end(); aFIter++) {
341 boost::shared_ptr<Model_Data> aData =
342 boost::dynamic_pointer_cast<Model_Data>((*aFIter)->data());
343 if (aData->label().IsEqual(theLabel))
346 return boost::shared_ptr<ModelAPI_Feature>(); // not found
349 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(string theDocID)
351 // just store sub-document identifier here to manage it later
352 if (mySubs.find(theDocID) == mySubs.end())
353 mySubs.insert(theDocID);
354 return Model_Application::getApplication()->getDocument(theDocID);
357 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
358 const string& theGroupID, const int theIndex)
360 TDF_Label aGroupLab = groupLabel(theGroupID);
361 Handle(TDataStd_ReferenceArray) aRefs;
362 if (aGroupLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
363 if (aRefs->Lower() <= theIndex && aRefs->Upper() >= theIndex) {
364 TDF_Label aFeatureLab = aRefs->Value(theIndex);
365 boost::shared_ptr<ModelAPI_Feature> aFeature = feature(aFeatureLab);
367 if (theGroupID == FEATURES_GROUP) { // just returns the feature from the history
369 } else { // create a new object from the group to return it
370 Handle(TDataStd_Name) aName; // name of the object
371 if (aGroupLab.FindChild(1).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
372 aRefs->Value(theIndex).FindAttribute(TDataStd_Name::GetID(), aName);
373 boost::shared_ptr<Model_Object> anObj(new Model_Object(aFeature, aName));
380 return boost::shared_ptr<ModelAPI_Feature>();
383 int Model_Document::size(const string& theGroupID)
385 Handle(TDataStd_ReferenceArray) aRefs;
386 if (groupLabel(theGroupID).FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
387 return aRefs->Length();
388 // group is not found
392 Model_Document::Model_Document(const std::string theID)
393 : myID(theID), myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
395 myDoc->SetUndoLimit(UNDO_LIMIT);
396 myTransactionsAfterSave = 0;
398 myDoc->SetNestedTransactionMode();
399 // to have something in the document and avoid empty doc open/save problem
400 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
403 TDF_Label Model_Document::groupLabel(const string theGroup)
405 // searching for existing
406 TCollection_ExtendedString aGroup(theGroup.c_str());
407 TDF_ChildIDIterator aGroupIter(myDoc->Main().FindChild(TAG_OBJECTS), TDataStd_Comment::GetID());
408 for(; aGroupIter.More(); aGroupIter.Next()) {
409 Handle(TDataStd_Comment) aName = Handle(TDataStd_Comment)::DownCast(aGroupIter.Value());
410 if (aName->Get() == aGroup)
411 return aGroupIter.Value()->Label();
414 TDF_Label aNew = myDoc->Main().FindChild(TAG_OBJECTS).NewChild();
415 TDataStd_Comment::Set(aNew, aGroup);
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(FEATURES_GROUP);
424 for(a = 0; a < aSize; a++) {
425 if (feature(FEATURES_GROUP, 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(FEATURES_GROUP, 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 //! Returns the object by the feature
447 boost::shared_ptr<ModelAPI_Feature> Model_Document::objectByFeature(
448 const boost::shared_ptr<ModelAPI_Feature> theFeature)
450 for(int a = 0; a < size(theFeature->getGroup()); a++) {
451 boost::shared_ptr<Model_Object> anObj =
452 boost::dynamic_pointer_cast<Model_Object>(feature(theFeature->getGroup(), a));
457 return boost::shared_ptr<ModelAPI_Feature>(); // not found
460 void Model_Document::synchronizeFeatures()
462 boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(myID);
464 vector<boost::shared_ptr<ModelAPI_Feature> >::iterator aFIter = myFeatures.begin();
465 // and in parallel iterate labels of features
466 TDF_ChildIDIterator aFLabIter(groupLabel(FEATURES_GROUP), TDataStd_Comment::GetID());
467 while(aFIter != myFeatures.end() || aFLabIter.More()) {
468 static const int INFINITE_TAG = INT_MAX; // no label means that it exists somwhere in infinite
469 int aFeatureTag = INFINITE_TAG;
470 if (aFIter != myFeatures.end()) { // existing tag for feature
471 boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>((*aFIter)->data());
472 aFeatureTag = aData->label().Tag();
474 int aDSTag = INFINITE_TAG;
475 if (aFLabIter.More()) { // next label in DS is existing
476 aDSTag = aFLabIter.Value()->Label().Tag();
478 if (aDSTag > aFeatureTag) { // feature is removed
479 Model_FeatureDeletedMessage aMsg1(aThis, FEATURES_GROUP);
480 Model_FeatureDeletedMessage aMsg2(aThis, (*aFIter)->getGroup());
481 aFIter = myFeatures.erase(aFIter);
482 // event: model is updated
483 Events_Loop::loop()->send(aMsg1);
484 Events_Loop::loop()->send(aMsg2);
485 } else if (aDSTag < aFeatureTag) { // a new feature is inserted
487 boost::shared_ptr<ModelAPI_Feature> aFeature = ModelAPI_PluginManager::get()->createFeature(
488 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
489 aFLabIter.Value())->Get()).ToCString());
491 if (aFIter == myFeatures.end()) { // must be before "setData" to redo the sketch line correctly
492 myFeatures.push_back(aFeature);
493 aFIter = myFeatures.end();
496 myFeatures.insert(aFIter, aFeature);
498 boost::shared_ptr<Model_Data> aData(new Model_Data);
499 TDF_Label aLab = aFLabIter.Value()->Label();
500 aData->setLabel(aLab);
501 aData->setFeature(aFeature);
502 aFeature->setDoc(aThis);
503 aFeature->setData(aData);
504 aFeature->initAttributes();
506 // event: model is updated
507 static Events_ID anEvent = Events_Loop::eventByName(EVENT_FEATURE_CREATED);
508 Model_FeatureUpdatedMessage aMsg1(aFeature, anEvent);
509 Events_Loop::loop()->send(aMsg1);
510 boost::shared_ptr<ModelAPI_Feature> anObj = objectByFeature(aFeature);
512 Model_FeatureUpdatedMessage aMsg2(anObj, anEvent);
513 Events_Loop::loop()->send(aMsg2);
516 // feature for this label is added, so go to the next label
518 } else { // nothing is changed, both iterators are incremented