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++;
293 void Model_Document::abortOperation()
295 if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
296 // first compact all nested
297 if (compactNested()) {
298 // for nested it is undo and clear redos
302 myTransactionsAfterSave--;
303 myIsEmptyTr.erase(myTransactionsAfterSave);
305 if (myNestedNum == 0) // abort only high-level
307 myDoc->AbortCommand();
309 synchronizeFeatures(true, false); // references were not changed since transaction start
310 // abort for all subs
311 std::set<std::string>::iterator aSubIter = mySubs.begin();
312 for (; aSubIter != mySubs.end(); aSubIter++)
313 subDoc(*aSubIter)->abortOperation();
316 bool Model_Document::isOperation()
318 // operation is opened for all documents: no need to check subs
319 return myDoc->HasOpenCommand() == Standard_True ;
322 bool Model_Document::isModified()
324 // is modified if at least one operation was commited and not undoed
325 return myTransactionsAfterSave > 0 || isOperation();
328 bool Model_Document::canUndo()
330 if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
331 && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
333 // check other subs contains operation that can be undoed
334 std::set<std::string>::iterator aSubIter = mySubs.begin();
335 for (; aSubIter != mySubs.end(); aSubIter++)
336 if (subDoc(*aSubIter)->canUndo())
341 void Model_Document::undo()
343 myTransactionsAfterSave--;
346 if (!myIsEmptyTr[myTransactionsAfterSave])
348 synchronizeFeatures(true, true);
350 std::set<std::string>::iterator aSubIter = mySubs.begin();
351 for (; aSubIter != mySubs.end(); aSubIter++)
352 subDoc(*aSubIter)->undo();
355 bool Model_Document::canRedo()
357 if (myDoc->GetAvailableRedos() > 0)
359 // check other subs contains operation that can be redoed
360 std::set<std::string>::iterator aSubIter = mySubs.begin();
361 for (; aSubIter != mySubs.end(); aSubIter++)
362 if (subDoc(*aSubIter)->canRedo())
367 void Model_Document::redo()
369 if (myNestedNum != -1)
371 if (!myIsEmptyTr[myTransactionsAfterSave])
373 myTransactionsAfterSave++;
374 synchronizeFeatures(true, true);
376 std::set<std::string>::iterator aSubIter = mySubs.begin();
377 for (; aSubIter != mySubs.end(); aSubIter++)
378 subDoc(*aSubIter)->redo();
381 /// Appenad to the array of references a new referenced label
382 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
384 Handle(TDataStd_ReferenceArray) aRefs;
385 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
386 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
387 aRefs->SetValue(0, theReferenced);
388 } else { // extend array by one more element
389 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
391 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
392 aNewArray->SetValue(a, aRefs->Value(a));
394 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
395 aRefs->SetInternalArray(aNewArray);
399 FeaturePtr Model_Document::addFeature(std::string theID)
401 TDF_Label anEmptyLab;
402 FeaturePtr anEmptyFeature;
403 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
406 boost::shared_ptr<Model_Document> aDocToAdd = boost::dynamic_pointer_cast<Model_Document>(
407 aFeature->documentToAdd());
409 TDF_Label aFeatureLab;
410 if (!aFeature->isAction()) { // do not add action to the data model
411 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
412 aFeatureLab = aFeaturesLab.NewChild();
413 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
414 // keep the feature ID to restore document later correctly
415 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
416 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
417 // store feature in the history of features array
418 if (aFeature->isInHistory()) {
419 AddToRefArray(aFeaturesLab, aFeatureLab);
422 if (!aFeature->isAction()) { // do not add action to the data model
423 // event: feature is added
424 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
425 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
426 } else { // feature must be executed
427 // no creation event => updater not working, problem with remove part
434 /// Appenad to the array of references a new referenced label.
435 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
436 /// \returns the index of removed element
437 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
440 int aResult = -1; // no returned
441 Handle(TDataStd_ReferenceArray) aRefs;
442 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
443 if (aRefs->Length() == 1) { // just erase an array
444 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
445 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
448 } else { // reduce the array
449 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
451 int aCount = aRefs->Lower();
452 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
453 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
457 aNewArray->SetValue(aCount, aRefs->Value(a));
460 aRefs->SetInternalArray(aNewArray);
466 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
469 // check the feature: it must have no depended objects on it
470 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
471 for(; aResIter != theFeature->results().cend(); aResIter++) {
472 boost::shared_ptr<Model_Data> aData =
473 boost::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
474 if (aData && !aData->refsToMe().empty()) {
476 "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
482 boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
483 TDF_Label aFeatureLabel = aData->label().Father();
484 if (myObjs.IsBound(aFeatureLabel))
485 myObjs.UnBind(aFeatureLabel);
487 return; // not found feature => do not remove
490 // erase all attributes under the label of feature
491 aFeatureLabel.ForgetAllAttributes();
492 // remove it from the references array
493 if (theFeature->isInHistory()) {
494 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
496 // event: feature is deleted
497 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
500 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
502 if (myObjs.IsBound(theLabel))
503 return myObjs.Find(theLabel);
504 return FeaturePtr(); // not found
507 ObjectPtr Model_Document::object(TDF_Label theLabel)
509 // try feature by label
510 FeaturePtr aFeature = feature(theLabel);
512 return feature(theLabel);
513 TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
514 aFeature = feature(aFeatureLabel);
516 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
517 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
518 for (; aRIter != aResults.cend(); aRIter++) {
519 boost::shared_ptr<Model_Data> aResData = boost::dynamic_pointer_cast<Model_Data>(
521 if (aResData->label().Father().IsEqual(theLabel))
525 return FeaturePtr(); // not found
528 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
530 // just store sub-document identifier here to manage it later
531 if (mySubs.find(theDocID) == mySubs.end())
532 mySubs.insert(theDocID);
533 return Model_Application::getApplication()->getDocument(theDocID);
536 boost::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
538 // just store sub-document identifier here to manage it later
539 if (mySubs.find(theDocID) == mySubs.end())
540 mySubs.insert(theDocID);
541 return boost::dynamic_pointer_cast<Model_Document>(
542 Model_Application::getApplication()->getDocument(theDocID));
545 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
546 const bool theHidden)
548 if (theGroupID == ModelAPI_Feature::group()) {
551 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
552 for (; aLabIter.More(); aLabIter.Next()) {
553 if (theIndex == anIndex) {
554 TDF_Label aFLabel = aLabIter.Value()->Label();
555 return feature(aFLabel);
560 Handle(TDataStd_ReferenceArray) aRefs;
561 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
563 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
565 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
566 return feature(aFeatureLabel);
569 // comment must be in any feature: it is kind
571 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
572 for (; aLabIter.More(); aLabIter.Next()) {
573 TDF_Label aFLabel = aLabIter.Value()->Label();
574 FeaturePtr aFeature = feature(aFLabel);
575 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
576 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
577 for (; aRIter != aResults.cend(); aRIter++) {
578 if ((*aRIter)->groupName() != theGroupID) continue;
579 bool isIn = theHidden && (*aRIter)->isInHistory();
580 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
581 isIn = !(*aRIter)->isConcealed();
584 if (anIndex == theIndex)
595 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
598 if (theGroupID == ModelAPI_Feature::group()) {
600 return myObjs.Size();
602 Handle(TDataStd_ReferenceArray) aRefs;
603 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
604 return aRefs->Length();
607 // comment must be in any feature: it is kind
608 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
609 for (; aLabIter.More(); aLabIter.Next()) {
610 TDF_Label aFLabel = aLabIter.Value()->Label();
611 FeaturePtr aFeature = feature(aFLabel);
612 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
613 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
614 for (; aRIter != aResults.cend(); aRIter++) {
615 if ((*aRIter)->groupName() != theGroupID) continue;
616 bool isIn = theHidden;
617 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
618 isIn = !(*aRIter)->isConcealed();
625 // group is not found
629 TDF_Label Model_Document::featuresLabel()
631 return myDoc->Main().FindChild(TAG_OBJECTS);
634 void Model_Document::setUniqueName(FeaturePtr theFeature)
636 if (!theFeature->data()->name().empty())
637 return; // not needed, name is already defined
638 std::string aName; // result
639 // first count all objects of such kind to start with index = count + 1
641 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
642 for (; aFIter.More(); aFIter.Next()) {
643 if (aFIter.Value()->getKind() == theFeature->getKind())
646 // generate candidate name
647 std::stringstream aNameStream;
648 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
649 aName = aNameStream.str();
650 // check this is unique, if not, increase index by 1
651 for (aFIter.Initialize(myObjs); aFIter.More();) {
652 FeaturePtr aFeature = aFIter.Value();
653 bool isSameName = aFeature->data()->name() == aName;
654 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
655 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
656 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
657 for (; aRIter != aResults.cend(); aRIter++) {
658 isSameName = (*aRIter)->data()->name() == aName;
663 std::stringstream aNameStream;
664 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
665 aName = aNameStream.str();
666 // reinitialize iterator to make sure a new name is unique
667 aFIter.Initialize(myObjs);
671 theFeature->data()->setName(aName);
674 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
676 boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
678 boost::shared_ptr<Model_Data> aData(new Model_Data);
679 aData->setLabel(theLab.FindChild(theTag));
680 aData->setObject(theObj);
681 theObj->setDoc(aThis);
682 theObj->setData(aData);
683 FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
685 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
686 aFeature->initAttributes();
690 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
692 boost::shared_ptr<ModelAPI_Document> aThis =
693 Model_Application::getApplication()->getDocument(myID);
694 // after all updates, sends a message that groups of features were created or updated
695 boost::static_pointer_cast<Model_Session>(Model_Session::get())
696 ->setCheckTransactions(false);
697 Events_Loop* aLoop = Events_Loop::loop();
698 aLoop->activateFlushes(false);
700 // update all objects by checking are they of labels or not
701 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
702 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
703 for (; aLabIter.More(); aLabIter.Next()) {
704 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
705 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
707 FeaturePtr aNewObj = ModelAPI_Session::get()->createFeature(
708 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
710 if (!aNewObj) { // somethig is wrong, most probably, the opened document has invalid structure
711 Events_Error::send("Invalid type of object in the document");
712 aLabIter.Value()->Label().ForgetAllAttributes();
715 // this must be before "setData" to redo the sketch line correctly
716 myObjs.Bind(aFeatureLabel, aNewObj);
717 aNewFeatures.insert(aNewObj);
718 initData(aNewObj, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
720 // event: model is updated
721 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
722 ModelAPI_EventCreator::get()->sendUpdated(aNewObj, anEvent);
724 // update results of the appeared feature
725 updateResults(aNewObj);
726 } else { // nothing is changed, both iterators are incremented
727 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
728 aKeptFeatures.insert(aFeature);
729 if (theMarkUpdated) {
730 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
731 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
733 updateResults(aFeature);
736 // execute new features to restore results: after features creation to make all references valid
737 /*std::set<FeaturePtr>::iterator aNewIter = aNewFeatures.begin();
738 for(; aNewIter != aNewFeatures.end(); aNewIter++) {
739 (*aNewIter)->execute();
741 // check all features are checked: if not => it was removed
742 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
743 while (aFIter.More()) {
744 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
745 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
746 FeaturePtr aFeature = aFIter.Value();
747 // event: model is updated
748 //if (aFeature->isInHistory()) {
749 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
751 // results of this feature must be redisplayed (hided)
752 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
753 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
754 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
756 for (; aRIter != aResults.cend(); aRIter++) {
757 boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
758 //aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
759 ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
760 ModelAPI_EventCreator::get()->sendDeleted(aThis, aRes->groupName());
763 // redisplay also removed feature (used for sketch and AISObject)
764 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
766 // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
767 TDF_Label aLab = aFIter.Key();
774 if (theUpdateReferences) {
775 synchronizeBackRefs();
778 myExecuteFeatures = false;
779 aLoop->activateFlushes(true);
781 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
782 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
783 if (theMarkUpdated) {
784 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
786 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
787 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
788 boost::static_pointer_cast<Model_Session>(Model_Session::get())
789 ->setCheckTransactions(true);
790 myExecuteFeatures = true;
793 void Model_Document::synchronizeBackRefs()
795 boost::shared_ptr<ModelAPI_Document> aThis =
796 Model_Application::getApplication()->getDocument(myID);
797 // keeps the concealed flags of result to catch the change and create created/deleted events
798 std::list<std::pair<ResultPtr, bool> > aConcealed;
799 // first cycle: erase all data about back-references
800 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
801 for(; aFeatures.More(); aFeatures.Next()) {
802 FeaturePtr aFeature = aFeatures.Value();
803 boost::shared_ptr<Model_Data> aFData =
804 boost::dynamic_pointer_cast<Model_Data>(aFeature->data());
806 aFData->eraseBackReferences();
808 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
809 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
810 for (; aRIter != aResults.cend(); aRIter++) {
811 boost::shared_ptr<Model_Data> aResData =
812 boost::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
814 aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
815 aResData->eraseBackReferences();
820 // second cycle: set new back-references: only features may have reference, iterate only them
821 ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
822 for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
823 FeaturePtr aFeature = aFeatures.Value();
824 boost::shared_ptr<Model_Data> aFData =
825 boost::dynamic_pointer_cast<Model_Data>(aFeature->data());
827 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
828 aFData->referencesToObjects(aRefs);
829 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
830 for(; aRefsIter != aRefs.end(); aRefsIter++) {
831 std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
832 for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
834 boost::shared_ptr<Model_Data> aRefData =
835 boost::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
836 aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
842 std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
843 for(; aCIter != aConcealed.end(); aCIter++) {
844 if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
845 if (aCIter->second) { // was concealed become not => creation event
846 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
847 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
848 } else { // was not concealed become concealed => delete event
849 ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
855 TDF_Label Model_Document::resultLabel(
856 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
858 const boost::shared_ptr<Model_Data>& aData =
859 boost::dynamic_pointer_cast<Model_Data>(theFeatureData);
860 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
863 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
864 boost::shared_ptr<ModelAPI_Result> theResult,
865 const int theResultIndex)
867 boost::shared_ptr<ModelAPI_Document> aThis =
868 Model_Application::getApplication()->getDocument(myID);
869 theResult->setDoc(aThis);
870 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
871 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
872 theResult->data()->setName(theFeatureData->name());
876 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
877 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
879 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
880 TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
881 ObjectPtr anOldObject = object(aLab);
882 boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
884 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
887 aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
888 storeResult(theFeatureData, aResult, theIndex);
893 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
894 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
896 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
897 TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
898 ObjectPtr anOldObject = object(aLab);
899 boost::shared_ptr<ModelAPI_ResultBody> aResult;
901 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
904 aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
905 storeResult(theFeatureData, aResult, theIndex);
910 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
911 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
913 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
914 TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
915 ObjectPtr anOldObject = object(aLab);
916 boost::shared_ptr<ModelAPI_ResultPart> aResult;
918 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
921 aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
922 storeResult(theFeatureData, aResult, theIndex);
927 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
928 const boost::shared_ptr<ModelAPI_Result>& theResult)
930 boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
932 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
933 return feature(aFeatureLab);
938 void Model_Document::updateResults(FeaturePtr theFeature)
940 // for not persistent is will be done by parametric updater automatically
941 if (!theFeature->isPersistentResult()) return;
942 // check the existing results and remove them if there is nothing on the label
943 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
944 while(aResIter != theFeature->results().cend()) {
945 ResultBodyPtr aBody = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
947 if (!aBody->data()->isValid()) {
948 // found a disappeared result => remove it
949 theFeature->removeResult(aBody);
950 // start iterate from beginning because iterator is corrupted by removing
951 aResIter = theFeature->results().cbegin();
957 // check that results are presented on all labels
958 int aResSize = theFeature->results().size();
959 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
960 for(; aLabIter.More(); aLabIter.Next()) {
961 // here must be GUID of the feature
962 int aResIndex = aLabIter.Value().Tag() - 1;
964 if (aResSize <= aResIndex) {
965 TDF_Label anArgLab = aLabIter.Value();
966 Handle(TDataStd_Comment) aGroup;
967 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
968 if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
969 aNewBody = createBody(theFeature->data(), aResIndex);
970 } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
971 aNewBody = createPart(theFeature->data(), aResIndex);
972 } else if (aGroup->Get() != ModelAPI_ResultConstruction::group().c_str()) {
973 Events_Error::send(std::string("Unknown type of result is found in the document:") +
974 TCollection_AsciiString(aGroup->Get()).ToCString());
978 theFeature->setResult(aNewBody, aResIndex);
984 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
986 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
989 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
991 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);