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 <Model_ResultGroup.h>
14 #include <ModelAPI_Validator.h>
15 #include <Events_Loop.h>
16 #include <Events_Error.h>
18 #include <TDataStd_Integer.hxx>
19 #include <TDataStd_Comment.hxx>
20 #include <TDF_ChildIDIterator.hxx>
21 #include <TDataStd_ReferenceArray.hxx>
22 #include <TDataStd_HLabelArray1.hxx>
23 #include <TDataStd_Name.hxx>
24 #include <TDF_Reference.hxx>
25 #include <TDF_ChildIDIterator.hxx>
26 #include <TDF_LabelMapHasher.hxx>
34 # define _separator_ '\\'
36 # define _separator_ '/'
39 static const int UNDO_LIMIT = 10; // number of possible undo operations
41 static const int TAG_GENERAL = 1; // general properties tag
42 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree (features, results)
43 static const int TAG_HISTORY = 3; // tag of the history sub-tree (python dump)
46 static const int TAG_FEATURE_ARGUMENTS = 1; ///< where the arguments are located
47 static const int TAG_FEATURE_RESULTS = 2; ///< where the results are located
49 Model_Document::Model_Document(const std::string theID, const std::string theKind)
50 : myID(theID), myKind(theKind),
51 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
53 myDoc->SetUndoLimit(UNDO_LIMIT);
54 myTransactionsCounter = 0;
55 myTransactionSave = 0;
57 myExecuteFeatures = true;
58 // to have something in the document and avoid empty doc open/save problem
59 // in transaction for nesting correct working
61 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
62 myDoc->CommitCommand();
65 /// Returns the file name of this document by the nameof directory and identifuer of a document
66 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
68 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
69 // remove end-separators
70 while(aPath.Length() && (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
71 aPath.Remove(aPath.Length());
73 aPath += theID.c_str();
74 aPath += ".cbf"; // standard binary file extension
78 bool Model_Document::load(const char* theFileName)
80 Handle(Model_Application) anApp = Model_Application::getApplication();
81 if (this == Model_Session::get()->moduleDocument().get()) {
82 anApp->setLoadPath(theFileName);
84 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
85 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
87 aStatus = anApp->Open(aPath, myDoc);
88 } catch (Standard_Failure) {
89 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
91 std::string("Exception in opening of document: ") + aFail->GetMessageString());
94 bool isError = aStatus != PCDM_RS_OK;
97 case PCDM_RS_UnknownDocument:
98 Events_Error::send(std::string("Can not open document: unknown format"));
100 case PCDM_RS_AlreadyRetrieved:
101 Events_Error::send(std::string("Can not open document: already opened"));
103 case PCDM_RS_AlreadyRetrievedAndModified:
105 std::string("Can not open document: already opened and modified"));
107 case PCDM_RS_NoDriver:
108 Events_Error::send(std::string("Can not open document: driver library is not found"));
110 case PCDM_RS_UnknownFileDriver:
111 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
113 case PCDM_RS_OpenError:
114 Events_Error::send(std::string("Can not open document: file open error"));
116 case PCDM_RS_NoVersion:
117 Events_Error::send(std::string("Can not open document: invalid version"));
119 case PCDM_RS_NoModel:
120 Events_Error::send(std::string("Can not open document: no data model"));
122 case PCDM_RS_NoDocument:
123 Events_Error::send(std::string("Can not open document: no document inside"));
125 case PCDM_RS_FormatFailure:
126 Events_Error::send(std::string("Can not open document: format failure"));
128 case PCDM_RS_TypeNotFoundInSchema:
129 Events_Error::send(std::string("Can not open document: invalid object"));
131 case PCDM_RS_UnrecognizedFileFormat:
132 Events_Error::send(std::string("Can not open document: unrecognized file format"));
134 case PCDM_RS_MakeFailure:
135 Events_Error::send(std::string("Can not open document: make failure"));
137 case PCDM_RS_PermissionDenied:
138 Events_Error::send(std::string("Can not open document: permission denied"));
140 case PCDM_RS_DriverFailure:
141 Events_Error::send(std::string("Can not open document: driver failure"));
144 Events_Error::send(std::string("Can not open document: unknown error"));
149 myDoc->SetUndoLimit(UNDO_LIMIT);
150 // to avoid the problem that feature is created in the current, not this, document
151 Model_Session::get()->setActiveDocument(anApp->getDocument(myID), false);
152 synchronizeFeatures(false, true);
153 Model_Session::get()->setActiveDocument(Model_Session::get()->moduleDocument(), false);
154 Model_Session::get()->setActiveDocument(anApp->getDocument(myID), true);
159 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
161 // create a directory in the root document if it is not yet exist
162 if (this == Model_Session::get()->moduleDocument().get()) {
164 CreateDirectory(theFileName, NULL);
166 mkdir(theFileName, 0x1ff);
169 // filename in the dir is id of document inside of the given directory
170 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
171 PCDM_StoreStatus aStatus;
173 aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
174 } catch (Standard_Failure) {
175 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
177 std::string("Exception in saving of document: ") + aFail->GetMessageString());
180 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
183 case PCDM_SS_DriverFailure:
184 Events_Error::send(std::string("Can not save document: save driver-library failure"));
186 case PCDM_SS_WriteFailure:
187 Events_Error::send(std::string("Can not save document: file writing failure"));
189 case PCDM_SS_Failure:
191 Events_Error::send(std::string("Can not save document"));
195 myTransactionSave = myTransactionsCounter;
196 if (isDone) { // save also sub-documents if any
197 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
198 std::set<std::string>::iterator aSubIter = mySubs.begin();
199 for (; aSubIter != mySubs.end() && isDone; aSubIter++) {
200 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
206 void Model_Document::close(const bool theForever)
208 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
209 if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
210 aPM->setActiveDocument(aPM->moduleDocument());
213 std::set<std::string>::iterator aSubIter = mySubs.begin();
214 for (; aSubIter != mySubs.end(); aSubIter++)
215 subDoc(*aSubIter)->close(theForever);
218 // close for thid document needs no transaction in this document
219 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
221 // delete all features of this document
222 std::shared_ptr<ModelAPI_Document> aThis =
223 Model_Application::getApplication()->getDocument(myID);
224 Events_Loop* aLoop = Events_Loop::loop();
225 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myObjs);
226 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
227 FeaturePtr aFeature = aFeaturesIter.Value();
228 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
229 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
230 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
231 aFeature->eraseResults();
235 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
236 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
238 // close all only if it is really asked, otherwise it can be undoed/redoed
240 if (myDoc->CanClose() == CDM_CCS_OK)
244 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
247 void Model_Document::startOperation()
249 if (myDoc->HasOpenCommand()) { // start of nested command
250 if (myNestedNum == -1) {
252 myDoc->InitDeltaCompaction();
254 myIsEmptyTr[myTransactionsCounter] = !myDoc->CommitCommand();
255 myTransactionsCounter++;
256 myDoc->OpenCommand();
257 } else { // start the simple command
260 // new command for all subs
261 std::set<std::string>::iterator aSubIter = mySubs.begin();
262 for (; aSubIter != mySubs.end(); aSubIter++)
263 subDoc(*aSubIter)->startOperation();
266 bool Model_Document::compactNested()
268 bool allWasEmpty = true;
269 while (myNestedNum != -1) {
270 myTransactionsCounter--;
271 if (!myIsEmptyTr[myTransactionsCounter]) {
274 myIsEmptyTr.erase(myTransactionsCounter);
277 myIsEmptyTr[myTransactionsCounter] = allWasEmpty;
278 myTransactionsCounter++;
280 // Issue 151: if everything is empty, it is a problem for OCCT to work with it,
281 // just commit the empty that returns nothing
282 myDoc->CommitCommand();
284 myDoc->PerformDeltaCompaction();
289 void Model_Document::finishOperation()
291 // just to be sure that everybody knows that changes were performed
292 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
293 std::static_pointer_cast<Model_Session>(Model_Session::get())
294 ->setCheckTransactions(false); // for nested transaction commit
295 synchronizeBackRefs();
296 Events_Loop* aLoop = Events_Loop::loop();
297 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
298 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
299 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
300 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
301 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
302 // this must be here just after everything is finished but before real transaction stop
303 // to avoid messages about modifications outside of the transaction
304 // and to rebuild everything after all updates and creates
305 if (Model_Session::get()->moduleDocument().get() == this) { // once for root document
306 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
307 static std::shared_ptr<Events_Message> aFinishMsg
308 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
309 Events_Loop::loop()->send(aFinishMsg);
310 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
312 // to avoid "updated" message appearance by updater
313 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
315 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
316 std::static_pointer_cast<Model_Session>(Model_Session::get())
317 ->setCheckTransactions(true); // for nested transaction commit
319 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
320 std::set<std::string>::iterator aSubIter = mySubs.begin();
321 for (; aSubIter != mySubs.end(); aSubIter++)
322 subDoc(*aSubIter)->finishOperation();
324 if (myNestedNum != -1) // this nested transaction is owervritten
326 if (!myDoc->HasOpenCommand()) {
327 if (myNestedNum != -1) {
332 // returns false if delta is empty and no transaction was made
333 myIsEmptyTr[myTransactionsCounter] = !myDoc->CommitCommand(); // && (myNestedNum == -1);
334 myTransactionsCounter++;
338 void Model_Document::abortOperation()
340 if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
341 // first compact all nested
342 if (compactNested()) {
343 myDoc->Undo(); // undo only compacted, if not: do not undo the empty transaction
346 myTransactionsCounter--;
347 myIsEmptyTr.erase(myTransactionsCounter);
349 if (myNestedNum == 0) // abort only high-level
351 myDoc->AbortCommand();
353 synchronizeFeatures(true, false); // references were not changed since transaction start
354 // abort for all subs
355 std::set<std::string>::iterator aSubIter = mySubs.begin();
356 for (; aSubIter != mySubs.end(); aSubIter++)
357 subDoc(*aSubIter)->abortOperation();
360 bool Model_Document::isOperation()
362 // operation is opened for all documents: no need to check subs
363 return myDoc->HasOpenCommand() == Standard_True ;
366 bool Model_Document::isModified()
368 // is modified if at least one operation was commited and not undoed
369 return myTransactionsCounter != myTransactionSave || isOperation();
372 bool Model_Document::canUndo()
374 if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
375 && myTransactionsCounter != 0 /* for omitting the first useless transaction */)
377 // check other subs contains operation that can be undoed
378 std::set<std::string>::iterator aSubIter = mySubs.begin();
379 for (; aSubIter != mySubs.end(); aSubIter++)
380 if (subDoc(*aSubIter)->canUndo())
385 void Model_Document::undo()
387 myTransactionsCounter--;
390 if (!myIsEmptyTr[myTransactionsCounter])
392 synchronizeFeatures(true, true);
394 std::set<std::string>::iterator aSubIter = mySubs.begin();
395 for (; aSubIter != mySubs.end(); aSubIter++)
396 subDoc(*aSubIter)->undo();
399 bool Model_Document::canRedo()
401 if (myDoc->GetAvailableRedos() > 0)
403 // check other subs contains operation that can be redoed
404 std::set<std::string>::iterator aSubIter = mySubs.begin();
405 for (; aSubIter != mySubs.end(); aSubIter++)
406 if (subDoc(*aSubIter)->canRedo())
411 void Model_Document::redo()
413 if (myNestedNum != -1)
415 if (!myIsEmptyTr[myTransactionsCounter])
417 myTransactionsCounter++;
418 synchronizeFeatures(true, true);
420 std::set<std::string>::iterator aSubIter = mySubs.begin();
421 for (; aSubIter != mySubs.end(); aSubIter++)
422 subDoc(*aSubIter)->redo();
425 /// Appenad to the array of references a new referenced label
426 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
428 Handle(TDataStd_ReferenceArray) aRefs;
429 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
430 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
431 aRefs->SetValue(0, theReferenced);
432 } else { // extend array by one more element
433 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
435 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
436 aNewArray->SetValue(a, aRefs->Value(a));
438 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
439 aRefs->SetInternalArray(aNewArray);
443 FeaturePtr Model_Document::addFeature(std::string theID)
445 TDF_Label anEmptyLab;
446 FeaturePtr anEmptyFeature;
447 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
450 std::shared_ptr<Model_Document> aDocToAdd = std::dynamic_pointer_cast<Model_Document>(
451 aFeature->documentToAdd());
453 TDF_Label aFeatureLab;
454 if (!aFeature->isAction()) { // do not add action to the data model
455 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
456 aFeatureLab = aFeaturesLab.NewChild();
457 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
458 // keep the feature ID to restore document later correctly
459 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
460 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
461 // store feature in the history of features array
462 if (aFeature->isInHistory()) {
463 AddToRefArray(aFeaturesLab, aFeatureLab);
466 if (!aFeature->isAction()) { // do not add action to the data model
467 // event: feature is added
468 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
469 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
470 } else { // feature must be executed
471 // no creation event => updater not working, problem with remove part
478 /// Appenad to the array of references a new referenced label.
479 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
480 /// \returns the index of removed element
481 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
484 int aResult = -1; // no returned
485 Handle(TDataStd_ReferenceArray) aRefs;
486 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
487 if (aRefs->Length() == 1) { // just erase an array
488 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
489 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
492 } else { // reduce the array
493 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
495 int aCount = aRefs->Lower();
496 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
497 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
501 aNewArray->SetValue(aCount, aRefs->Value(a));
504 aRefs->SetInternalArray(aNewArray);
510 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
513 // check the feature: it must have no depended objects on it
514 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
515 for(; aResIter != theFeature->results().cend(); aResIter++) {
516 std::shared_ptr<Model_Data> aData =
517 std::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
518 if (aData && !aData->refsToMe().empty()) {
520 "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
526 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
528 TDF_Label aFeatureLabel = aData->label().Father();
529 if (myObjs.IsBound(aFeatureLabel))
530 myObjs.UnBind(aFeatureLabel);
532 return; // not found feature => do not remove
535 // erase all attributes under the label of feature
536 aFeatureLabel.ForgetAllAttributes();
537 // remove it from the references array
538 if (theFeature->isInHistory()) {
539 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
542 // event: feature is deleted
543 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
546 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
548 if (myObjs.IsBound(theLabel))
549 return myObjs.Find(theLabel);
550 return FeaturePtr(); // not found
553 ObjectPtr Model_Document::object(TDF_Label theLabel)
555 // try feature by label
556 FeaturePtr aFeature = feature(theLabel);
558 return feature(theLabel);
559 TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
560 aFeature = feature(aFeatureLabel);
562 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
563 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
564 for (; aRIter != aResults.cend(); aRIter++) {
565 std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
567 if (aResData->label().Father().IsEqual(theLabel))
571 return FeaturePtr(); // not found
574 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
576 // just store sub-document identifier here to manage it later
577 if (mySubs.find(theDocID) == mySubs.end())
578 mySubs.insert(theDocID);
579 return Model_Application::getApplication()->getDocument(theDocID);
582 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
584 // just store sub-document identifier here to manage it later
585 if (mySubs.find(theDocID) == mySubs.end())
586 mySubs.insert(theDocID);
587 return std::dynamic_pointer_cast<Model_Document>(
588 Model_Application::getApplication()->getDocument(theDocID));
591 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
592 const bool theHidden)
594 if (theGroupID == ModelAPI_Feature::group()) {
597 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
598 for (; aLabIter.More(); aLabIter.Next()) {
599 if (theIndex == anIndex) {
600 TDF_Label aFLabel = aLabIter.Value()->Label();
601 return feature(aFLabel);
606 Handle(TDataStd_ReferenceArray) aRefs;
607 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
609 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
611 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
612 return feature(aFeatureLabel);
615 // comment must be in any feature: it is kind
617 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
618 for (; aLabIter.More(); aLabIter.Next()) {
619 TDF_Label aFLabel = aLabIter.Value()->Label();
620 FeaturePtr aFeature = feature(aFLabel);
621 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
622 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
623 for (; aRIter != aResults.cend(); aRIter++) {
624 if ((*aRIter)->groupName() != theGroupID) continue;
625 bool isIn = theHidden && (*aRIter)->isInHistory();
626 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
627 isIn = !(*aRIter)->isConcealed();
630 if (anIndex == theIndex)
641 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
644 if (theGroupID == ModelAPI_Feature::group()) {
646 return myObjs.Size();
648 Handle(TDataStd_ReferenceArray) aRefs;
649 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
650 return aRefs->Length();
653 // comment must be in any feature: it is kind
654 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
655 for (; aLabIter.More(); aLabIter.Next()) {
656 TDF_Label aFLabel = aLabIter.Value()->Label();
657 FeaturePtr aFeature = feature(aFLabel);
658 if (!aFeature) // may be on close
660 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
661 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
662 for (; aRIter != aResults.cend(); aRIter++) {
663 if ((*aRIter)->groupName() != theGroupID) continue;
664 bool isIn = theHidden;
665 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
666 isIn = !(*aRIter)->isConcealed();
673 // group is not found
677 TDF_Label Model_Document::featuresLabel()
679 return myDoc->Main().FindChild(TAG_OBJECTS);
682 void Model_Document::setUniqueName(FeaturePtr theFeature)
684 if (!theFeature->data()->name().empty())
685 return; // not needed, name is already defined
686 std::string aName; // result
687 // first count all objects of such kind to start with index = count + 1
689 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
690 for (; aFIter.More(); aFIter.Next()) {
691 if (aFIter.Value()->getKind() == theFeature->getKind())
694 // generate candidate name
695 std::stringstream aNameStream;
696 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
697 aName = aNameStream.str();
698 // check this is unique, if not, increase index by 1
699 for (aFIter.Initialize(myObjs); aFIter.More();) {
700 FeaturePtr aFeature = aFIter.Value();
701 bool isSameName = aFeature->data()->name() == aName;
702 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
703 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
704 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
705 for (; aRIter != aResults.cend(); aRIter++) {
706 isSameName = (*aRIter)->data()->name() == aName;
711 std::stringstream aNameStream;
712 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
713 aName = aNameStream.str();
714 // reinitialize iterator to make sure a new name is unique
715 aFIter.Initialize(myObjs);
719 theFeature->data()->setName(aName);
722 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
724 std::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
726 std::shared_ptr<Model_Data> aData(new Model_Data);
727 aData->setLabel(theLab.FindChild(theTag));
728 aData->setObject(theObj);
729 theObj->setDoc(aThis);
730 theObj->setData(aData);
731 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
733 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
734 aFeature->initAttributes();
738 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
740 std::shared_ptr<ModelAPI_Document> aThis =
741 Model_Application::getApplication()->getDocument(myID);
742 // after all updates, sends a message that groups of features were created or updated
743 std::static_pointer_cast<Model_Session>(Model_Session::get())
744 ->setCheckTransactions(false);
745 Events_Loop* aLoop = Events_Loop::loop();
746 aLoop->activateFlushes(false);
748 // update all objects by checking are they of labels or not
749 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
750 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
751 for (; aLabIter.More(); aLabIter.Next()) {
752 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
754 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
756 aFeature = ModelAPI_Session::get()->createFeature(
757 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
759 if (!aFeature) { // somethig is wrong, most probably, the opened document has invalid structure
760 Events_Error::send("Invalid type of object in the document");
761 aLabIter.Value()->Label().ForgetAllAttributes();
764 // this must be before "setData" to redo the sketch line correctly
765 myObjs.Bind(aFeatureLabel, aFeature);
766 aNewFeatures.insert(aFeature);
767 initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
769 // event: model is updated
770 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
771 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
772 } else { // nothing is changed, both iterators are incremented
773 aFeature = myObjs.Find(aFeatureLabel);
774 aKeptFeatures.insert(aFeature);
775 if (theMarkUpdated) {
776 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
777 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
781 // update results of thefeatures (after features created because they may be connected, like sketch and sub elements)
782 TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
783 for (; aLabIter2.More(); aLabIter2.Next()) {
784 TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
785 if (myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
786 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
787 updateResults(aFeature);
791 // check all features are checked: if not => it was removed
792 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
793 while (aFIter.More()) {
794 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
795 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
796 FeaturePtr aFeature = aFIter.Value();
797 // event: model is updated
798 //if (aFeature->isInHistory()) {
799 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
801 // results of this feature must be redisplayed (hided)
802 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
803 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
804 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
805 // redisplay also removed feature (used for sketch and AISObject)
806 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
808 // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
809 TDF_Label aLab = aFIter.Key();
816 if (theUpdateReferences) {
817 synchronizeBackRefs();
820 myExecuteFeatures = false;
821 aLoop->activateFlushes(true);
823 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
824 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
825 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
826 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
827 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
828 std::static_pointer_cast<Model_Session>(Model_Session::get())
829 ->setCheckTransactions(true);
830 myExecuteFeatures = true;
833 void Model_Document::synchronizeBackRefs()
835 std::shared_ptr<ModelAPI_Document> aThis =
836 Model_Application::getApplication()->getDocument(myID);
837 // keeps the concealed flags of result to catch the change and create created/deleted events
838 std::list<std::pair<ResultPtr, bool> > aConcealed;
839 // first cycle: erase all data about back-references
840 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
841 for(; aFeatures.More(); aFeatures.Next()) {
842 FeaturePtr aFeature = aFeatures.Value();
843 std::shared_ptr<Model_Data> aFData =
844 std::dynamic_pointer_cast<Model_Data>(aFeature->data());
846 aFData->eraseBackReferences();
848 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
849 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
850 for (; aRIter != aResults.cend(); aRIter++) {
851 std::shared_ptr<Model_Data> aResData =
852 std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
854 aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
855 aResData->eraseBackReferences();
860 // second cycle: set new back-references: only features may have reference, iterate only them
861 ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
862 for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
863 FeaturePtr aFeature = aFeatures.Value();
864 std::shared_ptr<Model_Data> aFData =
865 std::dynamic_pointer_cast<Model_Data>(aFeature->data());
867 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
868 aFData->referencesToObjects(aRefs);
869 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
870 for(; aRefsIter != aRefs.end(); aRefsIter++) {
871 std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
872 for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
874 std::shared_ptr<Model_Data> aRefData =
875 std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
876 aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
882 std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
883 for(; aCIter != aConcealed.end(); aCIter++) {
884 if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
885 if (aCIter->second) { // was concealed become not => creation event
886 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
887 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
888 } else { // was not concealed become concealed => delete event
889 ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
890 // redisplay for the viewer (it must be disappeared also)
891 static Events_ID EVENT_DISP =
892 Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
893 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
899 TDF_Label Model_Document::resultLabel(
900 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
902 const std::shared_ptr<Model_Data>& aData =
903 std::dynamic_pointer_cast<Model_Data>(theFeatureData);
904 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
907 void Model_Document::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
908 std::shared_ptr<ModelAPI_Result> theResult,
909 const int theResultIndex)
911 std::shared_ptr<ModelAPI_Document> aThis =
912 Model_Application::getApplication()->getDocument(myID);
913 theResult->setDoc(aThis);
914 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
915 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
916 theResult->data()->setName(theFeatureData->name());
920 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
921 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
923 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
924 TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
925 ObjectPtr anOldObject = object(aLab);
926 std::shared_ptr<ModelAPI_ResultConstruction> aResult;
928 aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
931 aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
932 storeResult(theFeatureData, aResult, theIndex);
937 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
938 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
940 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
941 TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
942 ObjectPtr anOldObject = object(aLab);
943 std::shared_ptr<ModelAPI_ResultBody> aResult;
945 aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
948 aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
949 storeResult(theFeatureData, aResult, theIndex);
954 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
955 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
957 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
958 TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
959 ObjectPtr anOldObject = object(aLab);
960 std::shared_ptr<ModelAPI_ResultPart> aResult;
962 aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
965 aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
966 storeResult(theFeatureData, aResult, theIndex);
971 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
972 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
974 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
975 TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
976 ObjectPtr anOldObject = object(aLab);
977 std::shared_ptr<ModelAPI_ResultGroup> aResult;
979 aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
982 aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
983 storeResult(theFeatureData, aResult, theIndex);
988 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
989 const std::shared_ptr<ModelAPI_Result>& theResult)
991 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
993 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
994 return feature(aFeatureLab);
999 void Model_Document::updateResults(FeaturePtr theFeature)
1001 // for not persistent is will be done by parametric updater automatically
1002 //if (!theFeature->isPersistentResult()) return;
1003 // check the existing results and remove them if there is nothing on the label
1004 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1005 while(aResIter != theFeature->results().cend()) {
1006 ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1008 if (!aBody->data()->isValid()) {
1009 // found a disappeared result => remove it
1010 theFeature->removeResult(aBody);
1011 // start iterate from beginning because iterator is corrupted by removing
1012 aResIter = theFeature->results().cbegin();
1018 // it may be on undo
1019 if (!theFeature->data() || !theFeature->data()->isValid())
1021 // check that results are presented on all labels
1022 int aResSize = theFeature->results().size();
1023 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1024 for(; aLabIter.More(); aLabIter.Next()) {
1025 // here must be GUID of the feature
1026 int aResIndex = aLabIter.Value().Tag() - 1;
1028 if (aResSize <= aResIndex) {
1029 TDF_Label anArgLab = aLabIter.Value();
1030 Handle(TDataStd_Comment) aGroup;
1031 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1032 if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1033 aNewBody = createBody(theFeature->data(), aResIndex);
1034 } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1035 aNewBody = createPart(theFeature->data(), aResIndex);
1036 } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1037 theFeature->execute(); // construction shapes are needed for sketch solver
1039 } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1040 aNewBody = createGroup(theFeature->data(), aResIndex);
1042 Events_Error::send(std::string("Unknown type of result is found in the document:") +
1043 TCollection_AsciiString(aGroup->Get()).ToCString());
1047 theFeature->setResult(aNewBody, aResIndex);
1053 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1055 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1058 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1060 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);