1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: Model_Document.cxx
4 // Created: 28 Feb 2014
5 // Author: Mikhail PONIKAROV
7 #include <Model_Document.h>
8 #include <Model_Data.h>
9 #include <Model_Application.h>
10 #include <Model_Session.h>
11 #include <Model_Events.h>
12 #include <Model_ResultPart.h>
13 #include <Model_ResultConstruction.h>
14 #include <Model_ResultBody.h>
15 #include <Model_ResultGroup.h>
16 #include <ModelAPI_Validator.h>
17 #include <ModelAPI_CompositeFeature.h>
18 #include <Events_Loop.h>
19 #include <Events_Error.h>
21 #include <TDataStd_Integer.hxx>
22 #include <TDataStd_Comment.hxx>
23 #include <TDF_ChildIDIterator.hxx>
24 #include <TDataStd_ReferenceArray.hxx>
25 #include <TDataStd_HLabelArray1.hxx>
26 #include <TDataStd_Name.hxx>
27 #include <TDF_Reference.hxx>
28 #include <TDF_ChildIDIterator.hxx>
29 #include <TDF_LabelMapHasher.hxx>
30 #include <OSD_File.hxx>
31 #include <OSD_Path.hxx>
39 # define _separator_ '\\'
41 # define _separator_ '/'
44 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
46 static const int TAG_GENERAL = 1; // general properties tag
47 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree (features, results)
48 static const int TAG_HISTORY = 3; // tag of the history sub-tree (python dump)
51 static const int TAG_FEATURE_ARGUMENTS = 1; ///< where the arguments are located
52 static const int TAG_FEATURE_RESULTS = 2; ///< where the results are located
55 /// 0:1:2 - where features are located
56 /// 0:1:2:N:1 - data of the feature N
57 /// 0:1:2:N:2:K:1 - data of the K result of the feature N
59 Model_Document::Model_Document(const std::string theID, const std::string theKind)
60 : myID(theID), myKind(theKind),
61 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
63 myDoc->SetUndoLimit(UNDO_LIMIT);
64 myTransactionSave = 0;
65 myExecuteFeatures = true;
66 // to have something in the document and avoid empty doc open/save problem
67 // in transaction for nesting correct working
69 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
70 myDoc->CommitCommand();
73 /// Returns the file name of this document by the nameof directory and identifuer of a document
74 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
76 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
77 // remove end-separators
78 while(aPath.Length() && (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
79 aPath.Remove(aPath.Length());
81 aPath += theID.c_str();
82 aPath += ".cbf"; // standard binary file extension
86 bool Model_Document::load(const char* theFileName)
88 Handle(Model_Application) anApp = Model_Application::getApplication();
89 if (this == Model_Session::get()->moduleDocument().get()) {
90 anApp->setLoadPath(theFileName);
92 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
93 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
95 aStatus = anApp->Open(aPath, myDoc);
96 } catch (Standard_Failure) {
97 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
99 std::string("Exception in opening of document: ") + aFail->GetMessageString());
102 bool isError = aStatus != PCDM_RS_OK;
105 case PCDM_RS_UnknownDocument:
106 Events_Error::send(std::string("Can not open document"));
108 case PCDM_RS_AlreadyRetrieved:
109 Events_Error::send(std::string("Can not open document: already opened"));
111 case PCDM_RS_AlreadyRetrievedAndModified:
113 std::string("Can not open document: already opened and modified"));
115 case PCDM_RS_NoDriver:
116 Events_Error::send(std::string("Can not open document: driver library is not found"));
118 case PCDM_RS_UnknownFileDriver:
119 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
121 case PCDM_RS_OpenError:
122 Events_Error::send(std::string("Can not open document: file open error"));
124 case PCDM_RS_NoVersion:
125 Events_Error::send(std::string("Can not open document: invalid version"));
127 case PCDM_RS_NoModel:
128 Events_Error::send(std::string("Can not open document: no data model"));
130 case PCDM_RS_NoDocument:
131 Events_Error::send(std::string("Can not open document: no document inside"));
133 case PCDM_RS_FormatFailure:
134 Events_Error::send(std::string("Can not open document: format failure"));
136 case PCDM_RS_TypeNotFoundInSchema:
137 Events_Error::send(std::string("Can not open document: invalid object"));
139 case PCDM_RS_UnrecognizedFileFormat:
140 Events_Error::send(std::string("Can not open document: unrecognized file format"));
142 case PCDM_RS_MakeFailure:
143 Events_Error::send(std::string("Can not open document: make failure"));
145 case PCDM_RS_PermissionDenied:
146 Events_Error::send(std::string("Can not open document: permission denied"));
148 case PCDM_RS_DriverFailure:
149 Events_Error::send(std::string("Can not open document: driver failure"));
152 Events_Error::send(std::string("Can not open document: unknown error"));
157 myDoc->SetUndoLimit(UNDO_LIMIT);
158 // to avoid the problem that feature is created in the current, not this, document
159 std::shared_ptr<Model_Session> aSession =
160 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
161 aSession->setActiveDocument(anApp->getDocument(myID), false);
162 aSession->setCheckTransactions(false);
163 synchronizeFeatures(false, true);
164 aSession->setCheckTransactions(true);
165 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
166 aSession->setActiveDocument(anApp->getDocument(myID), true);
171 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
173 // create a directory in the root document if it is not yet exist
174 Handle(Model_Application) anApp = Model_Application::getApplication();
175 if (this == Model_Session::get()->moduleDocument().get()) {
177 CreateDirectory(theFileName, NULL);
179 mkdir(theFileName, 0x1ff);
182 // filename in the dir is id of document inside of the given directory
183 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
184 PCDM_StoreStatus aStatus;
186 aStatus = anApp->SaveAs(myDoc, aPath);
187 } catch (Standard_Failure) {
188 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
190 std::string("Exception in saving of document: ") + aFail->GetMessageString());
193 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
196 case PCDM_SS_DriverFailure:
197 Events_Error::send(std::string("Can not save document: save driver-library failure"));
199 case PCDM_SS_WriteFailure:
200 Events_Error::send(std::string("Can not save document: file writing failure"));
202 case PCDM_SS_Failure:
204 Events_Error::send(std::string("Can not save document"));
208 myTransactionSave = myTransactions.size();
209 if (isDone) { // save also sub-documents if any
210 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
211 const std::set<std::string> aSubs = subDocuments(false);
212 std::set<std::string>::iterator aSubIter = aSubs.begin();
213 for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
214 if (anApp->isLoadByDemand(*aSubIter)) {
215 // copy not-activated document that is not in the memory
216 std::string aDocName = *aSubIter;
217 if (!aDocName.empty()) {
219 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
220 OSD_Path aPath(aSubPath);
221 OSD_File aFile(aPath);
222 if (aFile.Exists()) {
223 TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
224 OSD_Path aDestination(aDestinationDir);
225 aFile.Copy(aDestination);
226 theResults.push_back(aDestinationDir.ToCString());
229 std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
232 } else { // simply save opened document
233 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
240 void Model_Document::close(const bool theForever)
242 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
243 if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
244 aPM->setActiveDocument(aPM->moduleDocument());
245 } else if (this == aPM->moduleDocument().get()) {
246 // erase the active document if root is closed
247 aPM->setActiveDocument(DocumentPtr());
250 const std::set<std::string> aSubs = subDocuments(true);
251 std::set<std::string>::iterator aSubIter = aSubs.begin();
252 for (; aSubIter != aSubs.end(); aSubIter++)
253 subDoc(*aSubIter)->close(theForever);
255 // close for thid document needs no transaction in this document
256 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
258 // delete all features of this document
259 std::shared_ptr<ModelAPI_Document> aThis =
260 Model_Application::getApplication()->getDocument(myID);
261 Events_Loop* aLoop = Events_Loop::loop();
262 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myObjs);
263 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
264 FeaturePtr aFeature = aFeaturesIter.Value();
265 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
266 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
267 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
268 aFeature->eraseResults();
269 if (theForever) { // issue #294: do not delete content of the document until it can be redone
272 aFeature->data()->execState(ModelAPI_StateMustBeUpdated);
278 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
279 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
281 // close all only if it is really asked, otherwise it can be undoed/redoed
283 if (myDoc->CanClose() == CDM_CCS_OK)
287 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
290 void Model_Document::startOperation()
292 if (myDoc->HasOpenCommand()) { // start of nested command
293 if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
294 (*myTransactions.rbegin())++; // if has open command, the list is not empty
296 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
297 myDoc->OpenCommand();
298 } else { // start the simple command
301 // starts a new operation
302 myTransactions.push_back(0);
303 if (!myNestedNum.empty())
304 (*myNestedNum.rbegin())++;
306 // new command for all subs
307 const std::set<std::string> aSubs = subDocuments(true);
308 std::set<std::string>::iterator aSubIter = aSubs.begin();
309 for (; aSubIter != aSubs.end(); aSubIter++)
310 subDoc(*aSubIter)->startOperation();
313 void Model_Document::compactNested()
315 if (!myNestedNum.empty()) {
316 int aNumToCompact = *(myNestedNum.rbegin());
317 int aSumOfTransaction = 0;
318 for(int a = 0; a < aNumToCompact; a++) {
319 aSumOfTransaction += *(myTransactions.rbegin());
320 myTransactions.pop_back();
322 // the latest transaction is the start of lower-level operation which startes the nested
323 *(myTransactions.rbegin()) += aSumOfTransaction;
324 myNestedNum.pop_back();
328 void Model_Document::finishOperation()
330 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
331 static std::shared_ptr<Model_Session> aSession =
332 std::static_pointer_cast<Model_Session>(Model_Session::get());
333 synchronizeBackRefs();
334 Events_Loop* aLoop = Events_Loop::loop();
335 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
336 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
337 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
338 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
339 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
340 // this must be here just after everything is finished but before real transaction stop
341 // to avoid messages about modifications outside of the transaction
342 // and to rebuild everything after all updates and creates
343 if (Model_Session::get()->moduleDocument().get() == this) { // once for root document
344 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
345 static std::shared_ptr<Events_Message> aFinishMsg
346 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
347 Events_Loop::loop()->send(aFinishMsg);
348 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
350 // to avoid "updated" message appearance by updater
351 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
353 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
354 const std::set<std::string> aSubs = subDocuments(true);
355 std::set<std::string>::iterator aSubIter = aSubs.begin();
356 for (; aSubIter != aSubs.end(); aSubIter++)
357 subDoc(*aSubIter)->finishOperation();
359 if (myDoc->CommitCommand()) { // if commit is successfull, just increment counters
360 (*myTransactions.rbegin())++;
363 if (isNestedClosed) {
368 void Model_Document::abortOperation()
370 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
375 } else { // abort the current
376 int aNumTransactions = *myTransactions.rbegin();
377 myTransactions.pop_back();
378 if (!myNestedNum.empty())
379 (*myNestedNum.rbegin())--;
380 // roll back the needed number of transactions
381 myDoc->AbortCommand();
382 for(int a = 0; a < aNumTransactions; a++)
386 synchronizeFeatures(true, false); // references were not changed since transaction start
387 // abort for all subs
388 const std::set<std::string> aSubs = subDocuments(true);
389 std::set<std::string>::iterator aSubIter = aSubs.begin();
390 for (; aSubIter != aSubs.end(); aSubIter++)
391 subDoc(*aSubIter)->abortOperation();
394 bool Model_Document::isOperation()
396 // operation is opened for all documents: no need to check subs
397 return myDoc->HasOpenCommand() == Standard_True ;
400 bool Model_Document::isModified()
402 // is modified if at least one operation was commited and not undoed
403 return myTransactions.size() != myTransactionSave || isOperation();
406 bool Model_Document::canUndo()
408 if (myDoc->GetAvailableUndos() > 0 && (myNestedNum.empty() || *myNestedNum.rbegin() != 0) &&
409 !myTransactions.empty() /* for omitting the first useless transaction */)
411 // check other subs contains operation that can be undoed
412 const std::set<std::string> aSubs = subDocuments(true);
413 std::set<std::string>::iterator aSubIter = aSubs.begin();
414 for (; aSubIter != aSubs.end(); aSubIter++)
415 if (subDoc(*aSubIter)->canUndo())
420 void Model_Document::undoInternal(const bool theWithSubs)
422 int aNumTransactions = *myTransactions.rbegin();
423 myTransactions.pop_back();
424 myRedos.push_back(aNumTransactions);
425 if (!myNestedNum.empty())
426 (*myNestedNum.rbegin())--;
427 // roll back the needed number of transactions
428 for(int a = 0; a < aNumTransactions; a++)
432 synchronizeFeatures(true, true);
434 const std::set<std::string> aSubs = subDocuments(true);
435 std::set<std::string>::iterator aSubIter = aSubs.begin();
436 for (; aSubIter != aSubs.end(); aSubIter++)
437 subDoc(*aSubIter)->undo();
441 void Model_Document::undo()
446 bool Model_Document::canRedo()
448 if (myDoc->GetAvailableRedos() > 0)
450 // check other subs contains operation that can be redoed
451 const std::set<std::string> aSubs = subDocuments(true);
452 std::set<std::string>::iterator aSubIter = aSubs.begin();
453 for (; aSubIter != aSubs.end(); aSubIter++)
454 if (subDoc(*aSubIter)->canRedo())
459 void Model_Document::redo()
461 if (!myNestedNum.empty())
462 (*myNestedNum.rbegin())++;
463 int aNumRedos = *myRedos.rbegin();
465 myTransactions.push_back(aNumRedos);
466 for(int a = 0; a < aNumRedos; a++)
469 synchronizeFeatures(true, true);
471 const std::set<std::string> aSubs = subDocuments(true);
472 std::set<std::string>::iterator aSubIter = aSubs.begin();
473 for (; aSubIter != aSubs.end(); aSubIter++)
474 subDoc(*aSubIter)->redo();
477 /// Append to the array of references a new referenced label
478 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
480 Handle(TDataStd_ReferenceArray) aRefs;
481 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
482 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
483 aRefs->SetValue(0, theReferenced);
484 } else { // extend array by one more element
485 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
487 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
488 aNewArray->SetValue(a, aRefs->Value(a));
490 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
491 aRefs->SetInternalArray(aNewArray);
495 FeaturePtr Model_Document::addFeature(std::string theID)
497 TDF_Label anEmptyLab;
498 FeaturePtr anEmptyFeature;
499 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
502 std::shared_ptr<Model_Document> aDocToAdd = std::dynamic_pointer_cast<Model_Document>(
503 aFeature->documentToAdd());
505 TDF_Label aFeatureLab;
506 if (!aFeature->isAction()) { // do not add action to the data model
507 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
508 aFeatureLab = aFeaturesLab.NewChild();
509 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
510 // keep the feature ID to restore document later correctly
511 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
512 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
513 // store feature in the history of features array
514 if (aFeature->isInHistory()) {
515 AddToRefArray(aFeaturesLab, aFeatureLab);
518 if (!aFeature->isAction()) { // do not add action to the data model
519 // event: feature is added
520 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
521 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
522 } else { // feature must be executed
523 // no creation event => updater not working, problem with remove part
530 /// Appenad to the array of references a new referenced label.
531 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
532 /// \returns the index of removed element
533 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
536 int aResult = -1; // no returned
537 Handle(TDataStd_ReferenceArray) aRefs;
538 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
539 if (aRefs->Length() == 1) { // just erase an array
540 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
541 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
544 } else { // reduce the array
545 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
547 int aCount = aRefs->Lower();
548 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
549 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
553 aNewArray->SetValue(aCount, aRefs->Value(a));
556 aRefs->SetInternalArray(aNewArray);
562 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
565 // check the feature: it must have no depended objects on it
566 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
567 for(; aResIter != theFeature->results().cend(); aResIter++) {
568 std::shared_ptr<Model_Data> aData =
569 std::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
570 if (aData && !aData->refsToMe().empty()) {
572 "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
578 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
580 TDF_Label aFeatureLabel = aData->label().Father();
581 if (myObjs.IsBound(aFeatureLabel))
582 myObjs.UnBind(aFeatureLabel);
584 return; // not found feature => do not remove
587 // erase all attributes under the label of feature
588 aFeatureLabel.ForgetAllAttributes();
589 // remove it from the references array
590 if (theFeature->isInHistory()) {
591 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
594 // event: feature is deleted
595 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
598 FeaturePtr Model_Document::feature(TDF_Label& theLabel) const
600 if (myObjs.IsBound(theLabel))
601 return myObjs.Find(theLabel);
602 return FeaturePtr(); // not found
605 ObjectPtr Model_Document::object(TDF_Label theLabel)
607 // try feature by label
608 FeaturePtr aFeature = feature(theLabel);
610 return feature(theLabel);
611 TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
612 aFeature = feature(aFeatureLabel);
614 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
615 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
616 for (; aRIter != aResults.cend(); aRIter++) {
617 std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
619 if (aResData->label().Father().IsEqual(theLabel))
623 return FeaturePtr(); // not found
626 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
628 return Model_Application::getApplication()->getDocument(theDocID);
631 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
633 std::set<std::string> aResult;
634 // comment must be in any feature: it is kind
636 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
637 for (; aLabIter.More(); aLabIter.Next()) {
638 TDF_Label aFLabel = aLabIter.Value()->Label();
639 FeaturePtr aFeature = feature(aFLabel);
640 if (aFeature.get()) { // if document is closed the feature may be not in myObjs map
641 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
642 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
643 for (; aRIter != aResults.cend(); aRIter++) {
644 if ((*aRIter)->groupName() != ModelAPI_ResultPart::group()) continue;
645 if ((*aRIter)->isInHistory()) {
646 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRIter);
647 if (aPart && (!theActivatedOnly || aPart->isActivated()))
648 aResult.insert(aPart->data()->name());
656 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
658 // just store sub-document identifier here to manage it later
659 return std::dynamic_pointer_cast<Model_Document>(
660 Model_Application::getApplication()->getDocument(theDocID));
663 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
664 const bool theHidden)
666 if (theGroupID == ModelAPI_Feature::group()) {
669 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
670 for (; aLabIter.More(); aLabIter.Next()) {
671 if (theIndex == anIndex) {
672 TDF_Label aFLabel = aLabIter.Value()->Label();
673 return feature(aFLabel);
678 Handle(TDataStd_ReferenceArray) aRefs;
679 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
681 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
683 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
684 return feature(aFeatureLabel);
687 // comment must be in any feature: it is kind
689 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
690 for (; aLabIter.More(); aLabIter.Next()) {
691 TDF_Label aFLabel = aLabIter.Value()->Label();
692 FeaturePtr aFeature = feature(aFLabel);
693 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
694 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
695 for (; aRIter != aResults.cend(); aRIter++) {
696 if ((*aRIter)->groupName() != theGroupID) continue;
697 bool isIn = theHidden && (*aRIter)->isInHistory();
698 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
699 isIn = !(*aRIter)->isConcealed();
702 if (anIndex == theIndex)
713 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
716 if (theGroupID == ModelAPI_Feature::group()) {
718 return myObjs.Size();
720 Handle(TDataStd_ReferenceArray) aRefs;
721 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
722 return aRefs->Length();
725 // comment must be in any feature: it is kind
726 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
727 for (; aLabIter.More(); aLabIter.Next()) {
728 TDF_Label aFLabel = aLabIter.Value()->Label();
729 FeaturePtr aFeature = feature(aFLabel);
730 if (!aFeature) // may be on close
732 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
733 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
734 for (; aRIter != aResults.cend(); aRIter++) {
735 if ((*aRIter)->groupName() != theGroupID) continue;
736 bool isIn = theHidden;
737 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
738 isIn = !(*aRIter)->isConcealed();
745 // group is not found
749 TDF_Label Model_Document::featuresLabel() const
751 return myDoc->Main().FindChild(TAG_OBJECTS);
754 void Model_Document::setUniqueName(FeaturePtr theFeature)
756 if (!theFeature->data()->name().empty())
757 return; // not needed, name is already defined
758 std::string aName; // result
759 // first count all objects of such kind to start with index = count + 1
761 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
762 for (; aFIter.More(); aFIter.Next()) {
763 if (aFIter.Value()->getKind() == theFeature->getKind())
766 // generate candidate name
767 std::stringstream aNameStream;
768 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
769 aName = aNameStream.str();
770 // check this is unique, if not, increase index by 1
771 for (aFIter.Initialize(myObjs); aFIter.More();) {
772 FeaturePtr aFeature = aFIter.Value();
773 bool isSameName = aFeature->data()->name() == aName;
774 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
775 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
776 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
777 for (; aRIter != aResults.cend(); aRIter++) {
778 isSameName = (*aRIter)->data()->name() == aName;
783 std::stringstream aNameStream;
784 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
785 aName = aNameStream.str();
786 // reinitialize iterator to make sure a new name is unique
787 aFIter.Initialize(myObjs);
791 theFeature->data()->setName(aName);
794 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
796 std::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
798 std::shared_ptr<Model_Data> aData(new Model_Data);
799 aData->setLabel(theLab.FindChild(theTag));
800 aData->setObject(theObj);
801 theObj->setDoc(aThis);
802 theObj->setData(aData);
803 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
805 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
806 aFeature->initAttributes();
810 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
812 std::shared_ptr<ModelAPI_Document> aThis =
813 Model_Application::getApplication()->getDocument(myID);
814 // after all updates, sends a message that groups of features were created or updated
815 Events_Loop* aLoop = Events_Loop::loop();
816 aLoop->activateFlushes(false);
818 // update all objects by checking are they of labels or not
819 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
820 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
821 for (; aLabIter.More(); aLabIter.Next()) {
822 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
824 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
826 aFeature = ModelAPI_Session::get()->createFeature(
827 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
829 if (!aFeature) { // somethig is wrong, most probably, the opened document has invalid structure
830 Events_Error::send("Invalid type of object in the document");
831 aLabIter.Value()->Label().ForgetAllAttributes();
834 // this must be before "setData" to redo the sketch line correctly
835 myObjs.Bind(aFeatureLabel, aFeature);
836 aNewFeatures.insert(aFeature);
837 initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
839 // event: model is updated
840 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
841 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
842 } else { // nothing is changed, both iterators are incremented
843 aFeature = myObjs.Find(aFeatureLabel);
844 aKeptFeatures.insert(aFeature);
845 if (theMarkUpdated) {
846 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
847 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
851 // update results of thefeatures (after features created because they may be connected, like sketch and sub elements)
852 std::list<FeaturePtr> aComposites; // composites must be updated after their subs (issue 360)
853 TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
854 for (; aLabIter2.More(); aLabIter2.Next()) {
855 TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
856 if (myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
857 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
858 if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature).get())
859 aComposites.push_back(aFeature);
860 updateResults(aFeature);
863 std::list<FeaturePtr>::iterator aComposite = aComposites.begin();
864 for(; aComposite != aComposites.end(); aComposite++) {
865 updateResults(*aComposite);
868 // check all features are checked: if not => it was removed
869 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
870 while (aFIter.More()) {
871 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
872 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
873 FeaturePtr aFeature = aFIter.Value();
874 // event: model is updated
875 //if (aFeature->isInHistory()) {
876 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
878 // results of this feature must be redisplayed (hided)
879 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
880 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
881 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
882 // redisplay also removed feature (used for sketch and AISObject)
883 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
885 // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
886 myObjs.UnBind(aFIter.Key());
887 // reinitialize iterator because unbind may corrupt the previous order in the map
888 aFIter.Initialize(myObjs);
893 if (theUpdateReferences) {
894 synchronizeBackRefs();
897 myExecuteFeatures = false;
898 aLoop->activateFlushes(true);
900 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
901 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
902 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
903 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
904 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
905 myExecuteFeatures = true;
908 void Model_Document::synchronizeBackRefs()
910 std::shared_ptr<ModelAPI_Document> aThis =
911 Model_Application::getApplication()->getDocument(myID);
912 // keeps the concealed flags of result to catch the change and create created/deleted events
913 std::list<std::pair<ResultPtr, bool> > aConcealed;
914 // first cycle: erase all data about back-references
915 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
916 for(; aFeatures.More(); aFeatures.Next()) {
917 FeaturePtr aFeature = aFeatures.Value();
918 std::shared_ptr<Model_Data> aFData =
919 std::dynamic_pointer_cast<Model_Data>(aFeature->data());
921 aFData->eraseBackReferences();
923 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
924 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
925 for (; aRIter != aResults.cend(); aRIter++) {
926 std::shared_ptr<Model_Data> aResData =
927 std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
929 aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
930 aResData->eraseBackReferences();
935 // second cycle: set new back-references: only features may have reference, iterate only them
936 ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
937 for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
938 FeaturePtr aFeature = aFeatures.Value();
939 std::shared_ptr<Model_Data> aFData =
940 std::dynamic_pointer_cast<Model_Data>(aFeature->data());
942 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
943 aFData->referencesToObjects(aRefs);
944 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
945 for(; aRefsIter != aRefs.end(); aRefsIter++) {
946 std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
947 for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
949 std::shared_ptr<Model_Data> aRefData =
950 std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
951 aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
957 std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
958 for(; aCIter != aConcealed.end(); aCIter++) {
959 if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
960 if (aCIter->second) { // was concealed become not => creation event
961 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
962 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
963 } else { // was not concealed become concealed => delete event
964 ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
965 // redisplay for the viewer (it must be disappeared also)
966 static Events_ID EVENT_DISP =
967 Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
968 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
974 TDF_Label Model_Document::resultLabel(
975 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
977 const std::shared_ptr<Model_Data>& aData =
978 std::dynamic_pointer_cast<Model_Data>(theFeatureData);
979 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
982 void Model_Document::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
983 std::shared_ptr<ModelAPI_Result> theResult,
984 const int theResultIndex)
986 std::shared_ptr<ModelAPI_Document> aThis =
987 Model_Application::getApplication()->getDocument(myID);
988 theResult->setDoc(aThis);
989 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
990 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
991 theResult->data()->setName(theFeatureData->name());
995 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
996 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
998 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
999 TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
1000 ObjectPtr anOldObject = object(aLab);
1001 std::shared_ptr<ModelAPI_ResultConstruction> aResult;
1003 aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
1006 aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
1007 storeResult(theFeatureData, aResult, theIndex);
1012 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1013 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1015 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1016 TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1017 ObjectPtr anOldObject = object(aLab);
1018 std::shared_ptr<ModelAPI_ResultBody> aResult;
1020 aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1023 aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1024 storeResult(theFeatureData, aResult, theIndex);
1029 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1030 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1032 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1033 TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1034 ObjectPtr anOldObject = object(aLab);
1035 std::shared_ptr<ModelAPI_ResultPart> aResult;
1037 aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1040 aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1041 storeResult(theFeatureData, aResult, theIndex);
1046 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1047 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1049 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1050 TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1051 ObjectPtr anOldObject = object(aLab);
1052 std::shared_ptr<ModelAPI_ResultGroup> aResult;
1054 aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1057 aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1058 storeResult(theFeatureData, aResult, theIndex);
1063 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1064 const std::shared_ptr<ModelAPI_Result>& theResult)
1066 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1068 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1069 return feature(aFeatureLab);
1071 return FeaturePtr();
1074 void Model_Document::updateResults(FeaturePtr theFeature)
1076 // for not persistent is will be done by parametric updater automatically
1077 //if (!theFeature->isPersistentResult()) return;
1078 // check the existing results and remove them if there is nothing on the label
1079 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1080 while(aResIter != theFeature->results().cend()) {
1081 ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1083 if (!aBody->data()->isValid()) {
1084 // found a disappeared result => remove it
1085 theFeature->removeResult(aBody);
1086 // start iterate from beginning because iterator is corrupted by removing
1087 aResIter = theFeature->results().cbegin();
1093 // it may be on undo
1094 if (!theFeature->data() || !theFeature->data()->isValid())
1096 // check that results are presented on all labels
1097 int aResSize = theFeature->results().size();
1098 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1099 for(; aLabIter.More(); aLabIter.Next()) {
1100 // here must be GUID of the feature
1101 int aResIndex = aLabIter.Value().Tag() - 1;
1103 if (aResSize <= aResIndex) {
1104 TDF_Label anArgLab = aLabIter.Value();
1105 Handle(TDataStd_Comment) aGroup;
1106 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1107 if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1108 aNewBody = createBody(theFeature->data(), aResIndex);
1109 } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1110 aNewBody = createPart(theFeature->data(), aResIndex);
1111 } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1112 theFeature->execute(); // construction shapes are needed for sketch solver
1114 } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1115 aNewBody = createGroup(theFeature->data(), aResIndex);
1117 Events_Error::send(std::string("Unknown type of result is found in the document:") +
1118 TCollection_AsciiString(aGroup->Get()).ToCString());
1122 theFeature->setResult(aNewBody, aResIndex);
1128 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1130 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1133 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1135 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1138 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1140 myNamingNames[theName] = theLabel;
1143 TDF_Label Model_Document::findNamingName(std::string theName)
1145 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
1146 if (aFind == myNamingNames.end())
1147 return TDF_Label(); // not found
1148 return aFind->second;
1151 ResultPtr Model_Document::findByName(const std::string theName)
1153 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myObjs);
1154 for(; anObjIter.More(); anObjIter.Next()) {
1155 FeaturePtr& aFeature = anObjIter.ChangeValue();
1156 if (!aFeature) // may be on close
1158 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
1159 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
1160 for (; aRIter != aResults.cend(); aRIter++) {
1161 if (aRIter->get() && (*aRIter)->data() && (*aRIter)->data()->isValid() &&
1162 (*aRIter)->data()->name() == theName) {