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);
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] = false;
228 myTransactionsAfterSave++;
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 void 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();
255 void Model_Document::finishOperation()
257 // just to be sure that everybody knows that changes were performed
259 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
260 boost::static_pointer_cast<Model_Session>(Model_Session::get())
261 ->setCheckTransactions(false); // for nested transaction commit
262 Events_Loop* aLoop = Events_Loop::loop();
263 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
264 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
265 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
266 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
267 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
268 boost::static_pointer_cast<Model_Session>(Model_Session::get())
269 ->setCheckTransactions(true); // for nested transaction commit
271 if (myNestedNum != -1) // this nested transaction is owervritten
273 if (!myDoc->HasOpenCommand()) {
274 if (myNestedNum != -1) {
279 // returns false if delta is empty and no transaction was made
280 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand(); // && (myNestedNum == -1);
281 myTransactionsAfterSave++;
284 // finish for all subs
285 std::set<std::string>::iterator aSubIter = mySubs.begin();
286 for (; aSubIter != mySubs.end(); aSubIter++)
287 subDoc(*aSubIter)->finishOperation();
290 void Model_Document::abortOperation()
292 if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
293 // first compact all nested
295 // for nested it is undo and clear redos
298 myTransactionsAfterSave--;
299 myIsEmptyTr.erase(myTransactionsAfterSave);
301 if (myNestedNum == 0) // abort only high-level
303 myDoc->AbortCommand();
305 synchronizeFeatures(true);
306 // abort for all subs
307 std::set<std::string>::iterator aSubIter = mySubs.begin();
308 for (; aSubIter != mySubs.end(); aSubIter++)
309 subDoc(*aSubIter)->abortOperation();
312 bool Model_Document::isOperation()
314 // operation is opened for all documents: no need to check subs
315 return myDoc->HasOpenCommand() == Standard_True ;
318 bool Model_Document::isModified()
320 // is modified if at least one operation was commited and not undoed
321 return myTransactionsAfterSave > 0 || isOperation();
324 bool Model_Document::canUndo()
326 if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
327 && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
329 // check other subs contains operation that can be undoed
330 std::set<std::string>::iterator aSubIter = mySubs.begin();
331 for (; aSubIter != mySubs.end(); aSubIter++)
332 if (subDoc(*aSubIter)->canUndo())
337 void Model_Document::undo()
339 myTransactionsAfterSave--;
342 if (!myIsEmptyTr[myTransactionsAfterSave])
344 synchronizeFeatures(true);
346 std::set<std::string>::iterator aSubIter = mySubs.begin();
347 for (; aSubIter != mySubs.end(); aSubIter++)
348 subDoc(*aSubIter)->undo();
351 bool Model_Document::canRedo()
353 if (myDoc->GetAvailableRedos() > 0)
355 // check other subs contains operation that can be redoed
356 std::set<std::string>::iterator aSubIter = mySubs.begin();
357 for (; aSubIter != mySubs.end(); aSubIter++)
358 if (subDoc(*aSubIter)->canRedo())
363 void Model_Document::redo()
365 if (myNestedNum != -1)
367 if (!myIsEmptyTr[myTransactionsAfterSave])
369 myTransactionsAfterSave++;
370 synchronizeFeatures(true);
372 std::set<std::string>::iterator aSubIter = mySubs.begin();
373 for (; aSubIter != mySubs.end(); aSubIter++)
374 subDoc(*aSubIter)->redo();
377 /// Appenad to the array of references a new referenced label
378 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
380 Handle(TDataStd_ReferenceArray) aRefs;
381 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
382 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
383 aRefs->SetValue(0, theReferenced);
384 } else { // extend array by one more element
385 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
387 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
388 aNewArray->SetValue(a, aRefs->Value(a));
390 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
391 aRefs->SetInternalArray(aNewArray);
395 FeaturePtr Model_Document::addFeature(std::string theID)
397 TDF_Label anEmptyLab;
398 FeaturePtr anEmptyFeature;
399 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
400 boost::shared_ptr<Model_Document> aDocToAdd = boost::dynamic_pointer_cast<Model_Document>(
401 aFeature->documentToAdd());
403 TDF_Label aFeatureLab;
404 if (!aFeature->isAction()) { // do not add action to the data model
405 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
406 aFeatureLab = aFeaturesLab.NewChild();
407 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
408 // keep the feature ID to restore document later correctly
409 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
410 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
411 // store feature in the history of features array
412 if (aFeature->isInHistory()) {
413 AddToRefArray(aFeaturesLab, aFeatureLab);
416 if (!aFeature->isAction()) { // do not add action to the data model
417 // event: feature is added
418 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
419 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
420 } else { // feature must be executed
421 // no creation event => updater not working, problem with remove part
428 /// Appenad to the array of references a new referenced label.
429 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
430 /// \returns the index of removed element
431 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
434 int aResult = -1; // no returned
435 Handle(TDataStd_ReferenceArray) aRefs;
436 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
437 if (aRefs->Length() == 1) { // just erase an array
438 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
439 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
442 } else { // reduce the array
443 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
445 int aCount = aRefs->Lower();
446 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
447 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
451 aNewArray->SetValue(aCount, aRefs->Value(a));
454 aRefs->SetInternalArray(aNewArray);
460 void Model_Document::removeFeature(FeaturePtr theFeature)
462 boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
463 TDF_Label aFeatureLabel = aData->label().Father();
464 if (myObjs.IsBound(aFeatureLabel))
465 myObjs.UnBind(aFeatureLabel);
467 return; // not found feature => do not remove
469 // erase all attributes under the label of feature
470 aFeatureLabel.ForgetAllAttributes();
471 // remove it from the references array
472 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
474 // event: feature is deleted
475 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
476 // results of this feature must be redisplayed
477 static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
478 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
479 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
480 for (; aRIter != aResults.cend(); aRIter++) {
481 boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
482 aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
483 ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
484 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), aRes->groupName());
488 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
490 if (myObjs.IsBound(theLabel))
491 return myObjs.Find(theLabel);
492 return FeaturePtr(); // not found
495 ObjectPtr Model_Document::object(TDF_Label theLabel)
497 // try feature by label
498 FeaturePtr aFeature = feature(theLabel);
500 return feature(theLabel);
501 TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
502 aFeature = feature(aFeatureLabel);
504 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
505 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
506 for (; aRIter != aResults.cend(); aRIter++) {
507 boost::shared_ptr<Model_Data> aResData = boost::dynamic_pointer_cast<Model_Data>(
509 if (aResData->label().Father().IsEqual(theLabel))
513 return FeaturePtr(); // not found
516 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
518 // just store sub-document identifier here to manage it later
519 if (mySubs.find(theDocID) == mySubs.end())
520 mySubs.insert(theDocID);
521 return Model_Application::getApplication()->getDocument(theDocID);
524 boost::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
526 // just store sub-document identifier here to manage it later
527 if (mySubs.find(theDocID) == mySubs.end())
528 mySubs.insert(theDocID);
529 return boost::dynamic_pointer_cast<Model_Document>(
530 Model_Application::getApplication()->getDocument(theDocID));
533 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
534 const bool theHidden)
536 if (theGroupID == ModelAPI_Feature::group()) {
539 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
540 for (; aLabIter.More(); aLabIter.Next()) {
541 if (theIndex == anIndex) {
542 TDF_Label aFLabel = aLabIter.Value()->Label();
543 return feature(aFLabel);
548 Handle(TDataStd_ReferenceArray) aRefs;
549 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
551 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
553 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
554 return feature(aFeatureLabel);
557 // comment must be in any feature: it is kind
559 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
560 for (; aLabIter.More(); aLabIter.Next()) {
561 TDF_Label aFLabel = aLabIter.Value()->Label();
562 FeaturePtr aFeature = feature(aFLabel);
563 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
564 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
565 for (; aRIter != aResults.cend(); aRIter++) {
566 if ((theHidden || (*aRIter)->isInHistory()) && (*aRIter)->groupName() == theGroupID) {
567 if (anIndex == theIndex)
578 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
581 if (theGroupID == ModelAPI_Feature::group()) {
583 return myObjs.Size();
585 Handle(TDataStd_ReferenceArray) aRefs;
586 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
587 return aRefs->Length();
590 // comment must be in any feature: it is kind
591 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
592 for (; aLabIter.More(); aLabIter.Next()) {
593 TDF_Label aFLabel = aLabIter.Value()->Label();
594 FeaturePtr aFeature = feature(aFLabel);
595 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
596 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
597 for (; aRIter != aResults.cend(); aRIter++) {
598 if ((theHidden || (*aRIter)->isInHistory()) && (*aRIter)->groupName() == theGroupID) {
604 // group is not found
608 TDF_Label Model_Document::featuresLabel()
610 return myDoc->Main().FindChild(TAG_OBJECTS);
613 void Model_Document::setUniqueName(FeaturePtr theFeature)
615 if (!theFeature->data()->name().empty())
616 return; // not needed, name is already defined
617 std::string aName; // result
618 // first count all objects of such kind to start with index = count + 1
620 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
621 for (; aFIter.More(); aFIter.Next()) {
622 if (aFIter.Value()->getKind() == theFeature->getKind())
625 // generate candidate name
626 std::stringstream aNameStream;
627 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
628 aName = aNameStream.str();
629 // check this is unique, if not, increase index by 1
630 for (aFIter.Initialize(myObjs); aFIter.More();) {
631 FeaturePtr aFeature = aFIter.Value();
632 bool isSameName = aFeature->isInHistory() && aFeature->data()->name() == aName;
633 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
634 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
635 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
636 for (; aRIter != aResults.cend(); aRIter++) {
637 isSameName = (*aRIter)->isInHistory() && (*aRIter)->data()->name() == aName;
642 std::stringstream aNameStream;
643 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
644 aName = aNameStream.str();
645 // reinitialize iterator to make sure a new name is unique
646 aFIter.Initialize(myObjs);
650 theFeature->data()->setName(aName);
653 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
655 boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
657 boost::shared_ptr<Model_Data> aData(new Model_Data);
658 aData->setLabel(theLab.FindChild(theTag));
659 aData->setObject(theObj);
660 theObj->setDoc(aThis);
661 theObj->setData(aData);
662 FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
664 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
665 aFeature->initAttributes();
669 void Model_Document::synchronizeFeatures(const bool theMarkUpdated)
671 boost::shared_ptr<ModelAPI_Document> aThis =
672 Model_Application::getApplication()->getDocument(myID);
673 // after all updates, sends a message that groups of features were created or updated
674 boost::static_pointer_cast<Model_Session>(Model_Session::get())
675 ->setCheckTransactions(false);
676 Events_Loop* aLoop = Events_Loop::loop();
677 aLoop->activateFlushes(false);
679 // update all objects by checking are they of labels or not
680 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
681 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
682 for (; aLabIter.More(); aLabIter.Next()) {
683 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
684 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
686 FeaturePtr aNewObj = ModelAPI_Session::get()->createFeature(
687 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
689 if (!aNewObj) { // somethig is wrong, most probably, the opened document has invalid structure
690 Events_Error::send("Invalid type of object in the document");
691 aLabIter.Value()->Label().ForgetAllAttributes();
694 // this must be before "setData" to redo the sketch line correctly
695 myObjs.Bind(aFeatureLabel, aNewObj);
696 aNewFeatures.insert(aNewObj);
697 initData(aNewObj, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
699 // event: model is updated
700 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
701 ModelAPI_EventCreator::get()->sendUpdated(aNewObj, anEvent);
703 // update results of the appeared feature
704 updateResults(aNewObj);
705 } else { // nothing is changed, both iterators are incremented
706 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
707 aKeptFeatures.insert(aFeature);
708 if (theMarkUpdated) {
709 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
710 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
712 updateResults(aFeature);
715 // execute new features to restore results: after features creation to make all references valid
716 /*std::set<FeaturePtr>::iterator aNewIter = aNewFeatures.begin();
717 for(; aNewIter != aNewFeatures.end(); aNewIter++) {
718 (*aNewIter)->execute();
720 // check all features are checked: if not => it was removed
721 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
722 while (aFIter.More()) {
723 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
724 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
725 FeaturePtr aFeature = aFIter.Value();
726 TDF_Label aLab = aFIter.Key();
729 // event: model is updated
730 if (aFeature->isInHistory()) {
731 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
733 // results of this feature must be redisplayed (hided)
734 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
735 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
736 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
737 for (; aRIter != aResults.cend(); aRIter++) {
738 boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
739 //aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
740 ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
741 ModelAPI_EventCreator::get()->sendDeleted(aThis, aRes->groupName());
743 // redisplay also removed feature (used for sketch and AISObject)
744 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
749 myExecuteFeatures = false;
750 aLoop->activateFlushes(true);
752 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
753 if (theMarkUpdated) {
754 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
756 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
757 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
758 boost::static_pointer_cast<Model_Session>(Model_Session::get())
759 ->setCheckTransactions(true);
760 myExecuteFeatures = true;
763 TDF_Label Model_Document::resultLabel(
764 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
766 const boost::shared_ptr<Model_Data>& aData =
767 boost::dynamic_pointer_cast<Model_Data>(theFeatureData);
768 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
771 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
772 boost::shared_ptr<ModelAPI_Result> theResult,
773 const int theResultIndex)
775 boost::shared_ptr<ModelAPI_Document> aThis =
776 Model_Application::getApplication()->getDocument(myID);
777 theResult->setDoc(aThis);
778 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
779 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
780 theResult->data()->setName(theFeatureData->name());
784 static const Standard_GUID ID_CONSTRUCTION("b59fa408-8ab1-42b8-980c-af5adeebe7e4");
785 static const Standard_GUID ID_BODY("c1148e9a-9b17-4e9c-9160-18e918fd0013");
786 static const Standard_GUID ID_PART("1b3319b9-3e0a-4298-a1dc-3fb5aaf9be59");
788 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
789 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
791 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
792 TDataStd_UAttribute::Set(aLab, ID_CONSTRUCTION);
793 ObjectPtr anOldObject = object(aLab);
794 boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
796 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
799 aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
800 storeResult(theFeatureData, aResult, theIndex);
805 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
806 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
808 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
809 TDataStd_UAttribute::Set(aLab, ID_BODY);
810 ObjectPtr anOldObject = object(aLab);
811 boost::shared_ptr<ModelAPI_ResultBody> aResult;
813 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
816 aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
817 storeResult(theFeatureData, aResult, theIndex);
822 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
823 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
825 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
826 TDataStd_UAttribute::Set(aLab, ID_PART);
827 ObjectPtr anOldObject = object(aLab);
828 boost::shared_ptr<ModelAPI_ResultPart> aResult;
830 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
833 aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
834 storeResult(theFeatureData, aResult, theIndex);
839 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
840 const boost::shared_ptr<ModelAPI_Result>& theResult)
842 boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
844 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
845 return feature(aFeatureLab);
850 void Model_Document::updateResults(FeaturePtr theFeature)
852 // for not persistent is will be done by parametric updater automatically
853 if (!theFeature->isPersistentResult()) return;
854 // check the existing results and remove them if there is nothing on the label
855 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
856 while(aResIter != theFeature->results().cend()) {
857 ResultBodyPtr aBody = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
859 if (!aBody->data()->isValid()) {
860 // found a disappeared result => remove it
861 theFeature->removeResult(aBody);
862 // start iterate from beginning because iterator is corrupted by removing
863 aResIter = theFeature->results().cbegin();
869 // check that results are presented on all labels
870 int aResSize = theFeature->results().size();
871 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
872 for(; aLabIter.More(); aLabIter.Next()) {
873 // here must be GUID of the feature
874 int aResIndex = aLabIter.Value().Tag() - 1;
876 if (aResSize <= aResIndex) {
877 TDF_Label anArgLab = aLabIter.Value();
878 if (anArgLab.IsAttribute(ID_BODY)) {
879 aNewBody = createBody(theFeature->data(), aResIndex);
880 } else if (anArgLab.IsAttribute(ID_PART)) {
881 aNewBody = createPart(theFeature->data(), aResIndex);
882 } else if (!anArgLab.IsAttribute(ID_CONSTRUCTION) && anArgLab.FindChild(1).HasAttribute()) {
883 Events_Error::send("Unknown type of result is found in the document");
886 theFeature->setResult(aNewBody, aResIndex);
892 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
894 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
897 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
899 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);