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)
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);
69 aPath += theID.c_str();
70 aPath += ".cbf"; // standard binary file extension
74 bool Model_Document::load(const char* theFileName)
76 Handle(Model_Application) anApp = Model_Application::getApplication();
77 if (this == Model_Session::get()->rootDocument().get()) {
78 anApp->setLoadPath(theFileName);
80 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
81 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
83 aStatus = anApp->Open(aPath, myDoc);
84 } catch (Standard_Failure) {
85 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
87 std::string("Exception in opening of document: ") + aFail->GetMessageString());
90 bool isError = aStatus != PCDM_RS_OK;
93 case PCDM_RS_UnknownDocument:
94 Events_Error::send(std::string("Can not open document: unknown format"));
96 case PCDM_RS_AlreadyRetrieved:
97 Events_Error::send(std::string("Can not open document: already opened"));
99 case PCDM_RS_AlreadyRetrievedAndModified:
101 std::string("Can not open document: already opened and modified"));
103 case PCDM_RS_NoDriver:
104 Events_Error::send(std::string("Can not open document: driver library is not found"));
106 case PCDM_RS_UnknownFileDriver:
107 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
109 case PCDM_RS_OpenError:
110 Events_Error::send(std::string("Can not open document: file open error"));
112 case PCDM_RS_NoVersion:
113 Events_Error::send(std::string("Can not open document: invalid version"));
115 case PCDM_RS_NoModel:
116 Events_Error::send(std::string("Can not open document: no data model"));
118 case PCDM_RS_NoDocument:
119 Events_Error::send(std::string("Can not open document: no document inside"));
121 case PCDM_RS_FormatFailure:
122 Events_Error::send(std::string("Can not open document: format failure"));
124 case PCDM_RS_TypeNotFoundInSchema:
125 Events_Error::send(std::string("Can not open document: invalid object"));
127 case PCDM_RS_UnrecognizedFileFormat:
128 Events_Error::send(std::string("Can not open document: unrecognized file format"));
130 case PCDM_RS_MakeFailure:
131 Events_Error::send(std::string("Can not open document: make failure"));
133 case PCDM_RS_PermissionDenied:
134 Events_Error::send(std::string("Can not open document: permission denied"));
136 case PCDM_RS_DriverFailure:
137 Events_Error::send(std::string("Can not open document: driver failure"));
140 Events_Error::send(std::string("Can not open document: unknown error"));
145 myDoc->SetUndoLimit(UNDO_LIMIT);
146 synchronizeFeatures();
151 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
153 // create a directory in the root document if it is not yet exist
154 if (this == Model_Session::get()->rootDocument().get()) {
156 CreateDirectory(theFileName, NULL);
158 mkdir(theFileName, 0x1ff);
161 // filename in the dir is id of document inside of the given directory
162 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
163 PCDM_StoreStatus aStatus;
165 aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
166 } catch (Standard_Failure) {
167 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
169 std::string("Exception in saving of document: ") + aFail->GetMessageString());
172 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
175 case PCDM_SS_DriverFailure:
176 Events_Error::send(std::string("Can not save document: save driver-library failure"));
178 case PCDM_SS_WriteFailure:
179 Events_Error::send(std::string("Can not save document: file writing failure"));
181 case PCDM_SS_Failure:
183 Events_Error::send(std::string("Can not save document"));
187 myTransactionsAfterSave = 0;
188 if (isDone) { // save also sub-documents if any
189 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
190 std::set<std::string>::iterator aSubIter = mySubs.begin();
191 for (; aSubIter != mySubs.end() && isDone; aSubIter++)
192 isDone = subDocument(*aSubIter)->save(theFileName, theResults);
197 void Model_Document::close()
199 boost::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
200 if (this != aPM->rootDocument().get() && this == aPM->currentDocument().get()) {
201 aPM->setCurrentDocument(aPM->rootDocument());
204 std::set<std::string>::iterator aSubIter = mySubs.begin();
205 for (; aSubIter != mySubs.end(); aSubIter++)
206 subDocument(*aSubIter)->close();
209 /* do not close because it can be undoed
210 if (myDoc->CanClose() == CDM_CCS_OK)
212 Model_Application::getApplication()->deleteDocument(myID);
216 void Model_Document::startOperation()
218 if (myDoc->HasOpenCommand()) { // start of nested command
219 if (myNestedNum == -1) {
221 myDoc->InitDeltaCompaction();
223 myIsEmptyTr[myTransactionsAfterSave] = false;
224 myTransactionsAfterSave++;
226 } else { // start the simple command
229 // new command for all subs
230 std::set<std::string>::iterator aSubIter = mySubs.begin();
231 for (; aSubIter != mySubs.end(); aSubIter++)
232 subDocument(*aSubIter)->startOperation();
235 void Model_Document::compactNested()
237 bool allWasEmpty = true;
238 while (myNestedNum != -1) {
239 myTransactionsAfterSave--;
240 if (!myIsEmptyTr[myTransactionsAfterSave]) {
243 myIsEmptyTr.erase(myTransactionsAfterSave);
246 myIsEmptyTr[myTransactionsAfterSave] = allWasEmpty;
247 myTransactionsAfterSave++;
248 myDoc->PerformDeltaCompaction();
251 void Model_Document::finishOperation()
253 // just to be sure that everybody knows that changes were performed
255 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
256 boost::static_pointer_cast<Model_Session>(Model_Session::get())
257 ->setCheckTransactions(false); // for nested transaction commit
258 Events_Loop* aLoop = Events_Loop::loop();
259 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
260 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
261 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
262 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
263 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
264 boost::static_pointer_cast<Model_Session>(Model_Session::get())
265 ->setCheckTransactions(true); // for nested transaction commit
267 if (myNestedNum != -1) // this nested transaction is owervritten
269 if (!myDoc->HasOpenCommand()) {
270 if (myNestedNum != -1) {
275 // returns false if delta is empty and no transaction was made
276 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand(); // && (myNestedNum == -1);
277 myTransactionsAfterSave++;
280 // finish for all subs
281 std::set<std::string>::iterator aSubIter = mySubs.begin();
282 for (; aSubIter != mySubs.end(); aSubIter++)
283 subDocument(*aSubIter)->finishOperation();
286 void Model_Document::abortOperation()
288 if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
289 // first compact all nested
291 // for nested it is undo and clear redos
294 myTransactionsAfterSave--;
295 myIsEmptyTr.erase(myTransactionsAfterSave);
297 if (myNestedNum == 0) // abort only high-level
299 myDoc->AbortCommand();
301 synchronizeFeatures(true);
302 // abort for all subs
303 std::set<std::string>::iterator aSubIter = mySubs.begin();
304 for (; aSubIter != mySubs.end(); aSubIter++)
305 subDocument(*aSubIter)->abortOperation();
308 bool Model_Document::isOperation()
310 // operation is opened for all documents: no need to check subs
311 return myDoc->HasOpenCommand() == Standard_True ;
314 bool Model_Document::isModified()
316 // is modified if at least one operation was commited and not undoed
317 return myTransactionsAfterSave > 0;
320 bool Model_Document::canUndo()
322 if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
323 && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
325 // check other subs contains operation that can be undoed
326 std::set<std::string>::iterator aSubIter = mySubs.begin();
327 for (; aSubIter != mySubs.end(); aSubIter++)
328 if (subDocument(*aSubIter)->canUndo())
333 void Model_Document::undo()
335 myTransactionsAfterSave--;
338 if (!myIsEmptyTr[myTransactionsAfterSave])
340 synchronizeFeatures(true);
342 std::set<std::string>::iterator aSubIter = mySubs.begin();
343 for (; aSubIter != mySubs.end(); aSubIter++)
344 subDocument(*aSubIter)->undo();
347 bool Model_Document::canRedo()
349 if (myDoc->GetAvailableRedos() > 0)
351 // check other subs contains operation that can be redoed
352 std::set<std::string>::iterator aSubIter = mySubs.begin();
353 for (; aSubIter != mySubs.end(); aSubIter++)
354 if (subDocument(*aSubIter)->canRedo())
359 void Model_Document::redo()
361 if (myNestedNum != -1)
363 if (!myIsEmptyTr[myTransactionsAfterSave])
365 myTransactionsAfterSave++;
366 synchronizeFeatures(true);
368 std::set<std::string>::iterator aSubIter = mySubs.begin();
369 for (; aSubIter != mySubs.end(); aSubIter++)
370 subDocument(*aSubIter)->redo();
373 /// Appenad to the array of references a new referenced label
374 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
376 Handle(TDataStd_ReferenceArray) aRefs;
377 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
378 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
379 aRefs->SetValue(0, theReferenced);
380 } else { // extend array by one more element
381 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
383 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
384 aNewArray->SetValue(a, aRefs->Value(a));
386 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
387 aRefs->SetInternalArray(aNewArray);
391 FeaturePtr Model_Document::addFeature(std::string theID)
393 TDF_Label anEmptyLab;
394 FeaturePtr anEmptyFeature;
395 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
396 boost::shared_ptr<Model_Document> aDocToAdd = boost::dynamic_pointer_cast<Model_Document>(
397 aFeature->documentToAdd());
399 TDF_Label aFeatureLab;
400 if (!aFeature->isAction()) { // do not add action to the data model
401 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
402 aFeatureLab = aFeaturesLab.NewChild();
403 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
404 // keep the feature ID to restore document later correctly
405 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
406 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
407 // store feature in the history of features array
408 if (aFeature->isInHistory()) {
409 AddToRefArray(aFeaturesLab, aFeatureLab);
412 if (!aFeature->isAction()) { // do not add action to the data model
413 // event: feature is added
414 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
415 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
421 /// Appenad to the array of references a new referenced label.
422 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
423 /// \returns the index of removed element
424 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
427 int aResult = -1; // no returned
428 Handle(TDataStd_ReferenceArray) aRefs;
429 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
430 if (aRefs->Length() == 1) { // just erase an array
431 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
432 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
435 } else { // reduce the array
436 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
438 int aCount = aRefs->Lower();
439 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
440 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
444 aNewArray->SetValue(aCount, aRefs->Value(a));
447 aRefs->SetInternalArray(aNewArray);
453 void Model_Document::removeFeature(FeaturePtr theFeature)
455 boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
456 TDF_Label aFeatureLabel = aData->label().Father();
457 if (myObjs.IsBound(aFeatureLabel))
458 myObjs.UnBind(aFeatureLabel);
460 return; // not found feature => do not remove
462 // erase all attributes under the label of feature
463 aFeatureLabel.ForgetAllAttributes();
464 // remove it from the references array
465 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
467 // event: feature is deleted
468 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
469 // results of this feature must be redisplayed
470 static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
471 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
472 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
473 for (; aRIter != aResults.cend(); aRIter++) {
474 boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
475 aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
476 ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
477 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), aRes->groupName());
481 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
483 if (myObjs.IsBound(theLabel))
484 return myObjs.Find(theLabel);
485 return FeaturePtr(); // not found
488 ObjectPtr Model_Document::object(TDF_Label theLabel)
490 // try feature by label
491 FeaturePtr aFeature = feature(theLabel);
493 return feature(theLabel);
494 TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
495 aFeature = feature(aFeatureLabel);
497 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
498 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
499 for (; aRIter != aResults.cend(); aRIter++) {
500 boost::shared_ptr<Model_Data> aResData = boost::dynamic_pointer_cast<Model_Data>(
502 if (aResData->label().Father().IsEqual(theLabel))
506 return FeaturePtr(); // not found
509 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
511 // just store sub-document identifier here to manage it later
512 if (mySubs.find(theDocID) == mySubs.end())
513 mySubs.insert(theDocID);
514 return Model_Application::getApplication()->getDocument(theDocID);
517 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
518 const bool theHidden)
520 if (theGroupID == ModelAPI_Feature::group()) {
523 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
524 for (; aLabIter.More(); aLabIter.Next()) {
525 if (theIndex == anIndex) {
526 TDF_Label aFLabel = aLabIter.Value()->Label();
527 return feature(aFLabel);
532 Handle(TDataStd_ReferenceArray) aRefs;
533 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
535 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
537 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
538 return feature(aFeatureLabel);
541 // comment must be in any feature: it is kind
543 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
544 for (; aLabIter.More(); aLabIter.Next()) {
545 TDF_Label aFLabel = aLabIter.Value()->Label();
546 FeaturePtr aFeature = feature(aFLabel);
547 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
548 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
549 for (; aRIter != aResults.cend(); aRIter++) {
550 if ((theHidden || (*aRIter)->isInHistory()) && (*aRIter)->groupName() == theGroupID) {
551 if (anIndex == theIndex)
562 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
565 if (theGroupID == ModelAPI_Feature::group()) {
567 return myObjs.Size();
569 Handle(TDataStd_ReferenceArray) aRefs;
570 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
571 return aRefs->Length();
574 // comment must be in any feature: it is kind
575 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
576 for (; aLabIter.More(); aLabIter.Next()) {
577 TDF_Label aFLabel = aLabIter.Value()->Label();
578 FeaturePtr aFeature = feature(aFLabel);
579 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
580 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
581 for (; aRIter != aResults.cend(); aRIter++) {
582 if ((theHidden || (*aRIter)->isInHistory()) && (*aRIter)->groupName() == theGroupID) {
588 // group is not found
592 TDF_Label Model_Document::featuresLabel()
594 return myDoc->Main().FindChild(TAG_OBJECTS);
597 void Model_Document::setUniqueName(FeaturePtr theFeature)
599 if (!theFeature->data()->name().empty())
600 return; // not needed, name is already defined
601 std::string aName; // result
602 // first count all objects of such kind to start with index = count + 1
604 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
605 for (; aFIter.More(); aFIter.Next()) {
606 if (aFIter.Value()->getKind() == theFeature->getKind())
609 // generate candidate name
610 std::stringstream aNameStream;
611 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
612 aName = aNameStream.str();
613 // check this is unique, if not, increase index by 1
614 for (aFIter.Initialize(myObjs); aFIter.More();) {
615 FeaturePtr aFeature = aFIter.Value();
616 bool isSameName = aFeature->isInHistory() && aFeature->data()->name() == aName;
617 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
618 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
619 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
620 for (; aRIter != aResults.cend(); aRIter++) {
621 isSameName = (*aRIter)->isInHistory() && (*aRIter)->data()->name() == aName;
626 std::stringstream aNameStream;
627 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
628 aName = aNameStream.str();
629 // reinitialize iterator to make sure a new name is unique
630 aFIter.Initialize(myObjs);
634 theFeature->data()->setName(aName);
637 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
639 boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
641 boost::shared_ptr<Model_Data> aData(new Model_Data);
642 aData->setLabel(theLab.FindChild(theTag));
643 aData->setObject(theObj);
644 theObj->setDoc(aThis);
645 theObj->setData(aData);
646 FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
648 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
649 aFeature->initAttributes();
653 void Model_Document::synchronizeFeatures(const bool theMarkUpdated)
655 boost::shared_ptr<ModelAPI_Document> aThis =
656 Model_Application::getApplication()->getDocument(myID);
657 // after all updates, sends a message that groups of features were created or updated
658 boost::static_pointer_cast<Model_Session>(Model_Session::get())
659 ->setCheckTransactions(false);
660 Events_Loop* aLoop = Events_Loop::loop();
661 aLoop->activateFlushes(false);
663 // update all objects by checking are they of labels or not
664 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
665 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
666 for (; aLabIter.More(); aLabIter.Next()) {
667 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
668 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
670 FeaturePtr aNewObj = ModelAPI_Session::get()->createFeature(
671 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
673 if (!aNewObj) { // somethig is wrong, most probably, the opened document has invalid structure
674 Events_Error::send("Invalid type of object in the document");
675 aLabIter.Value()->Label().ForgetAllAttributes();
678 // this must be before "setData" to redo the sketch line correctly
679 myObjs.Bind(aFeatureLabel, aNewObj);
680 aNewFeatures.insert(aNewObj);
681 initData(aNewObj, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
683 // event: model is updated
684 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
685 ModelAPI_EventCreator::get()->sendUpdated(aNewObj, anEvent);
687 // update results of the appeared feature
688 updateResults(aNewObj);
689 } else { // nothing is changed, both iterators are incremented
690 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
691 aKeptFeatures.insert(aFeature);
692 if (theMarkUpdated) {
693 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
694 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
696 updateResults(aFeature);
699 // execute new features to restore results: after features creation to make all references valid
700 /*std::set<FeaturePtr>::iterator aNewIter = aNewFeatures.begin();
701 for(; aNewIter != aNewFeatures.end(); aNewIter++) {
702 (*aNewIter)->execute();
704 // check all features are checked: if not => it was removed
705 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
706 while (aFIter.More()) {
707 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
708 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
709 FeaturePtr aFeature = aFIter.Value();
710 TDF_Label aLab = aFIter.Key();
713 // event: model is updated
714 if (aFeature->isInHistory()) {
715 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
717 // results of this feature must be redisplayed (hided)
718 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
719 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
720 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
721 for (; aRIter != aResults.cend(); aRIter++) {
722 boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
723 //aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
724 ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
725 ModelAPI_EventCreator::get()->sendDeleted(aThis, aRes->groupName());
727 // redisplay also removed feature (used for sketch and AISObject)
728 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
733 myExecuteFeatures = false;
734 aLoop->activateFlushes(true);
736 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
737 if (theMarkUpdated) {
738 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
740 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
741 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
742 boost::static_pointer_cast<Model_Session>(Model_Session::get())
743 ->setCheckTransactions(true);
744 myExecuteFeatures = true;
747 TDF_Label Model_Document::resultLabel(
748 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
750 const boost::shared_ptr<Model_Data>& aData =
751 boost::dynamic_pointer_cast<Model_Data>(theFeatureData);
752 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
755 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
756 boost::shared_ptr<ModelAPI_Result> theResult,
757 const int theResultIndex)
759 boost::shared_ptr<ModelAPI_Document> aThis =
760 Model_Application::getApplication()->getDocument(myID);
761 theResult->setDoc(aThis);
762 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
763 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
764 theResult->data()->setName(theFeatureData->name());
768 static const Standard_GUID ID_CONSTRUCTION("b59fa408-8ab1-42b8-980c-af5adeebe7e4");
769 static const Standard_GUID ID_BODY("c1148e9a-9b17-4e9c-9160-18e918fd0013");
770 static const Standard_GUID ID_PART("1b3319b9-3e0a-4298-a1dc-3fb5aaf9be59");
772 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
773 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
775 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
776 TDataStd_UAttribute::Set(aLab, ID_CONSTRUCTION);
777 ObjectPtr anOldObject = object(aLab);
778 boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
780 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
783 aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
784 storeResult(theFeatureData, aResult, theIndex);
789 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
790 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
792 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
793 TDataStd_UAttribute::Set(aLab, ID_BODY);
794 ObjectPtr anOldObject = object(aLab);
795 boost::shared_ptr<ModelAPI_ResultBody> aResult;
797 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
800 aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
801 storeResult(theFeatureData, aResult, theIndex);
806 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
807 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
809 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
810 TDataStd_UAttribute::Set(aLab, ID_PART);
811 ObjectPtr anOldObject = object(aLab);
812 boost::shared_ptr<ModelAPI_ResultPart> aResult;
814 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
817 aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
818 storeResult(theFeatureData, aResult, theIndex);
823 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
824 const boost::shared_ptr<ModelAPI_Result>& theResult)
826 boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
828 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
829 return feature(aFeatureLab);
834 void Model_Document::updateResults(FeaturePtr theFeature)
836 // for not persistent is will be done by parametric updater automatically
837 if (!theFeature->isPersistentResult()) return;
838 // check the existing results and remove them if there is nothing on the label
839 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
840 while(aResIter != theFeature->results().cend()) {
841 ResultBodyPtr aBody = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
843 if (!aBody->data()->isValid()) {
844 // found a disappeared result => remove it
845 theFeature->removeResult(aBody);
846 // start iterate from beginning because iterator is corrupted by removing
847 aResIter = theFeature->results().cbegin();
853 // check that results are presented on all labels
854 int aResSize = theFeature->results().size();
855 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
856 for(; aLabIter.More(); aLabIter.Next()) {
857 // here must be GUID of the feature
858 int aResIndex = aLabIter.Value().Tag() - 1;
860 if (aResSize <= aResIndex) {
861 TDF_Label anArgLab = aLabIter.Value();
862 if (anArgLab.IsAttribute(ID_BODY)) {
863 aNewBody = createBody(theFeature->data(), aResIndex);
864 } else if (anArgLab.IsAttribute(ID_PART)) {
865 aNewBody = createPart(theFeature->data(), aResIndex);
866 } else if (!anArgLab.IsAttribute(ID_CONSTRUCTION)) {
867 Events_Error::send("Unknown type of result if found in the document");
870 theFeature->setResult(aNewBody, aResIndex);
876 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
878 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
881 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
883 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);