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 myTransactionsAfterSave = 0;
56 myExecuteFeatures = true;
57 // to have something in the document and avoid empty doc open/save problem
58 // in transaction for nesting correct working
60 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
61 myDoc->CommitCommand();
64 /// Returns the file name of this document by the nameof directory and identifuer of a document
65 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
67 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
68 // remove end-separators
69 while(aPath.Length() && (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
70 aPath.Remove(aPath.Length());
72 aPath += theID.c_str();
73 aPath += ".cbf"; // standard binary file extension
77 bool Model_Document::load(const char* theFileName)
79 Handle(Model_Application) anApp = Model_Application::getApplication();
80 if (this == Model_Session::get()->moduleDocument().get()) {
81 anApp->setLoadPath(theFileName);
83 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
84 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
86 aStatus = anApp->Open(aPath, myDoc);
87 } catch (Standard_Failure) {
88 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
90 std::string("Exception in opening of document: ") + aFail->GetMessageString());
93 bool isError = aStatus != PCDM_RS_OK;
96 case PCDM_RS_UnknownDocument:
97 Events_Error::send(std::string("Can not open document: unknown format"));
99 case PCDM_RS_AlreadyRetrieved:
100 Events_Error::send(std::string("Can not open document: already opened"));
102 case PCDM_RS_AlreadyRetrievedAndModified:
104 std::string("Can not open document: already opened and modified"));
106 case PCDM_RS_NoDriver:
107 Events_Error::send(std::string("Can not open document: driver library is not found"));
109 case PCDM_RS_UnknownFileDriver:
110 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
112 case PCDM_RS_OpenError:
113 Events_Error::send(std::string("Can not open document: file open error"));
115 case PCDM_RS_NoVersion:
116 Events_Error::send(std::string("Can not open document: invalid version"));
118 case PCDM_RS_NoModel:
119 Events_Error::send(std::string("Can not open document: no data model"));
121 case PCDM_RS_NoDocument:
122 Events_Error::send(std::string("Can not open document: no document inside"));
124 case PCDM_RS_FormatFailure:
125 Events_Error::send(std::string("Can not open document: format failure"));
127 case PCDM_RS_TypeNotFoundInSchema:
128 Events_Error::send(std::string("Can not open document: invalid object"));
130 case PCDM_RS_UnrecognizedFileFormat:
131 Events_Error::send(std::string("Can not open document: unrecognized file format"));
133 case PCDM_RS_MakeFailure:
134 Events_Error::send(std::string("Can not open document: make failure"));
136 case PCDM_RS_PermissionDenied:
137 Events_Error::send(std::string("Can not open document: permission denied"));
139 case PCDM_RS_DriverFailure:
140 Events_Error::send(std::string("Can not open document: driver failure"));
143 Events_Error::send(std::string("Can not open document: unknown error"));
148 myDoc->SetUndoLimit(UNDO_LIMIT);
149 // to avoid the problem that feature is created in the current, not this, document
150 Model_Session::get()->setActiveDocument(anApp->getDocument(myID), false);
151 synchronizeFeatures(false, true);
152 Model_Session::get()->setActiveDocument(Model_Session::get()->moduleDocument(), false);
153 Model_Session::get()->setActiveDocument(anApp->getDocument(myID), true);
158 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
160 // create a directory in the root document if it is not yet exist
161 if (this == Model_Session::get()->moduleDocument().get()) {
163 CreateDirectory(theFileName, NULL);
165 mkdir(theFileName, 0x1ff);
168 // filename in the dir is id of document inside of the given directory
169 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
170 PCDM_StoreStatus aStatus;
172 aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
173 } catch (Standard_Failure) {
174 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
176 std::string("Exception in saving of document: ") + aFail->GetMessageString());
179 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
182 case PCDM_SS_DriverFailure:
183 Events_Error::send(std::string("Can not save document: save driver-library failure"));
185 case PCDM_SS_WriteFailure:
186 Events_Error::send(std::string("Can not save document: file writing failure"));
188 case PCDM_SS_Failure:
190 Events_Error::send(std::string("Can not save document"));
194 myTransactionsAfterSave = 0;
195 if (isDone) { // save also sub-documents if any
196 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
197 std::set<std::string>::iterator aSubIter = mySubs.begin();
198 for (; aSubIter != mySubs.end() && isDone; aSubIter++) {
199 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
205 void Model_Document::close(const bool theForever)
207 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
208 if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
209 aPM->setActiveDocument(aPM->moduleDocument());
212 std::set<std::string>::iterator aSubIter = mySubs.begin();
213 for (; aSubIter != mySubs.end(); aSubIter++)
214 subDoc(*aSubIter)->close(theForever);
217 // close for thid document needs no transaction in this document
218 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
220 // delete all features of this document
221 std::shared_ptr<ModelAPI_Document> aThis =
222 Model_Application::getApplication()->getDocument(myID);
223 Events_Loop* aLoop = Events_Loop::loop();
224 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myObjs);
225 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
226 FeaturePtr aFeature = aFeaturesIter.Value();
227 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
228 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
229 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
230 aFeature->eraseResults();
234 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
235 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
237 // close all only if it is really asked, otherwise it can be undoed/redoed
239 if (myDoc->CanClose() == CDM_CCS_OK)
243 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
246 void Model_Document::startOperation()
248 if (myDoc->HasOpenCommand()) { // start of nested command
249 if (myNestedNum == -1) {
251 myDoc->InitDeltaCompaction();
253 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();
254 myTransactionsAfterSave++;
255 myDoc->OpenCommand();
256 } else { // start the simple command
259 // new command for all subs
260 std::set<std::string>::iterator aSubIter = mySubs.begin();
261 for (; aSubIter != mySubs.end(); aSubIter++)
262 subDoc(*aSubIter)->startOperation();
265 bool Model_Document::compactNested()
267 bool allWasEmpty = true;
268 while (myNestedNum != -1) {
269 myTransactionsAfterSave--;
270 if (!myIsEmptyTr[myTransactionsAfterSave]) {
273 myIsEmptyTr.erase(myTransactionsAfterSave);
276 myIsEmptyTr[myTransactionsAfterSave] = allWasEmpty;
277 myTransactionsAfterSave++;
279 // Issue 151: if everything is empty, it is a problem for OCCT to work with it,
280 // just commit the empty that returns nothing
281 myDoc->CommitCommand();
283 myDoc->PerformDeltaCompaction();
288 void Model_Document::finishOperation()
290 // just to be sure that everybody knows that changes were performed
291 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
292 std::static_pointer_cast<Model_Session>(Model_Session::get())
293 ->setCheckTransactions(false); // for nested transaction commit
294 synchronizeBackRefs();
295 Events_Loop* aLoop = Events_Loop::loop();
296 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
297 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
298 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
299 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
300 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
301 // this must be here just after everything is finished but before real transaction stop
302 // to avoid messages about modifications outside of the transaction
303 // and to rebuild everything after all updates and creates
304 if (Model_Session::get()->moduleDocument().get() == this) { // once for root document
305 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
306 static std::shared_ptr<Events_Message> aFinishMsg
307 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
308 Events_Loop::loop()->send(aFinishMsg);
309 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
311 // to avoid "updated" message appearance by updater
312 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
314 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
315 std::static_pointer_cast<Model_Session>(Model_Session::get())
316 ->setCheckTransactions(true); // for nested transaction commit
318 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
319 std::set<std::string>::iterator aSubIter = mySubs.begin();
320 for (; aSubIter != mySubs.end(); aSubIter++)
321 subDoc(*aSubIter)->finishOperation();
323 if (myNestedNum != -1) // this nested transaction is owervritten
325 if (!myDoc->HasOpenCommand()) {
326 if (myNestedNum != -1) {
331 // returns false if delta is empty and no transaction was made
332 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand(); // && (myNestedNum == -1);
333 myTransactionsAfterSave++;
337 void Model_Document::abortOperation()
339 if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
340 // first compact all nested
341 if (compactNested()) {
342 myDoc->Undo(); // undo only compacted, if not: do not undo the empty transaction
345 myTransactionsAfterSave--;
346 myIsEmptyTr.erase(myTransactionsAfterSave);
348 if (myNestedNum == 0) // abort only high-level
350 myDoc->AbortCommand();
352 synchronizeFeatures(true, false); // references were not changed since transaction start
353 // abort for all subs
354 std::set<std::string>::iterator aSubIter = mySubs.begin();
355 for (; aSubIter != mySubs.end(); aSubIter++)
356 subDoc(*aSubIter)->abortOperation();
359 bool Model_Document::isOperation()
361 // operation is opened for all documents: no need to check subs
362 return myDoc->HasOpenCommand() == Standard_True ;
365 bool Model_Document::isModified()
367 // is modified if at least one operation was commited and not undoed
368 return myTransactionsAfterSave > 0 || isOperation();
371 bool Model_Document::canUndo()
373 if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
374 && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
376 // check other subs contains operation that can be undoed
377 std::set<std::string>::iterator aSubIter = mySubs.begin();
378 for (; aSubIter != mySubs.end(); aSubIter++)
379 if (subDoc(*aSubIter)->canUndo())
384 void Model_Document::undo()
386 myTransactionsAfterSave--;
389 if (!myIsEmptyTr[myTransactionsAfterSave])
391 synchronizeFeatures(true, true);
393 std::set<std::string>::iterator aSubIter = mySubs.begin();
394 for (; aSubIter != mySubs.end(); aSubIter++)
395 subDoc(*aSubIter)->undo();
398 bool Model_Document::canRedo()
400 if (myDoc->GetAvailableRedos() > 0)
402 // check other subs contains operation that can be redoed
403 std::set<std::string>::iterator aSubIter = mySubs.begin();
404 for (; aSubIter != mySubs.end(); aSubIter++)
405 if (subDoc(*aSubIter)->canRedo())
410 void Model_Document::redo()
412 if (myNestedNum != -1)
414 if (!myIsEmptyTr[myTransactionsAfterSave])
416 myTransactionsAfterSave++;
417 synchronizeFeatures(true, true);
419 std::set<std::string>::iterator aSubIter = mySubs.begin();
420 for (; aSubIter != mySubs.end(); aSubIter++)
421 subDoc(*aSubIter)->redo();
424 /// Appenad to the array of references a new referenced label
425 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
427 Handle(TDataStd_ReferenceArray) aRefs;
428 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
429 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
430 aRefs->SetValue(0, theReferenced);
431 } else { // extend array by one more element
432 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
434 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
435 aNewArray->SetValue(a, aRefs->Value(a));
437 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
438 aRefs->SetInternalArray(aNewArray);
442 FeaturePtr Model_Document::addFeature(std::string theID)
444 TDF_Label anEmptyLab;
445 FeaturePtr anEmptyFeature;
446 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
449 std::shared_ptr<Model_Document> aDocToAdd = std::dynamic_pointer_cast<Model_Document>(
450 aFeature->documentToAdd());
452 TDF_Label aFeatureLab;
453 if (!aFeature->isAction()) { // do not add action to the data model
454 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
455 aFeatureLab = aFeaturesLab.NewChild();
456 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
457 // keep the feature ID to restore document later correctly
458 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
459 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
460 // store feature in the history of features array
461 if (aFeature->isInHistory()) {
462 AddToRefArray(aFeaturesLab, aFeatureLab);
465 if (!aFeature->isAction()) { // do not add action to the data model
466 // event: feature is added
467 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
468 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
469 } else { // feature must be executed
470 // no creation event => updater not working, problem with remove part
477 /// Appenad to the array of references a new referenced label.
478 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
479 /// \returns the index of removed element
480 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
483 int aResult = -1; // no returned
484 Handle(TDataStd_ReferenceArray) aRefs;
485 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
486 if (aRefs->Length() == 1) { // just erase an array
487 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
488 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
491 } else { // reduce the array
492 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
494 int aCount = aRefs->Lower();
495 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
496 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
500 aNewArray->SetValue(aCount, aRefs->Value(a));
503 aRefs->SetInternalArray(aNewArray);
509 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
512 // check the feature: it must have no depended objects on it
513 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
514 for(; aResIter != theFeature->results().cend(); aResIter++) {
515 std::shared_ptr<Model_Data> aData =
516 std::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
517 if (aData && !aData->refsToMe().empty()) {
519 "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
525 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
527 TDF_Label aFeatureLabel = aData->label().Father();
528 if (myObjs.IsBound(aFeatureLabel))
529 myObjs.UnBind(aFeatureLabel);
531 return; // not found feature => do not remove
534 // erase all attributes under the label of feature
535 aFeatureLabel.ForgetAllAttributes();
536 // remove it from the references array
537 if (theFeature->isInHistory()) {
538 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
541 // event: feature is deleted
542 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
545 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
547 if (myObjs.IsBound(theLabel))
548 return myObjs.Find(theLabel);
549 return FeaturePtr(); // not found
552 ObjectPtr Model_Document::object(TDF_Label theLabel)
554 // try feature by label
555 FeaturePtr aFeature = feature(theLabel);
557 return feature(theLabel);
558 TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
559 aFeature = feature(aFeatureLabel);
561 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
562 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
563 for (; aRIter != aResults.cend(); aRIter++) {
564 std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
566 if (aResData->label().Father().IsEqual(theLabel))
570 return FeaturePtr(); // not found
573 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
575 // just store sub-document identifier here to manage it later
576 if (mySubs.find(theDocID) == mySubs.end())
577 mySubs.insert(theDocID);
578 return Model_Application::getApplication()->getDocument(theDocID);
581 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
583 // just store sub-document identifier here to manage it later
584 if (mySubs.find(theDocID) == mySubs.end())
585 mySubs.insert(theDocID);
586 return std::dynamic_pointer_cast<Model_Document>(
587 Model_Application::getApplication()->getDocument(theDocID));
590 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
591 const bool theHidden)
593 if (theGroupID == ModelAPI_Feature::group()) {
596 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
597 for (; aLabIter.More(); aLabIter.Next()) {
598 if (theIndex == anIndex) {
599 TDF_Label aFLabel = aLabIter.Value()->Label();
600 return feature(aFLabel);
605 Handle(TDataStd_ReferenceArray) aRefs;
606 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
608 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
610 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
611 return feature(aFeatureLabel);
614 // comment must be in any feature: it is kind
616 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
617 for (; aLabIter.More(); aLabIter.Next()) {
618 TDF_Label aFLabel = aLabIter.Value()->Label();
619 FeaturePtr aFeature = feature(aFLabel);
620 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
621 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
622 for (; aRIter != aResults.cend(); aRIter++) {
623 if ((*aRIter)->groupName() != theGroupID) continue;
624 bool isIn = theHidden && (*aRIter)->isInHistory();
625 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
626 isIn = !(*aRIter)->isConcealed();
629 if (anIndex == theIndex)
640 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
643 if (theGroupID == ModelAPI_Feature::group()) {
645 return myObjs.Size();
647 Handle(TDataStd_ReferenceArray) aRefs;
648 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
649 return aRefs->Length();
652 // comment must be in any feature: it is kind
653 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
654 for (; aLabIter.More(); aLabIter.Next()) {
655 TDF_Label aFLabel = aLabIter.Value()->Label();
656 FeaturePtr aFeature = feature(aFLabel);
657 if (!aFeature) // may be on close
659 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
660 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
661 for (; aRIter != aResults.cend(); aRIter++) {
662 if ((*aRIter)->groupName() != theGroupID) continue;
663 bool isIn = theHidden;
664 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
665 isIn = !(*aRIter)->isConcealed();
672 // group is not found
676 TDF_Label Model_Document::featuresLabel()
678 return myDoc->Main().FindChild(TAG_OBJECTS);
681 void Model_Document::setUniqueName(FeaturePtr theFeature)
683 if (!theFeature->data()->name().empty())
684 return; // not needed, name is already defined
685 std::string aName; // result
686 // first count all objects of such kind to start with index = count + 1
688 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
689 for (; aFIter.More(); aFIter.Next()) {
690 if (aFIter.Value()->getKind() == theFeature->getKind())
693 // generate candidate name
694 std::stringstream aNameStream;
695 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
696 aName = aNameStream.str();
697 // check this is unique, if not, increase index by 1
698 for (aFIter.Initialize(myObjs); aFIter.More();) {
699 FeaturePtr aFeature = aFIter.Value();
700 bool isSameName = aFeature->data()->name() == aName;
701 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
702 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
703 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
704 for (; aRIter != aResults.cend(); aRIter++) {
705 isSameName = (*aRIter)->data()->name() == aName;
710 std::stringstream aNameStream;
711 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
712 aName = aNameStream.str();
713 // reinitialize iterator to make sure a new name is unique
714 aFIter.Initialize(myObjs);
718 theFeature->data()->setName(aName);
721 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
723 std::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
725 std::shared_ptr<Model_Data> aData(new Model_Data);
726 aData->setLabel(theLab.FindChild(theTag));
727 aData->setObject(theObj);
728 theObj->setDoc(aThis);
729 theObj->setData(aData);
730 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
732 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
733 aFeature->initAttributes();
737 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
739 std::shared_ptr<ModelAPI_Document> aThis =
740 Model_Application::getApplication()->getDocument(myID);
741 // after all updates, sends a message that groups of features were created or updated
742 std::static_pointer_cast<Model_Session>(Model_Session::get())
743 ->setCheckTransactions(false);
744 Events_Loop* aLoop = Events_Loop::loop();
745 aLoop->activateFlushes(false);
747 // update all objects by checking are they of labels or not
748 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
749 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
750 for (; aLabIter.More(); aLabIter.Next()) {
751 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
753 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
755 aFeature = ModelAPI_Session::get()->createFeature(
756 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
758 if (!aFeature) { // somethig is wrong, most probably, the opened document has invalid structure
759 Events_Error::send("Invalid type of object in the document");
760 aLabIter.Value()->Label().ForgetAllAttributes();
763 // this must be before "setData" to redo the sketch line correctly
764 myObjs.Bind(aFeatureLabel, aFeature);
765 aNewFeatures.insert(aFeature);
766 initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
768 // event: model is updated
769 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
770 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
771 } else { // nothing is changed, both iterators are incremented
772 aFeature = myObjs.Find(aFeatureLabel);
773 aKeptFeatures.insert(aFeature);
774 if (theMarkUpdated) {
775 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
776 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
780 // update results of thefeatures (after features created because they may be connected, like sketch and sub elements)
781 TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
782 for (; aLabIter2.More(); aLabIter2.Next()) {
783 TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
784 if (myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
785 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
786 updateResults(aFeature);
790 // check all features are checked: if not => it was removed
791 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
792 while (aFIter.More()) {
793 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
794 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
795 FeaturePtr aFeature = aFIter.Value();
796 // event: model is updated
797 //if (aFeature->isInHistory()) {
798 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
800 // results of this feature must be redisplayed (hided)
801 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
802 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
803 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
804 // redisplay also removed feature (used for sketch and AISObject)
805 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
807 // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
808 TDF_Label aLab = aFIter.Key();
815 if (theUpdateReferences) {
816 synchronizeBackRefs();
819 myExecuteFeatures = false;
820 aLoop->activateFlushes(true);
822 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
823 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
824 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
825 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
826 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
827 std::static_pointer_cast<Model_Session>(Model_Session::get())
828 ->setCheckTransactions(true);
829 myExecuteFeatures = true;
832 void Model_Document::synchronizeBackRefs()
834 std::shared_ptr<ModelAPI_Document> aThis =
835 Model_Application::getApplication()->getDocument(myID);
836 // keeps the concealed flags of result to catch the change and create created/deleted events
837 std::list<std::pair<ResultPtr, bool> > aConcealed;
838 // first cycle: erase all data about back-references
839 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
840 for(; aFeatures.More(); aFeatures.Next()) {
841 FeaturePtr aFeature = aFeatures.Value();
842 std::shared_ptr<Model_Data> aFData =
843 std::dynamic_pointer_cast<Model_Data>(aFeature->data());
845 aFData->eraseBackReferences();
847 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
848 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
849 for (; aRIter != aResults.cend(); aRIter++) {
850 std::shared_ptr<Model_Data> aResData =
851 std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
853 aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
854 aResData->eraseBackReferences();
859 // second cycle: set new back-references: only features may have reference, iterate only them
860 ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
861 for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
862 FeaturePtr aFeature = aFeatures.Value();
863 std::shared_ptr<Model_Data> aFData =
864 std::dynamic_pointer_cast<Model_Data>(aFeature->data());
866 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
867 aFData->referencesToObjects(aRefs);
868 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
869 for(; aRefsIter != aRefs.end(); aRefsIter++) {
870 std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
871 for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
873 std::shared_ptr<Model_Data> aRefData =
874 std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
875 aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
881 std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
882 for(; aCIter != aConcealed.end(); aCIter++) {
883 if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
884 if (aCIter->second) { // was concealed become not => creation event
885 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
886 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
887 } else { // was not concealed become concealed => delete event
888 ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
889 // redisplay for the viewer (it must be disappeared also)
890 static Events_ID EVENT_DISP =
891 Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
892 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
898 TDF_Label Model_Document::resultLabel(
899 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
901 const std::shared_ptr<Model_Data>& aData =
902 std::dynamic_pointer_cast<Model_Data>(theFeatureData);
903 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
906 void Model_Document::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
907 std::shared_ptr<ModelAPI_Result> theResult,
908 const int theResultIndex)
910 std::shared_ptr<ModelAPI_Document> aThis =
911 Model_Application::getApplication()->getDocument(myID);
912 theResult->setDoc(aThis);
913 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
914 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
915 theResult->data()->setName(theFeatureData->name());
919 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
920 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
922 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
923 TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
924 ObjectPtr anOldObject = object(aLab);
925 std::shared_ptr<ModelAPI_ResultConstruction> aResult;
927 aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
930 aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
931 storeResult(theFeatureData, aResult, theIndex);
936 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
937 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
939 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
940 TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
941 ObjectPtr anOldObject = object(aLab);
942 std::shared_ptr<ModelAPI_ResultBody> aResult;
944 aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
947 aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
948 storeResult(theFeatureData, aResult, theIndex);
953 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
954 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
956 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
957 TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
958 ObjectPtr anOldObject = object(aLab);
959 std::shared_ptr<ModelAPI_ResultPart> aResult;
961 aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
964 aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
965 storeResult(theFeatureData, aResult, theIndex);
970 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
971 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
973 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
974 TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
975 ObjectPtr anOldObject = object(aLab);
976 std::shared_ptr<ModelAPI_ResultGroup> aResult;
978 aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
981 aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
982 storeResult(theFeatureData, aResult, theIndex);
987 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
988 const std::shared_ptr<ModelAPI_Result>& theResult)
990 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
992 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
993 return feature(aFeatureLab);
998 void Model_Document::updateResults(FeaturePtr theFeature)
1000 // for not persistent is will be done by parametric updater automatically
1001 //if (!theFeature->isPersistentResult()) return;
1002 // check the existing results and remove them if there is nothing on the label
1003 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1004 while(aResIter != theFeature->results().cend()) {
1005 ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1007 if (!aBody->data()->isValid()) {
1008 // found a disappeared result => remove it
1009 theFeature->removeResult(aBody);
1010 // start iterate from beginning because iterator is corrupted by removing
1011 aResIter = theFeature->results().cbegin();
1017 // check that results are presented on all labels
1018 int aResSize = theFeature->results().size();
1019 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1020 for(; aLabIter.More(); aLabIter.Next()) {
1021 // here must be GUID of the feature
1022 int aResIndex = aLabIter.Value().Tag() - 1;
1024 if (aResSize <= aResIndex) {
1025 TDF_Label anArgLab = aLabIter.Value();
1026 Handle(TDataStd_Comment) aGroup;
1027 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1028 if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1029 aNewBody = createBody(theFeature->data(), aResIndex);
1030 } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1031 aNewBody = createPart(theFeature->data(), aResIndex);
1032 } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1033 theFeature->execute(); // construction shapes are needed for sketch solver
1035 } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1036 aNewBody = createGroup(theFeature->data(), aResIndex);
1038 Events_Error::send(std::string("Unknown type of result is found in the document:") +
1039 TCollection_AsciiString(aGroup->Get()).ToCString());
1043 theFeature->setResult(aNewBody, aResIndex);
1049 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1051 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1054 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1056 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);