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 = 10; // number of possible undo operations
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 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
627 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
628 for (; aRIter != aResults.cend(); aRIter++) {
629 if ((*aRIter)->groupName() != ModelAPI_ResultPart::group()) continue;
630 if ((*aRIter)->isInHistory()) {
631 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRIter);
632 if (aPart && (!theActivatedOnly || aPart->isActivated()))
633 aResult.insert(aPart->data()->name());
640 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
642 // just store sub-document identifier here to manage it later
643 return std::dynamic_pointer_cast<Model_Document>(
644 Model_Application::getApplication()->getDocument(theDocID));
647 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
648 const bool theHidden)
650 if (theGroupID == ModelAPI_Feature::group()) {
653 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
654 for (; aLabIter.More(); aLabIter.Next()) {
655 if (theIndex == anIndex) {
656 TDF_Label aFLabel = aLabIter.Value()->Label();
657 return feature(aFLabel);
662 Handle(TDataStd_ReferenceArray) aRefs;
663 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
665 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
667 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
668 return feature(aFeatureLabel);
671 // comment must be in any feature: it is kind
673 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
674 for (; aLabIter.More(); aLabIter.Next()) {
675 TDF_Label aFLabel = aLabIter.Value()->Label();
676 FeaturePtr aFeature = feature(aFLabel);
677 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
678 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
679 for (; aRIter != aResults.cend(); aRIter++) {
680 if ((*aRIter)->groupName() != theGroupID) continue;
681 bool isIn = theHidden && (*aRIter)->isInHistory();
682 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
683 isIn = !(*aRIter)->isConcealed();
686 if (anIndex == theIndex)
697 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
700 if (theGroupID == ModelAPI_Feature::group()) {
702 return myObjs.Size();
704 Handle(TDataStd_ReferenceArray) aRefs;
705 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
706 return aRefs->Length();
709 // comment must be in any feature: it is kind
710 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
711 for (; aLabIter.More(); aLabIter.Next()) {
712 TDF_Label aFLabel = aLabIter.Value()->Label();
713 FeaturePtr aFeature = feature(aFLabel);
714 if (!aFeature) // may be on close
716 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
717 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
718 for (; aRIter != aResults.cend(); aRIter++) {
719 if ((*aRIter)->groupName() != theGroupID) continue;
720 bool isIn = theHidden;
721 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
722 isIn = !(*aRIter)->isConcealed();
729 // group is not found
733 TDF_Label Model_Document::featuresLabel() const
735 return myDoc->Main().FindChild(TAG_OBJECTS);
738 void Model_Document::setUniqueName(FeaturePtr theFeature)
740 if (!theFeature->data()->name().empty())
741 return; // not needed, name is already defined
742 std::string aName; // result
743 // first count all objects of such kind to start with index = count + 1
745 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
746 for (; aFIter.More(); aFIter.Next()) {
747 if (aFIter.Value()->getKind() == theFeature->getKind())
750 // generate candidate name
751 std::stringstream aNameStream;
752 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
753 aName = aNameStream.str();
754 // check this is unique, if not, increase index by 1
755 for (aFIter.Initialize(myObjs); aFIter.More();) {
756 FeaturePtr aFeature = aFIter.Value();
757 bool isSameName = aFeature->data()->name() == aName;
758 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
759 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
760 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
761 for (; aRIter != aResults.cend(); aRIter++) {
762 isSameName = (*aRIter)->data()->name() == aName;
767 std::stringstream aNameStream;
768 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
769 aName = aNameStream.str();
770 // reinitialize iterator to make sure a new name is unique
771 aFIter.Initialize(myObjs);
775 theFeature->data()->setName(aName);
778 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
780 std::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
782 std::shared_ptr<Model_Data> aData(new Model_Data);
783 aData->setLabel(theLab.FindChild(theTag));
784 aData->setObject(theObj);
785 theObj->setDoc(aThis);
786 theObj->setData(aData);
787 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
789 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
790 aFeature->initAttributes();
794 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
796 std::shared_ptr<ModelAPI_Document> aThis =
797 Model_Application::getApplication()->getDocument(myID);
798 // after all updates, sends a message that groups of features were created or updated
799 std::static_pointer_cast<Model_Session>(Model_Session::get())
800 ->setCheckTransactions(false);
801 Events_Loop* aLoop = Events_Loop::loop();
802 aLoop->activateFlushes(false);
804 // update all objects by checking are they of labels or not
805 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
806 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
807 for (; aLabIter.More(); aLabIter.Next()) {
808 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
810 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
812 aFeature = ModelAPI_Session::get()->createFeature(
813 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
815 if (!aFeature) { // somethig is wrong, most probably, the opened document has invalid structure
816 Events_Error::send("Invalid type of object in the document");
817 aLabIter.Value()->Label().ForgetAllAttributes();
820 // this must be before "setData" to redo the sketch line correctly
821 myObjs.Bind(aFeatureLabel, aFeature);
822 aNewFeatures.insert(aFeature);
823 initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
825 // event: model is updated
826 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
827 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
828 } else { // nothing is changed, both iterators are incremented
829 aFeature = myObjs.Find(aFeatureLabel);
830 aKeptFeatures.insert(aFeature);
831 if (theMarkUpdated) {
832 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
833 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
837 // update results of thefeatures (after features created because they may be connected, like sketch and sub elements)
838 TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
839 for (; aLabIter2.More(); aLabIter2.Next()) {
840 TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
841 if (myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
842 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
843 updateResults(aFeature);
847 // check all features are checked: if not => it was removed
848 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
849 while (aFIter.More()) {
850 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
851 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
852 FeaturePtr aFeature = aFIter.Value();
853 // event: model is updated
854 //if (aFeature->isInHistory()) {
855 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
857 // results of this feature must be redisplayed (hided)
858 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
859 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
860 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
861 // redisplay also removed feature (used for sketch and AISObject)
862 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
864 // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
865 TDF_Label aLab = aFIter.Key();
872 if (theUpdateReferences) {
873 synchronizeBackRefs();
876 myExecuteFeatures = false;
877 aLoop->activateFlushes(true);
879 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
880 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
881 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
882 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
883 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
884 std::static_pointer_cast<Model_Session>(Model_Session::get())
885 ->setCheckTransactions(true);
886 myExecuteFeatures = true;
889 void Model_Document::synchronizeBackRefs()
891 std::shared_ptr<ModelAPI_Document> aThis =
892 Model_Application::getApplication()->getDocument(myID);
893 // keeps the concealed flags of result to catch the change and create created/deleted events
894 std::list<std::pair<ResultPtr, bool> > aConcealed;
895 // first cycle: erase all data about back-references
896 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
897 for(; aFeatures.More(); aFeatures.Next()) {
898 FeaturePtr aFeature = aFeatures.Value();
899 std::shared_ptr<Model_Data> aFData =
900 std::dynamic_pointer_cast<Model_Data>(aFeature->data());
902 aFData->eraseBackReferences();
904 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
905 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
906 for (; aRIter != aResults.cend(); aRIter++) {
907 std::shared_ptr<Model_Data> aResData =
908 std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
910 aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
911 aResData->eraseBackReferences();
916 // second cycle: set new back-references: only features may have reference, iterate only them
917 ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
918 for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
919 FeaturePtr aFeature = aFeatures.Value();
920 std::shared_ptr<Model_Data> aFData =
921 std::dynamic_pointer_cast<Model_Data>(aFeature->data());
923 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
924 aFData->referencesToObjects(aRefs);
925 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
926 for(; aRefsIter != aRefs.end(); aRefsIter++) {
927 std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
928 for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
930 std::shared_ptr<Model_Data> aRefData =
931 std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
932 aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
938 std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
939 for(; aCIter != aConcealed.end(); aCIter++) {
940 if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
941 if (aCIter->second) { // was concealed become not => creation event
942 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
943 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
944 } else { // was not concealed become concealed => delete event
945 ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
946 // redisplay for the viewer (it must be disappeared also)
947 static Events_ID EVENT_DISP =
948 Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
949 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
955 TDF_Label Model_Document::resultLabel(
956 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
958 const std::shared_ptr<Model_Data>& aData =
959 std::dynamic_pointer_cast<Model_Data>(theFeatureData);
960 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
963 void Model_Document::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
964 std::shared_ptr<ModelAPI_Result> theResult,
965 const int theResultIndex)
967 std::shared_ptr<ModelAPI_Document> aThis =
968 Model_Application::getApplication()->getDocument(myID);
969 theResult->setDoc(aThis);
970 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
971 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
972 theResult->data()->setName(theFeatureData->name());
976 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
977 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
979 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
980 TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
981 ObjectPtr anOldObject = object(aLab);
982 std::shared_ptr<ModelAPI_ResultConstruction> aResult;
984 aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
987 aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
988 storeResult(theFeatureData, aResult, theIndex);
993 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
994 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
996 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
997 TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
998 ObjectPtr anOldObject = object(aLab);
999 std::shared_ptr<ModelAPI_ResultBody> aResult;
1001 aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1004 aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1005 storeResult(theFeatureData, aResult, theIndex);
1010 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1011 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1013 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1014 TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1015 ObjectPtr anOldObject = object(aLab);
1016 std::shared_ptr<ModelAPI_ResultPart> aResult;
1018 aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1021 aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1022 storeResult(theFeatureData, aResult, theIndex);
1027 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1028 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1030 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1031 TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1032 ObjectPtr anOldObject = object(aLab);
1033 std::shared_ptr<ModelAPI_ResultGroup> aResult;
1035 aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1038 aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1039 storeResult(theFeatureData, aResult, theIndex);
1044 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1045 const std::shared_ptr<ModelAPI_Result>& theResult)
1047 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1049 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1050 return feature(aFeatureLab);
1052 return FeaturePtr();
1055 void Model_Document::updateResults(FeaturePtr theFeature)
1057 // for not persistent is will be done by parametric updater automatically
1058 //if (!theFeature->isPersistentResult()) return;
1059 // check the existing results and remove them if there is nothing on the label
1060 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1061 while(aResIter != theFeature->results().cend()) {
1062 ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1064 if (!aBody->data()->isValid()) {
1065 // found a disappeared result => remove it
1066 theFeature->removeResult(aBody);
1067 // start iterate from beginning because iterator is corrupted by removing
1068 aResIter = theFeature->results().cbegin();
1074 // it may be on undo
1075 if (!theFeature->data() || !theFeature->data()->isValid())
1077 // check that results are presented on all labels
1078 int aResSize = theFeature->results().size();
1079 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1080 for(; aLabIter.More(); aLabIter.Next()) {
1081 // here must be GUID of the feature
1082 int aResIndex = aLabIter.Value().Tag() - 1;
1084 if (aResSize <= aResIndex) {
1085 TDF_Label anArgLab = aLabIter.Value();
1086 Handle(TDataStd_Comment) aGroup;
1087 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1088 if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1089 aNewBody = createBody(theFeature->data(), aResIndex);
1090 } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1091 aNewBody = createPart(theFeature->data(), aResIndex);
1092 } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1093 theFeature->execute(); // construction shapes are needed for sketch solver
1095 } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1096 aNewBody = createGroup(theFeature->data(), aResIndex);
1098 Events_Error::send(std::string("Unknown type of result is found in the document:") +
1099 TCollection_AsciiString(aGroup->Get()).ToCString());
1103 theFeature->setResult(aNewBody, aResIndex);
1109 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1111 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1114 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1116 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1119 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1121 myNamingNames[theName] = theLabel;
1124 TDF_Label Model_Document::findNamingName(std::string theName)
1126 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
1127 if (aFind == myNamingNames.end())
1128 return TDF_Label(); // not found
1129 return aFind->second;