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 <ModelAPI_Validator.h>
14 #include <Events_Loop.h>
15 #include <Events_Error.h>
17 #include <TDataStd_Integer.hxx>
18 #include <TDataStd_Comment.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 // to have something in the document and avoid empty doc open/save problem
57 // in transaction for nesting correct working
59 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
60 myDoc->CommitCommand();
63 /// Returns the file name of this document by the nameof directory and identifuer of a document
64 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
66 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
67 // remove end-separators
68 while(aPath.Length() && (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
69 aPath.Remove(aPath.Length());
71 aPath += theID.c_str();
72 aPath += ".cbf"; // standard binary file extension
76 bool Model_Document::load(const char* theFileName)
78 Handle(Model_Application) anApp = Model_Application::getApplication();
79 if (this == Model_Session::get()->moduleDocument().get()) {
80 anApp->setLoadPath(theFileName);
82 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
83 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
85 aStatus = anApp->Open(aPath, myDoc);
86 } catch (Standard_Failure) {
87 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
89 std::string("Exception in opening of document: ") + aFail->GetMessageString());
92 bool isError = aStatus != PCDM_RS_OK;
95 case PCDM_RS_UnknownDocument:
96 Events_Error::send(std::string("Can not open document: unknown format"));
98 case PCDM_RS_AlreadyRetrieved:
99 Events_Error::send(std::string("Can not open document: already opened"));
101 case PCDM_RS_AlreadyRetrievedAndModified:
103 std::string("Can not open document: already opened and modified"));
105 case PCDM_RS_NoDriver:
106 Events_Error::send(std::string("Can not open document: driver library is not found"));
108 case PCDM_RS_UnknownFileDriver:
109 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
111 case PCDM_RS_OpenError:
112 Events_Error::send(std::string("Can not open document: file open error"));
114 case PCDM_RS_NoVersion:
115 Events_Error::send(std::string("Can not open document: invalid version"));
117 case PCDM_RS_NoModel:
118 Events_Error::send(std::string("Can not open document: no data model"));
120 case PCDM_RS_NoDocument:
121 Events_Error::send(std::string("Can not open document: no document inside"));
123 case PCDM_RS_FormatFailure:
124 Events_Error::send(std::string("Can not open document: format failure"));
126 case PCDM_RS_TypeNotFoundInSchema:
127 Events_Error::send(std::string("Can not open document: invalid object"));
129 case PCDM_RS_UnrecognizedFileFormat:
130 Events_Error::send(std::string("Can not open document: unrecognized file format"));
132 case PCDM_RS_MakeFailure:
133 Events_Error::send(std::string("Can not open document: make failure"));
135 case PCDM_RS_PermissionDenied:
136 Events_Error::send(std::string("Can not open document: permission denied"));
138 case PCDM_RS_DriverFailure:
139 Events_Error::send(std::string("Can not open document: driver failure"));
142 Events_Error::send(std::string("Can not open document: unknown error"));
147 myDoc->SetUndoLimit(UNDO_LIMIT);
148 // to avoid the problem that feature is created in the current, not this, document
149 Model_Session::get()->setActiveDocument(anApp->getDocument(myID));
150 synchronizeFeatures(false, true);
155 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
157 // create a directory in the root document if it is not yet exist
158 if (this == Model_Session::get()->moduleDocument().get()) {
160 CreateDirectory(theFileName, NULL);
162 mkdir(theFileName, 0x1ff);
165 // filename in the dir is id of document inside of the given directory
166 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
167 PCDM_StoreStatus aStatus;
169 aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
170 } catch (Standard_Failure) {
171 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
173 std::string("Exception in saving of document: ") + aFail->GetMessageString());
176 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
179 case PCDM_SS_DriverFailure:
180 Events_Error::send(std::string("Can not save document: save driver-library failure"));
182 case PCDM_SS_WriteFailure:
183 Events_Error::send(std::string("Can not save document: file writing failure"));
185 case PCDM_SS_Failure:
187 Events_Error::send(std::string("Can not save document"));
191 myTransactionsAfterSave = 0;
192 if (isDone) { // save also sub-documents if any
193 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
194 std::set<std::string>::iterator aSubIter = mySubs.begin();
195 for (; aSubIter != mySubs.end() && isDone; aSubIter++) {
196 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
202 void Model_Document::close()
204 boost::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
205 if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
206 aPM->setActiveDocument(aPM->moduleDocument());
209 std::set<std::string>::iterator aSubIter = mySubs.begin();
210 for (; aSubIter != mySubs.end(); aSubIter++)
211 subDoc(*aSubIter)->close();
214 /* do not close because it can be undoed
215 if (myDoc->CanClose() == CDM_CCS_OK)
217 Model_Application::getApplication()->deleteDocument(myID);
221 void Model_Document::startOperation()
223 if (myDoc->HasOpenCommand()) { // start of nested command
224 if (myNestedNum == -1) {
226 myDoc->InitDeltaCompaction();
228 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();
229 myTransactionsAfterSave++;
230 myDoc->OpenCommand();
231 } else { // start the simple command
234 // new command for all subs
235 std::set<std::string>::iterator aSubIter = mySubs.begin();
236 for (; aSubIter != mySubs.end(); aSubIter++)
237 subDoc(*aSubIter)->startOperation();
240 bool Model_Document::compactNested()
242 bool allWasEmpty = true;
243 while (myNestedNum != -1) {
244 myTransactionsAfterSave--;
245 if (!myIsEmptyTr[myTransactionsAfterSave]) {
248 myIsEmptyTr.erase(myTransactionsAfterSave);
251 myIsEmptyTr[myTransactionsAfterSave] = allWasEmpty;
252 myTransactionsAfterSave++;
253 myDoc->PerformDeltaCompaction();
257 void Model_Document::finishOperation()
259 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
260 std::set<std::string>::iterator aSubIter = mySubs.begin();
261 for (; aSubIter != mySubs.end(); aSubIter++)
262 subDoc(*aSubIter)->finishOperation();
264 // just to be sure that everybody knows that changes were performed
265 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
266 boost::static_pointer_cast<Model_Session>(Model_Session::get())
267 ->setCheckTransactions(false); // for nested transaction commit
268 synchronizeBackRefs();
269 Events_Loop* aLoop = Events_Loop::loop();
270 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
271 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
272 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
273 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
274 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
275 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
276 boost::static_pointer_cast<Model_Session>(Model_Session::get())
277 ->setCheckTransactions(true); // for nested transaction commit
279 if (myNestedNum != -1) // this nested transaction is owervritten
281 if (!myDoc->HasOpenCommand()) {
282 if (myNestedNum != -1) {
287 // returns false if delta is empty and no transaction was made
288 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand(); // && (myNestedNum == -1);
289 myTransactionsAfterSave++;
294 void Model_Document::abortOperation()
296 if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
297 // first compact all nested
298 if (compactNested()) {
299 // for nested it is undo and clear redos
303 myTransactionsAfterSave--;
304 myIsEmptyTr.erase(myTransactionsAfterSave);
306 if (myNestedNum == 0) // abort only high-level
308 myDoc->AbortCommand();
310 synchronizeFeatures(true, false); // references were not changed since transaction start
311 // abort for all subs
312 std::set<std::string>::iterator aSubIter = mySubs.begin();
313 for (; aSubIter != mySubs.end(); aSubIter++)
314 subDoc(*aSubIter)->abortOperation();
317 bool Model_Document::isOperation()
319 // operation is opened for all documents: no need to check subs
320 return myDoc->HasOpenCommand() == Standard_True ;
323 bool Model_Document::isModified()
325 // is modified if at least one operation was commited and not undoed
326 return myTransactionsAfterSave > 0 || isOperation();
329 bool Model_Document::canUndo()
331 if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
332 && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
334 // check other subs contains operation that can be undoed
335 std::set<std::string>::iterator aSubIter = mySubs.begin();
336 for (; aSubIter != mySubs.end(); aSubIter++)
337 if (subDoc(*aSubIter)->canUndo())
342 void Model_Document::undo()
344 myTransactionsAfterSave--;
347 if (!myIsEmptyTr[myTransactionsAfterSave])
349 synchronizeFeatures(true, true);
351 std::set<std::string>::iterator aSubIter = mySubs.begin();
352 for (; aSubIter != mySubs.end(); aSubIter++)
353 subDoc(*aSubIter)->undo();
356 bool Model_Document::canRedo()
358 if (myDoc->GetAvailableRedos() > 0)
360 // check other subs contains operation that can be redoed
361 std::set<std::string>::iterator aSubIter = mySubs.begin();
362 for (; aSubIter != mySubs.end(); aSubIter++)
363 if (subDoc(*aSubIter)->canRedo())
368 void Model_Document::redo()
370 if (myNestedNum != -1)
372 if (!myIsEmptyTr[myTransactionsAfterSave])
374 myTransactionsAfterSave++;
375 synchronizeFeatures(true, true);
377 std::set<std::string>::iterator aSubIter = mySubs.begin();
378 for (; aSubIter != mySubs.end(); aSubIter++)
379 subDoc(*aSubIter)->redo();
382 /// Appenad to the array of references a new referenced label
383 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
385 Handle(TDataStd_ReferenceArray) aRefs;
386 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
387 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
388 aRefs->SetValue(0, theReferenced);
389 } else { // extend array by one more element
390 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
392 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
393 aNewArray->SetValue(a, aRefs->Value(a));
395 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
396 aRefs->SetInternalArray(aNewArray);
400 FeaturePtr Model_Document::addFeature(std::string theID)
402 TDF_Label anEmptyLab;
403 FeaturePtr anEmptyFeature;
404 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
407 boost::shared_ptr<Model_Document> aDocToAdd = boost::dynamic_pointer_cast<Model_Document>(
408 aFeature->documentToAdd());
410 TDF_Label aFeatureLab;
411 if (!aFeature->isAction()) { // do not add action to the data model
412 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
413 aFeatureLab = aFeaturesLab.NewChild();
414 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
415 // keep the feature ID to restore document later correctly
416 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
417 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
418 // store feature in the history of features array
419 if (aFeature->isInHistory()) {
420 AddToRefArray(aFeaturesLab, aFeatureLab);
423 if (!aFeature->isAction()) { // do not add action to the data model
424 // event: feature is added
425 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
426 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
427 } else { // feature must be executed
428 // no creation event => updater not working, problem with remove part
435 /// Appenad to the array of references a new referenced label.
436 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
437 /// \returns the index of removed element
438 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
441 int aResult = -1; // no returned
442 Handle(TDataStd_ReferenceArray) aRefs;
443 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
444 if (aRefs->Length() == 1) { // just erase an array
445 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
446 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
449 } else { // reduce the array
450 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
452 int aCount = aRefs->Lower();
453 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
454 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
458 aNewArray->SetValue(aCount, aRefs->Value(a));
461 aRefs->SetInternalArray(aNewArray);
467 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
470 // check the feature: it must have no depended objects on it
471 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
472 for(; aResIter != theFeature->results().cend(); aResIter++) {
473 boost::shared_ptr<Model_Data> aData =
474 boost::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
475 if (aData && !aData->refsToMe().empty()) {
477 "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
483 boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
484 TDF_Label aFeatureLabel = aData->label().Father();
485 if (myObjs.IsBound(aFeatureLabel))
486 myObjs.UnBind(aFeatureLabel);
488 return; // not found feature => do not remove
491 // erase all attributes under the label of feature
492 aFeatureLabel.ForgetAllAttributes();
493 // remove it from the references array
494 if (theFeature->isInHistory()) {
495 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
497 // event: feature is deleted
498 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
501 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
503 if (myObjs.IsBound(theLabel))
504 return myObjs.Find(theLabel);
505 return FeaturePtr(); // not found
508 ObjectPtr Model_Document::object(TDF_Label theLabel)
510 // try feature by label
511 FeaturePtr aFeature = feature(theLabel);
513 return feature(theLabel);
514 TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
515 aFeature = feature(aFeatureLabel);
517 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
518 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
519 for (; aRIter != aResults.cend(); aRIter++) {
520 boost::shared_ptr<Model_Data> aResData = boost::dynamic_pointer_cast<Model_Data>(
522 if (aResData->label().Father().IsEqual(theLabel))
526 return FeaturePtr(); // not found
529 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
531 // just store sub-document identifier here to manage it later
532 if (mySubs.find(theDocID) == mySubs.end())
533 mySubs.insert(theDocID);
534 return Model_Application::getApplication()->getDocument(theDocID);
537 boost::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
539 // just store sub-document identifier here to manage it later
540 if (mySubs.find(theDocID) == mySubs.end())
541 mySubs.insert(theDocID);
542 return boost::dynamic_pointer_cast<Model_Document>(
543 Model_Application::getApplication()->getDocument(theDocID));
546 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
547 const bool theHidden)
549 if (theGroupID == ModelAPI_Feature::group()) {
552 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
553 for (; aLabIter.More(); aLabIter.Next()) {
554 if (theIndex == anIndex) {
555 TDF_Label aFLabel = aLabIter.Value()->Label();
556 return feature(aFLabel);
561 Handle(TDataStd_ReferenceArray) aRefs;
562 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
564 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
566 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
567 return feature(aFeatureLabel);
570 // comment must be in any feature: it is kind
572 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
573 for (; aLabIter.More(); aLabIter.Next()) {
574 TDF_Label aFLabel = aLabIter.Value()->Label();
575 FeaturePtr aFeature = feature(aFLabel);
576 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
577 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
578 for (; aRIter != aResults.cend(); aRIter++) {
579 if ((*aRIter)->groupName() != theGroupID) continue;
580 bool isIn = theHidden && (*aRIter)->isInHistory();
581 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
582 isIn = !(*aRIter)->isConcealed();
585 if (anIndex == theIndex)
596 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
599 if (theGroupID == ModelAPI_Feature::group()) {
601 return myObjs.Size();
603 Handle(TDataStd_ReferenceArray) aRefs;
604 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
605 return aRefs->Length();
608 // comment must be in any feature: it is kind
609 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
610 for (; aLabIter.More(); aLabIter.Next()) {
611 TDF_Label aFLabel = aLabIter.Value()->Label();
612 FeaturePtr aFeature = feature(aFLabel);
613 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
614 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
615 for (; aRIter != aResults.cend(); aRIter++) {
616 if ((*aRIter)->groupName() != theGroupID) continue;
617 bool isIn = theHidden;
618 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
619 isIn = !(*aRIter)->isConcealed();
626 // group is not found
630 TDF_Label Model_Document::featuresLabel()
632 return myDoc->Main().FindChild(TAG_OBJECTS);
635 void Model_Document::setUniqueName(FeaturePtr theFeature)
637 if (!theFeature->data()->name().empty())
638 return; // not needed, name is already defined
639 std::string aName; // result
640 // first count all objects of such kind to start with index = count + 1
642 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
643 for (; aFIter.More(); aFIter.Next()) {
644 if (aFIter.Value()->getKind() == theFeature->getKind())
647 // generate candidate name
648 std::stringstream aNameStream;
649 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
650 aName = aNameStream.str();
651 // check this is unique, if not, increase index by 1
652 for (aFIter.Initialize(myObjs); aFIter.More();) {
653 FeaturePtr aFeature = aFIter.Value();
654 bool isSameName = aFeature->data()->name() == aName;
655 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
656 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
657 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
658 for (; aRIter != aResults.cend(); aRIter++) {
659 isSameName = (*aRIter)->data()->name() == aName;
664 std::stringstream aNameStream;
665 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
666 aName = aNameStream.str();
667 // reinitialize iterator to make sure a new name is unique
668 aFIter.Initialize(myObjs);
672 theFeature->data()->setName(aName);
675 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
677 boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
679 boost::shared_ptr<Model_Data> aData(new Model_Data);
680 aData->setLabel(theLab.FindChild(theTag));
681 aData->setObject(theObj);
682 theObj->setDoc(aThis);
683 theObj->setData(aData);
684 FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
686 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
687 aFeature->initAttributes();
691 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
693 boost::shared_ptr<ModelAPI_Document> aThis =
694 Model_Application::getApplication()->getDocument(myID);
695 // after all updates, sends a message that groups of features were created or updated
696 boost::static_pointer_cast<Model_Session>(Model_Session::get())
697 ->setCheckTransactions(false);
698 Events_Loop* aLoop = Events_Loop::loop();
699 aLoop->activateFlushes(false);
701 // update all objects by checking are they of labels or not
702 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
703 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
704 for (; aLabIter.More(); aLabIter.Next()) {
705 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
706 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
708 FeaturePtr aNewObj = ModelAPI_Session::get()->createFeature(
709 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
711 if (!aNewObj) { // somethig is wrong, most probably, the opened document has invalid structure
712 Events_Error::send("Invalid type of object in the document");
713 aLabIter.Value()->Label().ForgetAllAttributes();
716 // this must be before "setData" to redo the sketch line correctly
717 myObjs.Bind(aFeatureLabel, aNewObj);
718 aNewFeatures.insert(aNewObj);
719 initData(aNewObj, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
721 // event: model is updated
722 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
723 ModelAPI_EventCreator::get()->sendUpdated(aNewObj, anEvent);
725 // update results of the appeared feature
726 updateResults(aNewObj);
727 } else { // nothing is changed, both iterators are incremented
728 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
729 aKeptFeatures.insert(aFeature);
730 if (theMarkUpdated) {
731 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
732 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
734 updateResults(aFeature);
737 // execute new features to restore results: after features creation to make all references valid
738 /*std::set<FeaturePtr>::iterator aNewIter = aNewFeatures.begin();
739 for(; aNewIter != aNewFeatures.end(); aNewIter++) {
740 (*aNewIter)->execute();
742 // check all features are checked: if not => it was removed
743 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
744 while (aFIter.More()) {
745 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
746 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
747 FeaturePtr aFeature = aFIter.Value();
748 // event: model is updated
749 //if (aFeature->isInHistory()) {
750 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
752 // results of this feature must be redisplayed (hided)
753 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
754 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
755 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
757 for (; aRIter != aResults.cend(); aRIter++) {
758 boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
759 //aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
760 ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
761 ModelAPI_EventCreator::get()->sendDeleted(aThis, aRes->groupName());
764 // redisplay also removed feature (used for sketch and AISObject)
765 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
767 // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
768 TDF_Label aLab = aFIter.Key();
775 if (theUpdateReferences) {
776 synchronizeBackRefs();
779 myExecuteFeatures = false;
780 aLoop->activateFlushes(true);
782 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
783 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
784 if (theMarkUpdated) {
785 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
787 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
788 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
789 boost::static_pointer_cast<Model_Session>(Model_Session::get())
790 ->setCheckTransactions(true);
791 myExecuteFeatures = true;
794 void Model_Document::synchronizeBackRefs()
796 // first cycle: erase all data about back-references
797 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
798 for(; aFeatures.More(); aFeatures.Next()) {
799 FeaturePtr aFeature = aFeatures.Value();
800 boost::shared_ptr<Model_Data> aFData =
801 boost::dynamic_pointer_cast<Model_Data>(aFeature->data());
803 aFData->eraseBackReferences();
805 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
806 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
807 for (; aRIter != aResults.cend(); aRIter++) {
808 boost::shared_ptr<Model_Data> aResData =
809 boost::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
811 aResData->eraseBackReferences();
816 // second cycle: set new back-references: only features may have reference, iterate only them
817 ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
818 for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
819 FeaturePtr aFeature = aFeatures.Value();
820 boost::shared_ptr<Model_Data> aFData =
821 boost::dynamic_pointer_cast<Model_Data>(aFeature->data());
823 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
824 aFData->referencesToObjects(aRefs);
825 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
826 for(; aRefsIter != aRefs.end(); aRefsIter++) {
827 std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
828 for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
830 boost::shared_ptr<Model_Data> aRefData =
831 boost::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
832 aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
840 TDF_Label Model_Document::resultLabel(
841 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
843 const boost::shared_ptr<Model_Data>& aData =
844 boost::dynamic_pointer_cast<Model_Data>(theFeatureData);
845 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
848 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
849 boost::shared_ptr<ModelAPI_Result> theResult,
850 const int theResultIndex)
852 boost::shared_ptr<ModelAPI_Document> aThis =
853 Model_Application::getApplication()->getDocument(myID);
854 theResult->setDoc(aThis);
855 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
856 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
857 theResult->data()->setName(theFeatureData->name());
861 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
862 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
864 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
865 TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
866 ObjectPtr anOldObject = object(aLab);
867 boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
869 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
872 aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
873 storeResult(theFeatureData, aResult, theIndex);
878 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
879 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
881 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
882 TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
883 ObjectPtr anOldObject = object(aLab);
884 boost::shared_ptr<ModelAPI_ResultBody> aResult;
886 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
889 aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
890 storeResult(theFeatureData, aResult, theIndex);
895 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
896 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
898 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
899 TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
900 ObjectPtr anOldObject = object(aLab);
901 boost::shared_ptr<ModelAPI_ResultPart> aResult;
903 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
906 aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
907 storeResult(theFeatureData, aResult, theIndex);
912 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
913 const boost::shared_ptr<ModelAPI_Result>& theResult)
915 boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
917 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
918 return feature(aFeatureLab);
923 void Model_Document::updateResults(FeaturePtr theFeature)
925 // for not persistent is will be done by parametric updater automatically
926 if (!theFeature->isPersistentResult()) return;
927 // check the existing results and remove them if there is nothing on the label
928 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
929 while(aResIter != theFeature->results().cend()) {
930 ResultBodyPtr aBody = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
932 if (!aBody->data()->isValid()) {
933 // found a disappeared result => remove it
934 theFeature->removeResult(aBody);
935 // start iterate from beginning because iterator is corrupted by removing
936 aResIter = theFeature->results().cbegin();
942 // check that results are presented on all labels
943 int aResSize = theFeature->results().size();
944 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
945 for(; aLabIter.More(); aLabIter.Next()) {
946 // here must be GUID of the feature
947 int aResIndex = aLabIter.Value().Tag() - 1;
949 if (aResSize <= aResIndex) {
950 TDF_Label anArgLab = aLabIter.Value();
951 Handle(TDataStd_Comment) aGroup;
952 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
953 if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
954 aNewBody = createBody(theFeature->data(), aResIndex);
955 } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
956 aNewBody = createPart(theFeature->data(), aResIndex);
957 } else if (aGroup->Get() != ModelAPI_ResultConstruction::group().c_str()) {
958 Events_Error::send(std::string("Unknown type of result is found in the document:") +
959 TCollection_AsciiString(aGroup->Get()).ToCString());
963 theFeature->setResult(aNewBody, aResIndex);
969 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
971 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
974 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
976 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);