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 <Events_Loop.h>
18 #include <Events_Error.h>
20 #include <TDataStd_Integer.hxx>
21 #include <TDataStd_Comment.hxx>
22 #include <TDF_ChildIDIterator.hxx>
23 #include <TDataStd_ReferenceArray.hxx>
24 #include <TDataStd_HLabelArray1.hxx>
25 #include <TDataStd_Name.hxx>
26 #include <TDF_Reference.hxx>
27 #include <TDF_ChildIDIterator.hxx>
28 #include <TDF_LabelMapHasher.hxx>
29 #include <OSD_File.hxx>
30 #include <OSD_Path.hxx>
38 # define _separator_ '\\'
40 # define _separator_ '/'
43 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
45 static const int TAG_GENERAL = 1; // general properties tag
46 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree (features, results)
47 static const int TAG_HISTORY = 3; // tag of the history sub-tree (python dump)
50 static const int TAG_FEATURE_ARGUMENTS = 1; ///< where the arguments are located
51 static const int TAG_FEATURE_RESULTS = 2; ///< where the results are located
54 /// 0:1:2 - where features are located
55 /// 0:1:2:N:1 - data of the feature N
56 /// 0:1:2:N:2:K:1 - data of the K result of the feature N
58 Model_Document::Model_Document(const std::string theID, const std::string theKind)
59 : myID(theID), myKind(theKind),
60 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
62 myDoc->SetUndoLimit(UNDO_LIMIT);
63 myTransactionsCounter = 0;
64 myTransactionSave = 0;
66 myExecuteFeatures = true;
67 // to have something in the document and avoid empty doc open/save problem
68 // in transaction for nesting correct working
70 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
71 myDoc->CommitCommand();
74 /// Returns the file name of this document by the nameof directory and identifuer of a document
75 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
77 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
78 // remove end-separators
79 while(aPath.Length() && (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
80 aPath.Remove(aPath.Length());
82 aPath += theID.c_str();
83 aPath += ".cbf"; // standard binary file extension
87 bool Model_Document::load(const char* theFileName)
89 Handle(Model_Application) anApp = Model_Application::getApplication();
90 if (this == Model_Session::get()->moduleDocument().get()) {
91 anApp->setLoadPath(theFileName);
93 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
94 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
96 aStatus = anApp->Open(aPath, myDoc);
97 } catch (Standard_Failure) {
98 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
100 std::string("Exception in opening of document: ") + aFail->GetMessageString());
103 bool isError = aStatus != PCDM_RS_OK;
106 case PCDM_RS_UnknownDocument:
107 Events_Error::send(std::string("Can not open document"));
109 case PCDM_RS_AlreadyRetrieved:
110 Events_Error::send(std::string("Can not open document: already opened"));
112 case PCDM_RS_AlreadyRetrievedAndModified:
114 std::string("Can not open document: already opened and modified"));
116 case PCDM_RS_NoDriver:
117 Events_Error::send(std::string("Can not open document: driver library is not found"));
119 case PCDM_RS_UnknownFileDriver:
120 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
122 case PCDM_RS_OpenError:
123 Events_Error::send(std::string("Can not open document: file open error"));
125 case PCDM_RS_NoVersion:
126 Events_Error::send(std::string("Can not open document: invalid version"));
128 case PCDM_RS_NoModel:
129 Events_Error::send(std::string("Can not open document: no data model"));
131 case PCDM_RS_NoDocument:
132 Events_Error::send(std::string("Can not open document: no document inside"));
134 case PCDM_RS_FormatFailure:
135 Events_Error::send(std::string("Can not open document: format failure"));
137 case PCDM_RS_TypeNotFoundInSchema:
138 Events_Error::send(std::string("Can not open document: invalid object"));
140 case PCDM_RS_UnrecognizedFileFormat:
141 Events_Error::send(std::string("Can not open document: unrecognized file format"));
143 case PCDM_RS_MakeFailure:
144 Events_Error::send(std::string("Can not open document: make failure"));
146 case PCDM_RS_PermissionDenied:
147 Events_Error::send(std::string("Can not open document: permission denied"));
149 case PCDM_RS_DriverFailure:
150 Events_Error::send(std::string("Can not open document: driver failure"));
153 Events_Error::send(std::string("Can not open document: unknown error"));
158 myDoc->SetUndoLimit(UNDO_LIMIT);
159 // to avoid the problem that feature is created in the current, not this, document
160 Model_Session::get()->setActiveDocument(anApp->getDocument(myID), false);
161 synchronizeFeatures(false, true);
162 Model_Session::get()->setActiveDocument(Model_Session::get()->moduleDocument(), false);
163 Model_Session::get()->setActiveDocument(anApp->getDocument(myID), true);
168 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
170 // create a directory in the root document if it is not yet exist
171 Handle(Model_Application) anApp = Model_Application::getApplication();
172 if (this == Model_Session::get()->moduleDocument().get()) {
174 CreateDirectory(theFileName, NULL);
176 mkdir(theFileName, 0x1ff);
179 // filename in the dir is id of document inside of the given directory
180 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
181 PCDM_StoreStatus aStatus;
183 aStatus = anApp->SaveAs(myDoc, aPath);
184 } catch (Standard_Failure) {
185 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
187 std::string("Exception in saving of document: ") + aFail->GetMessageString());
190 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
193 case PCDM_SS_DriverFailure:
194 Events_Error::send(std::string("Can not save document: save driver-library failure"));
196 case PCDM_SS_WriteFailure:
197 Events_Error::send(std::string("Can not save document: file writing failure"));
199 case PCDM_SS_Failure:
201 Events_Error::send(std::string("Can not save document"));
205 myTransactionSave = myTransactionsCounter;
206 if (isDone) { // save also sub-documents if any
207 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
208 const std::set<std::string> aSubs = subDocuments(false);
209 std::set<std::string>::iterator aSubIter = aSubs.begin();
210 for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
211 if (anApp->isLoadByDemand(*aSubIter)) {
212 // copy not-activated document that is not in the memory
213 std::string aDocName = *aSubIter;
214 if (!aDocName.empty()) {
216 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
217 OSD_Path aPath(aSubPath);
218 OSD_File aFile(aPath);
219 if (aFile.Exists()) {
220 TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
221 OSD_Path aDestination(aDestinationDir);
222 aFile.Copy(aDestination);
223 theResults.push_back(aDestinationDir.ToCString());
226 std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
229 } else { // simply save opened document
230 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
237 void Model_Document::close(const bool theForever)
239 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
240 if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
241 aPM->setActiveDocument(aPM->moduleDocument());
244 const std::set<std::string> aSubs = subDocuments(true);
245 std::set<std::string>::iterator aSubIter = aSubs.begin();
246 for (; aSubIter != aSubs.end(); aSubIter++)
247 subDoc(*aSubIter)->close(theForever);
249 // close for thid document needs no transaction in this document
250 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
252 // delete all features of this document
253 std::shared_ptr<ModelAPI_Document> aThis =
254 Model_Application::getApplication()->getDocument(myID);
255 Events_Loop* aLoop = Events_Loop::loop();
256 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myObjs);
257 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
258 FeaturePtr aFeature = aFeaturesIter.Value();
259 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
260 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
261 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
262 aFeature->eraseResults();
266 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
267 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
269 // close all only if it is really asked, otherwise it can be undoed/redoed
271 if (myDoc->CanClose() == CDM_CCS_OK)
275 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
278 void Model_Document::startOperation()
280 if (myDoc->HasOpenCommand()) { // start of nested command
281 if (myNestedNum == -1) {
283 myDoc->InitDeltaCompaction();
285 myIsEmptyTr[myTransactionsCounter] = !myDoc->CommitCommand();
286 myTransactionsCounter++;
287 myDoc->OpenCommand();
288 } else { // start the simple command
291 // new command for all subs
292 const std::set<std::string> aSubs = subDocuments(true);
293 std::set<std::string>::iterator aSubIter = aSubs.begin();
294 for (; aSubIter != aSubs.end(); aSubIter++)
295 subDoc(*aSubIter)->startOperation();
298 bool Model_Document::compactNested()
300 bool allWasEmpty = true;
301 while (myNestedNum != -1) {
302 myTransactionsCounter--;
303 if (!myIsEmptyTr[myTransactionsCounter]) {
306 myIsEmptyTr.erase(myTransactionsCounter);
309 myIsEmptyTr[myTransactionsCounter] = allWasEmpty;
310 myTransactionsCounter++;
312 // Issue 151: if everything is empty, it is a problem for OCCT to work with it,
313 // just commit the empty that returns nothing
314 myDoc->CommitCommand();
316 myDoc->PerformDeltaCompaction();
321 void Model_Document::finishOperation()
323 // just to be sure that everybody knows that changes were performed
324 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
325 std::static_pointer_cast<Model_Session>(Model_Session::get())
326 ->setCheckTransactions(false); // for nested transaction commit
327 synchronizeBackRefs();
328 Events_Loop* aLoop = Events_Loop::loop();
329 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
330 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
331 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
332 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
333 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
334 // this must be here just after everything is finished but before real transaction stop
335 // to avoid messages about modifications outside of the transaction
336 // and to rebuild everything after all updates and creates
337 if (Model_Session::get()->moduleDocument().get() == this) { // once for root document
338 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
339 static std::shared_ptr<Events_Message> aFinishMsg
340 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
341 Events_Loop::loop()->send(aFinishMsg);
342 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
344 // to avoid "updated" message appearance by updater
345 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
347 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
348 std::static_pointer_cast<Model_Session>(Model_Session::get())
349 ->setCheckTransactions(true); // for nested transaction commit
351 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
352 const std::set<std::string> aSubs = subDocuments(true);
353 std::set<std::string>::iterator aSubIter = aSubs.begin();
354 for (; aSubIter != aSubs.end(); aSubIter++)
355 subDoc(*aSubIter)->finishOperation();
357 if (myNestedNum != -1) // this nested transaction is owervritten
359 if (!myDoc->HasOpenCommand()) {
360 if (myNestedNum != -1) {
365 // returns false if delta is empty and no transaction was made
366 myIsEmptyTr[myTransactionsCounter] = !myDoc->CommitCommand(); // && (myNestedNum == -1);
367 myTransactionsCounter++;
371 void Model_Document::abortOperation()
373 if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
374 // first compact all nested
375 if (compactNested()) {
376 myDoc->Undo(); // undo only compacted, if not: do not undo the empty transaction
379 myTransactionsCounter--;
380 myIsEmptyTr.erase(myTransactionsCounter);
382 if (myNestedNum == 0) // abort only high-level
384 myDoc->AbortCommand();
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 myTransactionsCounter != myTransactionSave || isOperation();
406 bool Model_Document::canUndo()
408 if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
409 && myTransactionsCounter != 0 /* 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::undo()
422 myTransactionsCounter--;
425 if (!myIsEmptyTr[myTransactionsCounter])
427 synchronizeFeatures(true, true);
429 const std::set<std::string> aSubs = subDocuments(true);
430 std::set<std::string>::iterator aSubIter = aSubs.begin();
431 for (; aSubIter != aSubs.end(); aSubIter++)
432 subDoc(*aSubIter)->undo();
435 bool Model_Document::canRedo()
437 if (myDoc->GetAvailableRedos() > 0)
439 // check other subs contains operation that can be redoed
440 const std::set<std::string> aSubs = subDocuments(true);
441 std::set<std::string>::iterator aSubIter = aSubs.begin();
442 for (; aSubIter != aSubs.end(); aSubIter++)
443 if (subDoc(*aSubIter)->canRedo())
448 void Model_Document::redo()
450 if (myNestedNum != -1)
452 if (!myIsEmptyTr[myTransactionsCounter])
454 myTransactionsCounter++;
455 synchronizeFeatures(true, true);
457 const std::set<std::string> aSubs = subDocuments(true);
458 std::set<std::string>::iterator aSubIter = aSubs.begin();
459 for (; aSubIter != aSubs.end(); aSubIter++)
460 subDoc(*aSubIter)->redo();
463 /// Appenad to the array of references a new referenced label
464 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
466 Handle(TDataStd_ReferenceArray) aRefs;
467 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
468 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
469 aRefs->SetValue(0, theReferenced);
470 } else { // extend array by one more element
471 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
473 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
474 aNewArray->SetValue(a, aRefs->Value(a));
476 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
477 aRefs->SetInternalArray(aNewArray);
481 FeaturePtr Model_Document::addFeature(std::string theID)
483 TDF_Label anEmptyLab;
484 FeaturePtr anEmptyFeature;
485 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
488 std::shared_ptr<Model_Document> aDocToAdd = std::dynamic_pointer_cast<Model_Document>(
489 aFeature->documentToAdd());
491 TDF_Label aFeatureLab;
492 if (!aFeature->isAction()) { // do not add action to the data model
493 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
494 aFeatureLab = aFeaturesLab.NewChild();
495 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
496 // keep the feature ID to restore document later correctly
497 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
498 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
499 // store feature in the history of features array
500 if (aFeature->isInHistory()) {
501 AddToRefArray(aFeaturesLab, aFeatureLab);
504 if (!aFeature->isAction()) { // do not add action to the data model
505 // event: feature is added
506 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
507 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
508 } else { // feature must be executed
509 // no creation event => updater not working, problem with remove part
516 /// Appenad to the array of references a new referenced label.
517 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
518 /// \returns the index of removed element
519 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
522 int aResult = -1; // no returned
523 Handle(TDataStd_ReferenceArray) aRefs;
524 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
525 if (aRefs->Length() == 1) { // just erase an array
526 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
527 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
530 } else { // reduce the array
531 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
533 int aCount = aRefs->Lower();
534 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
535 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
539 aNewArray->SetValue(aCount, aRefs->Value(a));
542 aRefs->SetInternalArray(aNewArray);
548 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
551 // check the feature: it must have no depended objects on it
552 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
553 for(; aResIter != theFeature->results().cend(); aResIter++) {
554 std::shared_ptr<Model_Data> aData =
555 std::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
556 if (aData && !aData->refsToMe().empty()) {
558 "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
564 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
566 TDF_Label aFeatureLabel = aData->label().Father();
567 if (myObjs.IsBound(aFeatureLabel))
568 myObjs.UnBind(aFeatureLabel);
570 return; // not found feature => do not remove
573 // erase all attributes under the label of feature
574 aFeatureLabel.ForgetAllAttributes();
575 // remove it from the references array
576 if (theFeature->isInHistory()) {
577 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
580 // event: feature is deleted
581 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
584 FeaturePtr Model_Document::feature(TDF_Label& theLabel) const
586 if (myObjs.IsBound(theLabel))
587 return myObjs.Find(theLabel);
588 return FeaturePtr(); // not found
591 ObjectPtr Model_Document::object(TDF_Label theLabel)
593 // try feature by label
594 FeaturePtr aFeature = feature(theLabel);
596 return feature(theLabel);
597 TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
598 aFeature = feature(aFeatureLabel);
600 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
601 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
602 for (; aRIter != aResults.cend(); aRIter++) {
603 std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
605 if (aResData->label().Father().IsEqual(theLabel))
609 return FeaturePtr(); // not found
612 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
614 return Model_Application::getApplication()->getDocument(theDocID);
617 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
619 std::set<std::string> aResult;
620 // comment must be in any feature: it is kind
622 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
623 for (; aLabIter.More(); aLabIter.Next()) {
624 TDF_Label aFLabel = aLabIter.Value()->Label();
625 FeaturePtr aFeature = feature(aFLabel);
626 if (aFeature.get()) { // if document is closed the feature may be not in myObjs map
627 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
628 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
629 for (; aRIter != aResults.cend(); aRIter++) {
630 if ((*aRIter)->groupName() != ModelAPI_ResultPart::group()) continue;
631 if ((*aRIter)->isInHistory()) {
632 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRIter);
633 if (aPart && (!theActivatedOnly || aPart->isActivated()))
634 aResult.insert(aPart->data()->name());
642 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
644 // just store sub-document identifier here to manage it later
645 return std::dynamic_pointer_cast<Model_Document>(
646 Model_Application::getApplication()->getDocument(theDocID));
649 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
650 const bool theHidden)
652 if (theGroupID == ModelAPI_Feature::group()) {
655 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
656 for (; aLabIter.More(); aLabIter.Next()) {
657 if (theIndex == anIndex) {
658 TDF_Label aFLabel = aLabIter.Value()->Label();
659 return feature(aFLabel);
664 Handle(TDataStd_ReferenceArray) aRefs;
665 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
667 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
669 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
670 return feature(aFeatureLabel);
673 // comment must be in any feature: it is kind
675 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
676 for (; aLabIter.More(); aLabIter.Next()) {
677 TDF_Label aFLabel = aLabIter.Value()->Label();
678 FeaturePtr aFeature = feature(aFLabel);
679 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
680 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
681 for (; aRIter != aResults.cend(); aRIter++) {
682 if ((*aRIter)->groupName() != theGroupID) continue;
683 bool isIn = theHidden && (*aRIter)->isInHistory();
684 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
685 isIn = !(*aRIter)->isConcealed();
688 if (anIndex == theIndex)
699 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
702 if (theGroupID == ModelAPI_Feature::group()) {
704 return myObjs.Size();
706 Handle(TDataStd_ReferenceArray) aRefs;
707 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
708 return aRefs->Length();
711 // comment must be in any feature: it is kind
712 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
713 for (; aLabIter.More(); aLabIter.Next()) {
714 TDF_Label aFLabel = aLabIter.Value()->Label();
715 FeaturePtr aFeature = feature(aFLabel);
716 if (!aFeature) // may be on close
718 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
719 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
720 for (; aRIter != aResults.cend(); aRIter++) {
721 if ((*aRIter)->groupName() != theGroupID) continue;
722 bool isIn = theHidden;
723 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
724 isIn = !(*aRIter)->isConcealed();
731 // group is not found
735 TDF_Label Model_Document::featuresLabel() const
737 return myDoc->Main().FindChild(TAG_OBJECTS);
740 void Model_Document::setUniqueName(FeaturePtr theFeature)
742 if (!theFeature->data()->name().empty())
743 return; // not needed, name is already defined
744 std::string aName; // result
745 // first count all objects of such kind to start with index = count + 1
747 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
748 for (; aFIter.More(); aFIter.Next()) {
749 if (aFIter.Value()->getKind() == theFeature->getKind())
752 // generate candidate name
753 std::stringstream aNameStream;
754 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
755 aName = aNameStream.str();
756 // check this is unique, if not, increase index by 1
757 for (aFIter.Initialize(myObjs); aFIter.More();) {
758 FeaturePtr aFeature = aFIter.Value();
759 bool isSameName = aFeature->data()->name() == aName;
760 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
761 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
762 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
763 for (; aRIter != aResults.cend(); aRIter++) {
764 isSameName = (*aRIter)->data()->name() == aName;
769 std::stringstream aNameStream;
770 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
771 aName = aNameStream.str();
772 // reinitialize iterator to make sure a new name is unique
773 aFIter.Initialize(myObjs);
777 theFeature->data()->setName(aName);
780 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
782 std::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
784 std::shared_ptr<Model_Data> aData(new Model_Data);
785 aData->setLabel(theLab.FindChild(theTag));
786 aData->setObject(theObj);
787 theObj->setDoc(aThis);
788 theObj->setData(aData);
789 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
791 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
792 aFeature->initAttributes();
796 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
798 std::shared_ptr<ModelAPI_Document> aThis =
799 Model_Application::getApplication()->getDocument(myID);
800 // after all updates, sends a message that groups of features were created or updated
801 std::static_pointer_cast<Model_Session>(Model_Session::get())
802 ->setCheckTransactions(false);
803 Events_Loop* aLoop = Events_Loop::loop();
804 aLoop->activateFlushes(false);
806 // update all objects by checking are they of labels or not
807 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
808 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
809 for (; aLabIter.More(); aLabIter.Next()) {
810 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
812 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
814 aFeature = ModelAPI_Session::get()->createFeature(
815 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
817 if (!aFeature) { // somethig is wrong, most probably, the opened document has invalid structure
818 Events_Error::send("Invalid type of object in the document");
819 aLabIter.Value()->Label().ForgetAllAttributes();
822 // this must be before "setData" to redo the sketch line correctly
823 myObjs.Bind(aFeatureLabel, aFeature);
824 aNewFeatures.insert(aFeature);
825 initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
827 // event: model is updated
828 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
829 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
830 } else { // nothing is changed, both iterators are incremented
831 aFeature = myObjs.Find(aFeatureLabel);
832 aKeptFeatures.insert(aFeature);
833 if (theMarkUpdated) {
834 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
835 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
839 // update results of thefeatures (after features created because they may be connected, like sketch and sub elements)
840 TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
841 for (; aLabIter2.More(); aLabIter2.Next()) {
842 TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
843 if (myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
844 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
845 updateResults(aFeature);
849 // check all features are checked: if not => it was removed
850 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
851 while (aFIter.More()) {
852 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
853 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
854 FeaturePtr aFeature = aFIter.Value();
855 // event: model is updated
856 //if (aFeature->isInHistory()) {
857 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
859 // results of this feature must be redisplayed (hided)
860 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
861 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
862 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
863 // redisplay also removed feature (used for sketch and AISObject)
864 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
866 // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
867 TDF_Label aLab = aFIter.Key();
874 if (theUpdateReferences) {
875 synchronizeBackRefs();
878 myExecuteFeatures = false;
879 aLoop->activateFlushes(true);
881 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
882 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
883 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
884 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
885 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
886 std::static_pointer_cast<Model_Session>(Model_Session::get())
887 ->setCheckTransactions(true);
888 myExecuteFeatures = true;
891 void Model_Document::synchronizeBackRefs()
893 std::shared_ptr<ModelAPI_Document> aThis =
894 Model_Application::getApplication()->getDocument(myID);
895 // keeps the concealed flags of result to catch the change and create created/deleted events
896 std::list<std::pair<ResultPtr, bool> > aConcealed;
897 // first cycle: erase all data about back-references
898 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
899 for(; aFeatures.More(); aFeatures.Next()) {
900 FeaturePtr aFeature = aFeatures.Value();
901 std::shared_ptr<Model_Data> aFData =
902 std::dynamic_pointer_cast<Model_Data>(aFeature->data());
904 aFData->eraseBackReferences();
906 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
907 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
908 for (; aRIter != aResults.cend(); aRIter++) {
909 std::shared_ptr<Model_Data> aResData =
910 std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
912 aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
913 aResData->eraseBackReferences();
918 // second cycle: set new back-references: only features may have reference, iterate only them
919 ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
920 for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
921 FeaturePtr aFeature = aFeatures.Value();
922 std::shared_ptr<Model_Data> aFData =
923 std::dynamic_pointer_cast<Model_Data>(aFeature->data());
925 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
926 aFData->referencesToObjects(aRefs);
927 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
928 for(; aRefsIter != aRefs.end(); aRefsIter++) {
929 std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
930 for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
932 std::shared_ptr<Model_Data> aRefData =
933 std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
934 aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
940 std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
941 for(; aCIter != aConcealed.end(); aCIter++) {
942 if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
943 if (aCIter->second) { // was concealed become not => creation event
944 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
945 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
946 } else { // was not concealed become concealed => delete event
947 ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
948 // redisplay for the viewer (it must be disappeared also)
949 static Events_ID EVENT_DISP =
950 Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
951 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
957 TDF_Label Model_Document::resultLabel(
958 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
960 const std::shared_ptr<Model_Data>& aData =
961 std::dynamic_pointer_cast<Model_Data>(theFeatureData);
962 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
965 void Model_Document::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
966 std::shared_ptr<ModelAPI_Result> theResult,
967 const int theResultIndex)
969 std::shared_ptr<ModelAPI_Document> aThis =
970 Model_Application::getApplication()->getDocument(myID);
971 theResult->setDoc(aThis);
972 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
973 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
974 theResult->data()->setName(theFeatureData->name());
978 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
979 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
981 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
982 TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
983 ObjectPtr anOldObject = object(aLab);
984 std::shared_ptr<ModelAPI_ResultConstruction> aResult;
986 aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
989 aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
990 storeResult(theFeatureData, aResult, theIndex);
995 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
996 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
998 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
999 TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1000 ObjectPtr anOldObject = object(aLab);
1001 std::shared_ptr<ModelAPI_ResultBody> aResult;
1003 aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1006 aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1007 storeResult(theFeatureData, aResult, theIndex);
1012 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1013 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1015 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1016 TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1017 ObjectPtr anOldObject = object(aLab);
1018 std::shared_ptr<ModelAPI_ResultPart> aResult;
1020 aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1023 aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1024 storeResult(theFeatureData, aResult, theIndex);
1029 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1030 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1032 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1033 TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1034 ObjectPtr anOldObject = object(aLab);
1035 std::shared_ptr<ModelAPI_ResultGroup> aResult;
1037 aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1040 aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1041 storeResult(theFeatureData, aResult, theIndex);
1046 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1047 const std::shared_ptr<ModelAPI_Result>& theResult)
1049 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1051 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1052 return feature(aFeatureLab);
1054 return FeaturePtr();
1057 void Model_Document::updateResults(FeaturePtr theFeature)
1059 // for not persistent is will be done by parametric updater automatically
1060 //if (!theFeature->isPersistentResult()) return;
1061 // check the existing results and remove them if there is nothing on the label
1062 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1063 while(aResIter != theFeature->results().cend()) {
1064 ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1066 if (!aBody->data()->isValid()) {
1067 // found a disappeared result => remove it
1068 theFeature->removeResult(aBody);
1069 // start iterate from beginning because iterator is corrupted by removing
1070 aResIter = theFeature->results().cbegin();
1076 // it may be on undo
1077 if (!theFeature->data() || !theFeature->data()->isValid())
1079 // check that results are presented on all labels
1080 int aResSize = theFeature->results().size();
1081 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1082 for(; aLabIter.More(); aLabIter.Next()) {
1083 // here must be GUID of the feature
1084 int aResIndex = aLabIter.Value().Tag() - 1;
1086 if (aResSize <= aResIndex) {
1087 TDF_Label anArgLab = aLabIter.Value();
1088 Handle(TDataStd_Comment) aGroup;
1089 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1090 if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1091 aNewBody = createBody(theFeature->data(), aResIndex);
1092 } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1093 aNewBody = createPart(theFeature->data(), aResIndex);
1094 } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1095 theFeature->execute(); // construction shapes are needed for sketch solver
1097 } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1098 aNewBody = createGroup(theFeature->data(), aResIndex);
1100 Events_Error::send(std::string("Unknown type of result is found in the document:") +
1101 TCollection_AsciiString(aGroup->Get()).ToCString());
1105 theFeature->setResult(aNewBody, aResIndex);
1111 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1113 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1116 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1118 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1121 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1123 myNamingNames[theName] = theLabel;
1126 TDF_Label Model_Document::findNamingName(std::string theName)
1128 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
1129 if (aFind == myNamingNames.end())
1130 return TDF_Label(); // not found
1131 return aFind->second;
1134 ResultPtr Model_Document::findByName(const std::string theName)
1136 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myObjs);
1137 for(; anObjIter.More(); anObjIter.Next()) {
1138 FeaturePtr& aFeature = anObjIter.ChangeValue();
1139 if (!aFeature) // may be on close
1141 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
1142 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
1143 for (; aRIter != aResults.cend(); aRIter++) {
1144 if (aRIter->get() && (*aRIter)->data() && (*aRIter)->data()->isValid() &&
1145 (*aRIter)->data()->name() == theName) {