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()->moduleDocument().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()->moduleDocument().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 = subDoc(*aSubIter)->save(theFileName, theResults);
198 void Model_Document::close()
200 boost::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
201 if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
202 aPM->setActiveDocument(aPM->moduleDocument());
205 std::set<std::string>::iterator aSubIter = mySubs.begin();
206 for (; aSubIter != mySubs.end(); aSubIter++)
207 subDoc(*aSubIter)->close();
210 /* do not close because it can be undoed
211 if (myDoc->CanClose() == CDM_CCS_OK)
213 Model_Application::getApplication()->deleteDocument(myID);
217 void Model_Document::startOperation()
219 if (myDoc->HasOpenCommand()) { // start of nested command
220 if (myNestedNum == -1) {
222 myDoc->InitDeltaCompaction();
224 myIsEmptyTr[myTransactionsAfterSave] = false;
225 myTransactionsAfterSave++;
227 } else { // start the simple command
230 // new command for all subs
231 std::set<std::string>::iterator aSubIter = mySubs.begin();
232 for (; aSubIter != mySubs.end(); aSubIter++)
233 subDoc(*aSubIter)->startOperation();
236 void Model_Document::compactNested()
238 bool allWasEmpty = true;
239 while (myNestedNum != -1) {
240 myTransactionsAfterSave--;
241 if (!myIsEmptyTr[myTransactionsAfterSave]) {
244 myIsEmptyTr.erase(myTransactionsAfterSave);
247 myIsEmptyTr[myTransactionsAfterSave] = allWasEmpty;
248 myTransactionsAfterSave++;
249 myDoc->PerformDeltaCompaction();
252 void Model_Document::finishOperation()
254 // just to be sure that everybody knows that changes were performed
256 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
257 boost::static_pointer_cast<Model_Session>(Model_Session::get())
258 ->setCheckTransactions(false); // for nested transaction commit
259 Events_Loop* aLoop = Events_Loop::loop();
260 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
261 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
262 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
263 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
264 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
265 boost::static_pointer_cast<Model_Session>(Model_Session::get())
266 ->setCheckTransactions(true); // for nested transaction commit
268 if (myNestedNum != -1) // this nested transaction is owervritten
270 if (!myDoc->HasOpenCommand()) {
271 if (myNestedNum != -1) {
276 // returns false if delta is empty and no transaction was made
277 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand(); // && (myNestedNum == -1);
278 myTransactionsAfterSave++;
281 // finish for all subs
282 std::set<std::string>::iterator aSubIter = mySubs.begin();
283 for (; aSubIter != mySubs.end(); aSubIter++)
284 subDoc(*aSubIter)->finishOperation();
287 void Model_Document::abortOperation()
289 if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
290 // first compact all nested
292 // for nested it is undo and clear redos
295 myTransactionsAfterSave--;
296 myIsEmptyTr.erase(myTransactionsAfterSave);
298 if (myNestedNum == 0) // abort only high-level
300 myDoc->AbortCommand();
302 synchronizeFeatures(true);
303 // abort for all subs
304 std::set<std::string>::iterator aSubIter = mySubs.begin();
305 for (; aSubIter != mySubs.end(); aSubIter++)
306 subDoc(*aSubIter)->abortOperation();
309 bool Model_Document::isOperation()
311 // operation is opened for all documents: no need to check subs
312 return myDoc->HasOpenCommand() == Standard_True ;
315 bool Model_Document::isModified()
317 // is modified if at least one operation was commited and not undoed
318 return myTransactionsAfterSave > 0 || isOperation();
321 bool Model_Document::canUndo()
323 if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
324 && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
326 // check other subs contains operation that can be undoed
327 std::set<std::string>::iterator aSubIter = mySubs.begin();
328 for (; aSubIter != mySubs.end(); aSubIter++)
329 if (subDoc(*aSubIter)->canUndo())
334 void Model_Document::undo()
336 myTransactionsAfterSave--;
339 if (!myIsEmptyTr[myTransactionsAfterSave])
341 synchronizeFeatures(true);
343 std::set<std::string>::iterator aSubIter = mySubs.begin();
344 for (; aSubIter != mySubs.end(); aSubIter++)
345 subDoc(*aSubIter)->undo();
348 bool Model_Document::canRedo()
350 if (myDoc->GetAvailableRedos() > 0)
352 // check other subs contains operation that can be redoed
353 std::set<std::string>::iterator aSubIter = mySubs.begin();
354 for (; aSubIter != mySubs.end(); aSubIter++)
355 if (subDoc(*aSubIter)->canRedo())
360 void Model_Document::redo()
362 if (myNestedNum != -1)
364 if (!myIsEmptyTr[myTransactionsAfterSave])
366 myTransactionsAfterSave++;
367 synchronizeFeatures(true);
369 std::set<std::string>::iterator aSubIter = mySubs.begin();
370 for (; aSubIter != mySubs.end(); aSubIter++)
371 subDoc(*aSubIter)->redo();
374 /// Appenad to the array of references a new referenced label
375 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
377 Handle(TDataStd_ReferenceArray) aRefs;
378 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
379 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
380 aRefs->SetValue(0, theReferenced);
381 } else { // extend array by one more element
382 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
384 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
385 aNewArray->SetValue(a, aRefs->Value(a));
387 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
388 aRefs->SetInternalArray(aNewArray);
392 FeaturePtr Model_Document::addFeature(std::string theID)
394 TDF_Label anEmptyLab;
395 FeaturePtr anEmptyFeature;
396 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
397 boost::shared_ptr<Model_Document> aDocToAdd = boost::dynamic_pointer_cast<Model_Document>(
398 aFeature->documentToAdd());
400 TDF_Label aFeatureLab;
401 if (!aFeature->isAction()) { // do not add action to the data model
402 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
403 aFeatureLab = aFeaturesLab.NewChild();
404 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
405 // keep the feature ID to restore document later correctly
406 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
407 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
408 // store feature in the history of features array
409 if (aFeature->isInHistory()) {
410 AddToRefArray(aFeaturesLab, aFeatureLab);
413 if (!aFeature->isAction()) { // do not add action to the data model
414 // event: feature is added
415 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
416 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
422 /// Appenad to the array of references a new referenced label.
423 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
424 /// \returns the index of removed element
425 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
428 int aResult = -1; // no returned
429 Handle(TDataStd_ReferenceArray) aRefs;
430 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
431 if (aRefs->Length() == 1) { // just erase an array
432 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
433 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
436 } else { // reduce the array
437 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
439 int aCount = aRefs->Lower();
440 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
441 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
445 aNewArray->SetValue(aCount, aRefs->Value(a));
448 aRefs->SetInternalArray(aNewArray);
454 void Model_Document::removeFeature(FeaturePtr theFeature)
456 boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
457 TDF_Label aFeatureLabel = aData->label().Father();
458 if (myObjs.IsBound(aFeatureLabel))
459 myObjs.UnBind(aFeatureLabel);
461 return; // not found feature => do not remove
463 // erase all attributes under the label of feature
464 aFeatureLabel.ForgetAllAttributes();
465 // remove it from the references array
466 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
468 // event: feature is deleted
469 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
470 // results of this feature must be redisplayed
471 static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
472 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
473 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
474 for (; aRIter != aResults.cend(); aRIter++) {
475 boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
476 aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
477 ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
478 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), aRes->groupName());
482 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
484 if (myObjs.IsBound(theLabel))
485 return myObjs.Find(theLabel);
486 return FeaturePtr(); // not found
489 ObjectPtr Model_Document::object(TDF_Label theLabel)
491 // try feature by label
492 FeaturePtr aFeature = feature(theLabel);
494 return feature(theLabel);
495 TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
496 aFeature = feature(aFeatureLabel);
498 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
499 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
500 for (; aRIter != aResults.cend(); aRIter++) {
501 boost::shared_ptr<Model_Data> aResData = boost::dynamic_pointer_cast<Model_Data>(
503 if (aResData->label().Father().IsEqual(theLabel))
507 return FeaturePtr(); // not found
510 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
512 // just store sub-document identifier here to manage it later
513 if (mySubs.find(theDocID) == mySubs.end())
514 mySubs.insert(theDocID);
515 return Model_Application::getApplication()->getDocument(theDocID);
518 boost::shared_ptr<Model_Document> Model_Document::subDoc(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 boost::dynamic_pointer_cast<Model_Document>(
524 Model_Application::getApplication()->getDocument(theDocID));
527 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
528 const bool theHidden)
530 if (theGroupID == ModelAPI_Feature::group()) {
533 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
534 for (; aLabIter.More(); aLabIter.Next()) {
535 if (theIndex == anIndex) {
536 TDF_Label aFLabel = aLabIter.Value()->Label();
537 return feature(aFLabel);
542 Handle(TDataStd_ReferenceArray) aRefs;
543 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
545 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
547 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
548 return feature(aFeatureLabel);
551 // comment must be in any feature: it is kind
553 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
554 for (; aLabIter.More(); aLabIter.Next()) {
555 TDF_Label aFLabel = aLabIter.Value()->Label();
556 FeaturePtr aFeature = feature(aFLabel);
557 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
558 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
559 for (; aRIter != aResults.cend(); aRIter++) {
560 if ((theHidden || (*aRIter)->isInHistory()) && (*aRIter)->groupName() == theGroupID) {
561 if (anIndex == theIndex)
572 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
575 if (theGroupID == ModelAPI_Feature::group()) {
577 return myObjs.Size();
579 Handle(TDataStd_ReferenceArray) aRefs;
580 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
581 return aRefs->Length();
584 // comment must be in any feature: it is kind
585 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
586 for (; aLabIter.More(); aLabIter.Next()) {
587 TDF_Label aFLabel = aLabIter.Value()->Label();
588 FeaturePtr aFeature = feature(aFLabel);
589 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
590 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
591 for (; aRIter != aResults.cend(); aRIter++) {
592 if ((theHidden || (*aRIter)->isInHistory()) && (*aRIter)->groupName() == theGroupID) {
598 // group is not found
602 TDF_Label Model_Document::featuresLabel()
604 return myDoc->Main().FindChild(TAG_OBJECTS);
607 void Model_Document::setUniqueName(FeaturePtr theFeature)
609 if (!theFeature->data()->name().empty())
610 return; // not needed, name is already defined
611 std::string aName; // result
612 // first count all objects of such kind to start with index = count + 1
614 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
615 for (; aFIter.More(); aFIter.Next()) {
616 if (aFIter.Value()->getKind() == theFeature->getKind())
619 // generate candidate name
620 std::stringstream aNameStream;
621 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
622 aName = aNameStream.str();
623 // check this is unique, if not, increase index by 1
624 for (aFIter.Initialize(myObjs); aFIter.More();) {
625 FeaturePtr aFeature = aFIter.Value();
626 bool isSameName = aFeature->isInHistory() && aFeature->data()->name() == aName;
627 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
628 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
629 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
630 for (; aRIter != aResults.cend(); aRIter++) {
631 isSameName = (*aRIter)->isInHistory() && (*aRIter)->data()->name() == aName;
636 std::stringstream aNameStream;
637 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
638 aName = aNameStream.str();
639 // reinitialize iterator to make sure a new name is unique
640 aFIter.Initialize(myObjs);
644 theFeature->data()->setName(aName);
647 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
649 boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
651 boost::shared_ptr<Model_Data> aData(new Model_Data);
652 aData->setLabel(theLab.FindChild(theTag));
653 aData->setObject(theObj);
654 theObj->setDoc(aThis);
655 theObj->setData(aData);
656 FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
658 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
659 aFeature->initAttributes();
663 void Model_Document::synchronizeFeatures(const bool theMarkUpdated)
665 boost::shared_ptr<ModelAPI_Document> aThis =
666 Model_Application::getApplication()->getDocument(myID);
667 // after all updates, sends a message that groups of features were created or updated
668 boost::static_pointer_cast<Model_Session>(Model_Session::get())
669 ->setCheckTransactions(false);
670 Events_Loop* aLoop = Events_Loop::loop();
671 aLoop->activateFlushes(false);
673 // update all objects by checking are they of labels or not
674 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
675 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
676 for (; aLabIter.More(); aLabIter.Next()) {
677 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
678 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
680 FeaturePtr aNewObj = ModelAPI_Session::get()->createFeature(
681 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
683 if (!aNewObj) { // somethig is wrong, most probably, the opened document has invalid structure
684 Events_Error::send("Invalid type of object in the document");
685 aLabIter.Value()->Label().ForgetAllAttributes();
688 // this must be before "setData" to redo the sketch line correctly
689 myObjs.Bind(aFeatureLabel, aNewObj);
690 aNewFeatures.insert(aNewObj);
691 initData(aNewObj, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
693 // event: model is updated
694 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
695 ModelAPI_EventCreator::get()->sendUpdated(aNewObj, anEvent);
697 // update results of the appeared feature
698 updateResults(aNewObj);
699 } else { // nothing is changed, both iterators are incremented
700 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
701 aKeptFeatures.insert(aFeature);
702 if (theMarkUpdated) {
703 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
704 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
706 updateResults(aFeature);
709 // execute new features to restore results: after features creation to make all references valid
710 /*std::set<FeaturePtr>::iterator aNewIter = aNewFeatures.begin();
711 for(; aNewIter != aNewFeatures.end(); aNewIter++) {
712 (*aNewIter)->execute();
714 // check all features are checked: if not => it was removed
715 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
716 while (aFIter.More()) {
717 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
718 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
719 FeaturePtr aFeature = aFIter.Value();
720 TDF_Label aLab = aFIter.Key();
723 // event: model is updated
724 if (aFeature->isInHistory()) {
725 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
727 // results of this feature must be redisplayed (hided)
728 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
729 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
730 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
731 for (; aRIter != aResults.cend(); aRIter++) {
732 boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
733 //aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
734 ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
735 ModelAPI_EventCreator::get()->sendDeleted(aThis, aRes->groupName());
737 // redisplay also removed feature (used for sketch and AISObject)
738 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
743 myExecuteFeatures = false;
744 aLoop->activateFlushes(true);
746 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
747 if (theMarkUpdated) {
748 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
750 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
751 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
752 boost::static_pointer_cast<Model_Session>(Model_Session::get())
753 ->setCheckTransactions(true);
754 myExecuteFeatures = true;
757 TDF_Label Model_Document::resultLabel(
758 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
760 const boost::shared_ptr<Model_Data>& aData =
761 boost::dynamic_pointer_cast<Model_Data>(theFeatureData);
762 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
765 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
766 boost::shared_ptr<ModelAPI_Result> theResult,
767 const int theResultIndex)
769 boost::shared_ptr<ModelAPI_Document> aThis =
770 Model_Application::getApplication()->getDocument(myID);
771 theResult->setDoc(aThis);
772 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
773 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
774 theResult->data()->setName(theFeatureData->name());
778 static const Standard_GUID ID_CONSTRUCTION("b59fa408-8ab1-42b8-980c-af5adeebe7e4");
779 static const Standard_GUID ID_BODY("c1148e9a-9b17-4e9c-9160-18e918fd0013");
780 static const Standard_GUID ID_PART("1b3319b9-3e0a-4298-a1dc-3fb5aaf9be59");
782 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
783 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
785 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
786 TDataStd_UAttribute::Set(aLab, ID_CONSTRUCTION);
787 ObjectPtr anOldObject = object(aLab);
788 boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
790 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
793 aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
794 storeResult(theFeatureData, aResult, theIndex);
799 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
800 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
802 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
803 TDataStd_UAttribute::Set(aLab, ID_BODY);
804 ObjectPtr anOldObject = object(aLab);
805 boost::shared_ptr<ModelAPI_ResultBody> aResult;
807 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
810 aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
811 storeResult(theFeatureData, aResult, theIndex);
816 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
817 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
819 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
820 TDataStd_UAttribute::Set(aLab, ID_PART);
821 ObjectPtr anOldObject = object(aLab);
822 boost::shared_ptr<ModelAPI_ResultPart> aResult;
824 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
827 aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
828 storeResult(theFeatureData, aResult, theIndex);
833 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
834 const boost::shared_ptr<ModelAPI_Result>& theResult)
836 boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
838 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
839 return feature(aFeatureLab);
844 void Model_Document::updateResults(FeaturePtr theFeature)
846 // for not persistent is will be done by parametric updater automatically
847 if (!theFeature->isPersistentResult()) return;
848 // check the existing results and remove them if there is nothing on the label
849 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
850 while(aResIter != theFeature->results().cend()) {
851 ResultBodyPtr aBody = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
853 if (!aBody->data()->isValid()) {
854 // found a disappeared result => remove it
855 theFeature->removeResult(aBody);
856 // start iterate from beginning because iterator is corrupted by removing
857 aResIter = theFeature->results().cbegin();
863 // check that results are presented on all labels
864 int aResSize = theFeature->results().size();
865 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
866 for(; aLabIter.More(); aLabIter.Next()) {
867 // here must be GUID of the feature
868 int aResIndex = aLabIter.Value().Tag() - 1;
870 if (aResSize <= aResIndex) {
871 TDF_Label anArgLab = aLabIter.Value();
872 if (anArgLab.IsAttribute(ID_BODY)) {
873 aNewBody = createBody(theFeature->data(), aResIndex);
874 } else if (anArgLab.IsAttribute(ID_PART)) {
875 aNewBody = createPart(theFeature->data(), aResIndex);
876 } else if (!anArgLab.IsAttribute(ID_CONSTRUCTION) && anArgLab.FindChild(1).HasAttribute()) {
877 Events_Error::send("Unknown type of result is found in the document");
880 theFeature->setResult(aNewBody, aResIndex);
886 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
888 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
891 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
893 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);