1 // File: Model_Document.cxx
2 // Created: 28 Feb 2014
3 // Author: Mikhail PONIKAROV
5 #include <Model_Document.h>
6 #include <Model_Data.h>
7 #include <Model_Application.h>
8 #include <Model_Session.h>
9 #include <Model_Events.h>
10 #include <Model_ResultPart.h>
11 #include <Model_ResultConstruction.h>
12 #include <Model_ResultBody.h>
13 #include <Events_Loop.h>
14 #include <Events_Error.h>
16 #include <TDataStd_Integer.hxx>
17 #include <TDataStd_Comment.hxx>
18 #include <TDataStd_UAttribute.hxx>
19 #include <TDF_ChildIDIterator.hxx>
20 #include <TDataStd_ReferenceArray.hxx>
21 #include <TDataStd_HLabelArray1.hxx>
22 #include <TDataStd_Name.hxx>
23 #include <TDF_Reference.hxx>
24 #include <TDF_ChildIDIterator.hxx>
25 #include <TDF_LabelMapHasher.hxx>
33 # define _separator_ '\\'
35 # define _separator_ '/'
38 static const int UNDO_LIMIT = 10; // number of possible undo operations
40 static const int TAG_GENERAL = 1; // general properties tag
41 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree (features, results)
42 static const int TAG_HISTORY = 3; // tag of the history sub-tree (python dump)
45 static const int TAG_FEATURE_ARGUMENTS = 1; ///< where the arguments are located
46 static const int TAG_FEATURE_RESULTS = 2; ///< where the results are located
48 Model_Document::Model_Document(const std::string theID, const std::string theKind)
49 : myID(theID), myKind(theKind),
50 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
52 myDoc->SetUndoLimit(UNDO_LIMIT);
53 myTransactionsAfterSave = 0;
55 myExecuteFeatures = true;
56 //myDoc->SetNestedTransactionMode();
57 // to have something in the document and avoid empty doc open/save problem
58 // in transaction for nesting correct working
60 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
61 myDoc->CommitCommand();
64 /// Returns the file name of this document by the nameof directory and identifuer of a document
65 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
67 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
68 // remove end-separators
69 while(aPath.Length() && (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
70 aPath.Remove(aPath.Length());
72 aPath += theID.c_str();
73 aPath += ".cbf"; // standard binary file extension
77 bool Model_Document::load(const char* theFileName)
79 Handle(Model_Application) anApp = Model_Application::getApplication();
80 if (this == Model_Session::get()->moduleDocument().get()) {
81 anApp->setLoadPath(theFileName);
83 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
84 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
86 aStatus = anApp->Open(aPath, myDoc);
87 } catch (Standard_Failure) {
88 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
90 std::string("Exception in opening of document: ") + aFail->GetMessageString());
93 bool isError = aStatus != PCDM_RS_OK;
96 case PCDM_RS_UnknownDocument:
97 Events_Error::send(std::string("Can not open document: unknown format"));
99 case PCDM_RS_AlreadyRetrieved:
100 Events_Error::send(std::string("Can not open document: already opened"));
102 case PCDM_RS_AlreadyRetrievedAndModified:
104 std::string("Can not open document: already opened and modified"));
106 case PCDM_RS_NoDriver:
107 Events_Error::send(std::string("Can not open document: driver library is not found"));
109 case PCDM_RS_UnknownFileDriver:
110 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
112 case PCDM_RS_OpenError:
113 Events_Error::send(std::string("Can not open document: file open error"));
115 case PCDM_RS_NoVersion:
116 Events_Error::send(std::string("Can not open document: invalid version"));
118 case PCDM_RS_NoModel:
119 Events_Error::send(std::string("Can not open document: no data model"));
121 case PCDM_RS_NoDocument:
122 Events_Error::send(std::string("Can not open document: no document inside"));
124 case PCDM_RS_FormatFailure:
125 Events_Error::send(std::string("Can not open document: format failure"));
127 case PCDM_RS_TypeNotFoundInSchema:
128 Events_Error::send(std::string("Can not open document: invalid object"));
130 case PCDM_RS_UnrecognizedFileFormat:
131 Events_Error::send(std::string("Can not open document: unrecognized file format"));
133 case PCDM_RS_MakeFailure:
134 Events_Error::send(std::string("Can not open document: make failure"));
136 case PCDM_RS_PermissionDenied:
137 Events_Error::send(std::string("Can not open document: permission denied"));
139 case PCDM_RS_DriverFailure:
140 Events_Error::send(std::string("Can not open document: driver failure"));
143 Events_Error::send(std::string("Can not open document: unknown error"));
148 myDoc->SetUndoLimit(UNDO_LIMIT);
149 synchronizeFeatures();
154 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
156 // create a directory in the root document if it is not yet exist
157 if (this == Model_Session::get()->moduleDocument().get()) {
159 CreateDirectory(theFileName, NULL);
161 mkdir(theFileName, 0x1ff);
164 // filename in the dir is id of document inside of the given directory
165 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
166 PCDM_StoreStatus aStatus;
168 aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
169 } catch (Standard_Failure) {
170 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
172 std::string("Exception in saving of document: ") + aFail->GetMessageString());
175 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
178 case PCDM_SS_DriverFailure:
179 Events_Error::send(std::string("Can not save document: save driver-library failure"));
181 case PCDM_SS_WriteFailure:
182 Events_Error::send(std::string("Can not save document: file writing failure"));
184 case PCDM_SS_Failure:
186 Events_Error::send(std::string("Can not save document"));
190 myTransactionsAfterSave = 0;
191 if (isDone) { // save also sub-documents if any
192 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
193 std::set<std::string>::iterator aSubIter = mySubs.begin();
194 for (; aSubIter != mySubs.end() && isDone; aSubIter++) {
195 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
201 void Model_Document::close()
203 boost::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
204 if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
205 aPM->setActiveDocument(aPM->moduleDocument());
208 std::set<std::string>::iterator aSubIter = mySubs.begin();
209 for (; aSubIter != mySubs.end(); aSubIter++)
210 subDoc(*aSubIter)->close();
213 /* do not close because it can be undoed
214 if (myDoc->CanClose() == CDM_CCS_OK)
216 Model_Application::getApplication()->deleteDocument(myID);
220 void Model_Document::startOperation()
222 if (myDoc->HasOpenCommand()) { // start of nested command
223 if (myNestedNum == -1) {
225 myDoc->InitDeltaCompaction();
227 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();
228 myTransactionsAfterSave++;
229 myDoc->OpenCommand();
230 } else { // start the simple command
233 // new command for all subs
234 std::set<std::string>::iterator aSubIter = mySubs.begin();
235 for (; aSubIter != mySubs.end(); aSubIter++)
236 subDoc(*aSubIter)->startOperation();
239 bool Model_Document::compactNested()
241 bool allWasEmpty = true;
242 while (myNestedNum != -1) {
243 myTransactionsAfterSave--;
244 if (!myIsEmptyTr[myTransactionsAfterSave]) {
247 myIsEmptyTr.erase(myTransactionsAfterSave);
250 myIsEmptyTr[myTransactionsAfterSave] = allWasEmpty;
251 myTransactionsAfterSave++;
252 myDoc->PerformDeltaCompaction();
256 void Model_Document::finishOperation()
258 // just to be sure that everybody knows that changes were performed
260 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
261 boost::static_pointer_cast<Model_Session>(Model_Session::get())
262 ->setCheckTransactions(false); // for nested transaction commit
263 Events_Loop* aLoop = Events_Loop::loop();
264 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
265 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
266 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
267 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
268 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
269 boost::static_pointer_cast<Model_Session>(Model_Session::get())
270 ->setCheckTransactions(true); // for nested transaction commit
272 if (myNestedNum != -1) // this nested transaction is owervritten
274 if (!myDoc->HasOpenCommand()) {
275 if (myNestedNum != -1) {
280 // returns false if delta is empty and no transaction was made
281 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand(); // && (myNestedNum == -1);
282 myTransactionsAfterSave++;
285 // finish for all subs
286 std::set<std::string>::iterator aSubIter = mySubs.begin();
287 for (; aSubIter != mySubs.end(); aSubIter++)
288 subDoc(*aSubIter)->finishOperation();
291 void Model_Document::abortOperation()
293 if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
294 // first compact all nested
295 if (compactNested()) {
296 // for nested it is undo and clear redos
300 myTransactionsAfterSave--;
301 myIsEmptyTr.erase(myTransactionsAfterSave);
303 if (myNestedNum == 0) // abort only high-level
305 myDoc->AbortCommand();
307 synchronizeFeatures(true);
308 // abort for all subs
309 std::set<std::string>::iterator aSubIter = mySubs.begin();
310 for (; aSubIter != mySubs.end(); aSubIter++)
311 subDoc(*aSubIter)->abortOperation();
314 bool Model_Document::isOperation()
316 // operation is opened for all documents: no need to check subs
317 return myDoc->HasOpenCommand() == Standard_True ;
320 bool Model_Document::isModified()
322 // is modified if at least one operation was commited and not undoed
323 return myTransactionsAfterSave > 0 || isOperation();
326 bool Model_Document::canUndo()
328 if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
329 && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
331 // check other subs contains operation that can be undoed
332 std::set<std::string>::iterator aSubIter = mySubs.begin();
333 for (; aSubIter != mySubs.end(); aSubIter++)
334 if (subDoc(*aSubIter)->canUndo())
339 void Model_Document::undo()
341 myTransactionsAfterSave--;
344 if (!myIsEmptyTr[myTransactionsAfterSave])
346 synchronizeFeatures(true);
348 std::set<std::string>::iterator aSubIter = mySubs.begin();
349 for (; aSubIter != mySubs.end(); aSubIter++)
350 subDoc(*aSubIter)->undo();
353 bool Model_Document::canRedo()
355 if (myDoc->GetAvailableRedos() > 0)
357 // check other subs contains operation that can be redoed
358 std::set<std::string>::iterator aSubIter = mySubs.begin();
359 for (; aSubIter != mySubs.end(); aSubIter++)
360 if (subDoc(*aSubIter)->canRedo())
365 void Model_Document::redo()
367 if (myNestedNum != -1)
369 if (!myIsEmptyTr[myTransactionsAfterSave])
371 myTransactionsAfterSave++;
372 synchronizeFeatures(true);
374 std::set<std::string>::iterator aSubIter = mySubs.begin();
375 for (; aSubIter != mySubs.end(); aSubIter++)
376 subDoc(*aSubIter)->redo();
379 /// Appenad to the array of references a new referenced label
380 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
382 Handle(TDataStd_ReferenceArray) aRefs;
383 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
384 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
385 aRefs->SetValue(0, theReferenced);
386 } else { // extend array by one more element
387 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
389 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
390 aNewArray->SetValue(a, aRefs->Value(a));
392 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
393 aRefs->SetInternalArray(aNewArray);
397 FeaturePtr Model_Document::addFeature(std::string theID)
399 TDF_Label anEmptyLab;
400 FeaturePtr anEmptyFeature;
401 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
402 boost::shared_ptr<Model_Document> aDocToAdd = boost::dynamic_pointer_cast<Model_Document>(
403 aFeature->documentToAdd());
405 TDF_Label aFeatureLab;
406 if (!aFeature->isAction()) { // do not add action to the data model
407 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
408 aFeatureLab = aFeaturesLab.NewChild();
409 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
410 // keep the feature ID to restore document later correctly
411 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
412 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
413 // store feature in the history of features array
414 if (aFeature->isInHistory()) {
415 AddToRefArray(aFeaturesLab, aFeatureLab);
418 if (!aFeature->isAction()) { // do not add action to the data model
419 // event: feature is added
420 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
421 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
422 } else { // feature must be executed
423 // no creation event => updater not working, problem with remove part
430 /// Appenad to the array of references a new referenced label.
431 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
432 /// \returns the index of removed element
433 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
436 int aResult = -1; // no returned
437 Handle(TDataStd_ReferenceArray) aRefs;
438 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
439 if (aRefs->Length() == 1) { // just erase an array
440 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
441 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
444 } else { // reduce the array
445 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
447 int aCount = aRefs->Lower();
448 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
449 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
453 aNewArray->SetValue(aCount, aRefs->Value(a));
456 aRefs->SetInternalArray(aNewArray);
462 void Model_Document::removeFeature(FeaturePtr theFeature)
464 boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
465 TDF_Label aFeatureLabel = aData->label().Father();
466 if (myObjs.IsBound(aFeatureLabel))
467 myObjs.UnBind(aFeatureLabel);
469 return; // not found feature => do not remove
471 // erase all attributes under the label of feature
472 aFeatureLabel.ForgetAllAttributes();
473 // remove it from the references array
474 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
476 // event: feature is deleted
477 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
478 // results of this feature must be redisplayed
479 static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
480 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
481 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
482 for (; aRIter != aResults.cend(); aRIter++) {
483 boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
484 aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
485 ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
486 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), aRes->groupName());
490 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
492 if (myObjs.IsBound(theLabel))
493 return myObjs.Find(theLabel);
494 return FeaturePtr(); // not found
497 ObjectPtr Model_Document::object(TDF_Label theLabel)
499 // try feature by label
500 FeaturePtr aFeature = feature(theLabel);
502 return feature(theLabel);
503 TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
504 aFeature = feature(aFeatureLabel);
506 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
507 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
508 for (; aRIter != aResults.cend(); aRIter++) {
509 boost::shared_ptr<Model_Data> aResData = boost::dynamic_pointer_cast<Model_Data>(
511 if (aResData->label().Father().IsEqual(theLabel))
515 return FeaturePtr(); // not found
518 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
520 // just store sub-document identifier here to manage it later
521 if (mySubs.find(theDocID) == mySubs.end())
522 mySubs.insert(theDocID);
523 return Model_Application::getApplication()->getDocument(theDocID);
526 boost::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
528 // just store sub-document identifier here to manage it later
529 if (mySubs.find(theDocID) == mySubs.end())
530 mySubs.insert(theDocID);
531 return boost::dynamic_pointer_cast<Model_Document>(
532 Model_Application::getApplication()->getDocument(theDocID));
535 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
536 const bool theHidden)
538 if (theGroupID == ModelAPI_Feature::group()) {
541 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
542 for (; aLabIter.More(); aLabIter.Next()) {
543 if (theIndex == anIndex) {
544 TDF_Label aFLabel = aLabIter.Value()->Label();
545 return feature(aFLabel);
550 Handle(TDataStd_ReferenceArray) aRefs;
551 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
553 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
555 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
556 return feature(aFeatureLabel);
559 // comment must be in any feature: it is kind
561 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
562 for (; aLabIter.More(); aLabIter.Next()) {
563 TDF_Label aFLabel = aLabIter.Value()->Label();
564 FeaturePtr aFeature = feature(aFLabel);
565 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
566 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
567 for (; aRIter != aResults.cend(); aRIter++) {
568 if ((*aRIter)->groupName() != theGroupID) continue;
569 bool isIn = theHidden;
570 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
571 isIn = myConcealedResults.find(*aRIter) == myConcealedResults.end();
574 if (anIndex == theIndex)
585 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
588 if (theGroupID == ModelAPI_Feature::group()) {
590 return myObjs.Size();
592 Handle(TDataStd_ReferenceArray) aRefs;
593 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
594 return aRefs->Length();
597 // comment must be in any feature: it is kind
598 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
599 for (; aLabIter.More(); aLabIter.Next()) {
600 TDF_Label aFLabel = aLabIter.Value()->Label();
601 FeaturePtr aFeature = feature(aFLabel);
602 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
603 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
604 for (; aRIter != aResults.cend(); aRIter++) {
605 if ((*aRIter)->groupName() != theGroupID) continue;
606 bool isIn = theHidden;
607 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
608 isIn = myConcealedResults.find(*aRIter) == myConcealedResults.end();
615 // group is not found
619 TDF_Label Model_Document::featuresLabel()
621 return myDoc->Main().FindChild(TAG_OBJECTS);
624 void Model_Document::setUniqueName(FeaturePtr theFeature)
626 if (!theFeature->data()->name().empty())
627 return; // not needed, name is already defined
628 std::string aName; // result
629 // first count all objects of such kind to start with index = count + 1
631 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
632 for (; aFIter.More(); aFIter.Next()) {
633 if (aFIter.Value()->getKind() == theFeature->getKind())
636 // generate candidate name
637 std::stringstream aNameStream;
638 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
639 aName = aNameStream.str();
640 // check this is unique, if not, increase index by 1
641 for (aFIter.Initialize(myObjs); aFIter.More();) {
642 FeaturePtr aFeature = aFIter.Value();
643 bool isSameName = aFeature->isInHistory() && aFeature->data()->name() == aName;
644 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
645 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
646 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
647 for (; aRIter != aResults.cend(); aRIter++) {
648 isSameName = (*aRIter)->isInHistory() && (*aRIter)->data()->name() == aName;
653 std::stringstream aNameStream;
654 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
655 aName = aNameStream.str();
656 // reinitialize iterator to make sure a new name is unique
657 aFIter.Initialize(myObjs);
661 theFeature->data()->setName(aName);
664 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
666 boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
668 boost::shared_ptr<Model_Data> aData(new Model_Data);
669 aData->setLabel(theLab.FindChild(theTag));
670 aData->setObject(theObj);
671 theObj->setDoc(aThis);
672 theObj->setData(aData);
673 FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
675 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
676 aFeature->initAttributes();
680 void Model_Document::synchronizeFeatures(const bool theMarkUpdated)
682 boost::shared_ptr<ModelAPI_Document> aThis =
683 Model_Application::getApplication()->getDocument(myID);
684 // after all updates, sends a message that groups of features were created or updated
685 boost::static_pointer_cast<Model_Session>(Model_Session::get())
686 ->setCheckTransactions(false);
687 Events_Loop* aLoop = Events_Loop::loop();
688 aLoop->activateFlushes(false);
690 // update all objects by checking are they of labels or not
691 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
692 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
693 for (; aLabIter.More(); aLabIter.Next()) {
694 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
695 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
697 FeaturePtr aNewObj = ModelAPI_Session::get()->createFeature(
698 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
700 if (!aNewObj) { // somethig is wrong, most probably, the opened document has invalid structure
701 Events_Error::send("Invalid type of object in the document");
702 aLabIter.Value()->Label().ForgetAllAttributes();
705 // this must be before "setData" to redo the sketch line correctly
706 myObjs.Bind(aFeatureLabel, aNewObj);
707 aNewFeatures.insert(aNewObj);
708 initData(aNewObj, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
710 // event: model is updated
711 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
712 ModelAPI_EventCreator::get()->sendUpdated(aNewObj, anEvent);
714 // update results of the appeared feature
715 updateResults(aNewObj);
716 } else { // nothing is changed, both iterators are incremented
717 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
718 aKeptFeatures.insert(aFeature);
719 if (theMarkUpdated) {
720 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
721 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
723 updateResults(aFeature);
726 // execute new features to restore results: after features creation to make all references valid
727 /*std::set<FeaturePtr>::iterator aNewIter = aNewFeatures.begin();
728 for(; aNewIter != aNewFeatures.end(); aNewIter++) {
729 (*aNewIter)->execute();
731 // check all features are checked: if not => it was removed
732 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
733 while (aFIter.More()) {
734 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
735 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
736 FeaturePtr aFeature = aFIter.Value();
737 TDF_Label aLab = aFIter.Key();
740 // event: model is updated
741 //if (aFeature->isInHistory()) {
742 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
744 // results of this feature must be redisplayed (hided)
745 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
746 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
747 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
748 for (; aRIter != aResults.cend(); aRIter++) {
749 boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
750 //aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
751 ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
752 ModelAPI_EventCreator::get()->sendDeleted(aThis, aRes->groupName());
754 // redisplay also removed feature (used for sketch and AISObject)
755 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
760 myExecuteFeatures = false;
761 aLoop->activateFlushes(true);
763 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
764 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
765 if (theMarkUpdated) {
766 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
768 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
769 boost::static_pointer_cast<Model_Session>(Model_Session::get())
770 ->setCheckTransactions(true);
771 myExecuteFeatures = true;
774 TDF_Label Model_Document::resultLabel(
775 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
777 const boost::shared_ptr<Model_Data>& aData =
778 boost::dynamic_pointer_cast<Model_Data>(theFeatureData);
779 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
782 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
783 boost::shared_ptr<ModelAPI_Result> theResult,
784 const int theResultIndex)
786 boost::shared_ptr<ModelAPI_Document> aThis =
787 Model_Application::getApplication()->getDocument(myID);
788 theResult->setDoc(aThis);
789 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
790 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
791 theResult->data()->setName(theFeatureData->name());
795 static const Standard_GUID ID_CONSTRUCTION("b59fa408-8ab1-42b8-980c-af5adeebe7e4");
796 static const Standard_GUID ID_BODY("c1148e9a-9b17-4e9c-9160-18e918fd0013");
797 static const Standard_GUID ID_PART("1b3319b9-3e0a-4298-a1dc-3fb5aaf9be59");
799 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
800 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
802 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
803 TDataStd_UAttribute::Set(aLab, ID_CONSTRUCTION);
804 ObjectPtr anOldObject = object(aLab);
805 boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
807 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
810 aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
811 storeResult(theFeatureData, aResult, theIndex);
816 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
817 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
819 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
820 TDataStd_UAttribute::Set(aLab, ID_BODY);
821 ObjectPtr anOldObject = object(aLab);
822 boost::shared_ptr<ModelAPI_ResultBody> aResult;
824 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
827 aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
828 storeResult(theFeatureData, aResult, theIndex);
833 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
834 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
836 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
837 TDataStd_UAttribute::Set(aLab, ID_PART);
838 ObjectPtr anOldObject = object(aLab);
839 boost::shared_ptr<ModelAPI_ResultPart> aResult;
841 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
844 aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
845 storeResult(theFeatureData, aResult, theIndex);
850 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
851 const boost::shared_ptr<ModelAPI_Result>& theResult)
853 boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
855 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
856 return feature(aFeatureLab);
861 void Model_Document::updateResults(FeaturePtr theFeature)
863 // for not persistent is will be done by parametric updater automatically
864 if (!theFeature->isPersistentResult()) return;
865 // check the existing results and remove them if there is nothing on the label
866 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
867 while(aResIter != theFeature->results().cend()) {
868 ResultBodyPtr aBody = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
870 if (!aBody->data()->isValid()) {
871 // found a disappeared result => remove it
872 theFeature->removeResult(aBody);
873 // start iterate from beginning because iterator is corrupted by removing
874 aResIter = theFeature->results().cbegin();
880 // check that results are presented on all labels
881 int aResSize = theFeature->results().size();
882 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
883 for(; aLabIter.More(); aLabIter.Next()) {
884 // here must be GUID of the feature
885 int aResIndex = aLabIter.Value().Tag() - 1;
887 if (aResSize <= aResIndex) {
888 TDF_Label anArgLab = aLabIter.Value();
889 if (anArgLab.IsAttribute(ID_BODY)) {
890 aNewBody = createBody(theFeature->data(), aResIndex);
891 } else if (anArgLab.IsAttribute(ID_PART)) {
892 aNewBody = createPart(theFeature->data(), aResIndex);
893 } else if (!anArgLab.IsAttribute(ID_CONSTRUCTION) && anArgLab.FindChild(1).HasAttribute()) {
894 Events_Error::send("Unknown type of result is found in the document");
897 theFeature->setResult(aNewBody, aResIndex);
903 void Model_Document::objectIsReferenced(const ObjectPtr& theObject)
905 // only bodies are concealed now
906 ResultBodyPtr aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(theObject);
908 if (myConcealedResults.find(aResult) != myConcealedResults.end()) {
909 Events_Error::send(std::string("The object '") + aResult->data()->name() +
910 "' is already referenced");
912 myConcealedResults.insert(aResult);
913 boost::shared_ptr<ModelAPI_Document> aThis =
914 Model_Application::getApplication()->getDocument(myID);
915 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_ResultBody::group());
920 void Model_Document::objectIsNotReferenced(const ObjectPtr& theObject)
922 // only bodies are concealed now
923 ResultBodyPtr aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(theObject);
925 std::set<ResultPtr>::iterator aFind = myConcealedResults.find(aResult);
926 if (aFind != myConcealedResults.end()) {
927 myConcealedResults.erase(aFind);
928 boost::shared_ptr<ModelAPI_Document> aThis =
929 Model_Application::getApplication()->getDocument(myID);
930 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
931 ModelAPI_EventCreator::get()->sendUpdated(*aFind, anEvent, false);
933 Events_Error::send(std::string("The object '") + aResult->data()->name() +
934 "' was not referenced '");
939 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
941 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
944 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
946 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);