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(true);
209 std::set<std::string>::iterator aSubIter = aSubs.begin();
210 for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
211 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
213 const std::set<std::string> allSubs = subDocuments(false);
214 if (isDone) { // also try to copy the not-activated sub-documents
215 for(aSubIter = allSubs.begin(); aSubIter != allSubs.end(); aSubIter++) {
216 if (aSubs.find(*aSubIter) == aSubs.end()) { // filter out the active subs
217 std::string aDocName = *aSubIter;
218 if (!aDocName.empty() && aSubs.find(aDocName) == aSubs.end()) {
220 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
221 OSD_Path aPath(aSubPath);
222 OSD_File aFile(aPath);
223 if (aFile.Exists()) {
224 TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
225 OSD_Path aDestination(aDestinationDir);
226 aFile.Copy(aDestination);
227 theResults.push_back(aDestinationDir.ToCString());
230 std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
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());
247 const std::set<std::string> aSubs = subDocuments(true);
248 std::set<std::string>::iterator aSubIter = aSubs.begin();
249 for (; aSubIter != aSubs.end(); aSubIter++)
250 subDoc(*aSubIter)->close(theForever);
252 // close for thid document needs no transaction in this document
253 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
255 // delete all features of this document
256 std::shared_ptr<ModelAPI_Document> aThis =
257 Model_Application::getApplication()->getDocument(myID);
258 Events_Loop* aLoop = Events_Loop::loop();
259 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myObjs);
260 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
261 FeaturePtr aFeature = aFeaturesIter.Value();
262 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
263 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
264 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
265 aFeature->eraseResults();
269 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
270 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
272 // close all only if it is really asked, otherwise it can be undoed/redoed
274 if (myDoc->CanClose() == CDM_CCS_OK)
278 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
281 void Model_Document::startOperation()
283 if (myDoc->HasOpenCommand()) { // start of nested command
284 if (myNestedNum == -1) {
286 myDoc->InitDeltaCompaction();
288 myIsEmptyTr[myTransactionsCounter] = !myDoc->CommitCommand();
289 myTransactionsCounter++;
290 myDoc->OpenCommand();
291 } else { // start the simple command
294 // new command for all subs
295 const std::set<std::string> aSubs = subDocuments(true);
296 std::set<std::string>::iterator aSubIter = aSubs.begin();
297 for (; aSubIter != aSubs.end(); aSubIter++)
298 subDoc(*aSubIter)->startOperation();
301 bool Model_Document::compactNested()
303 bool allWasEmpty = true;
304 while (myNestedNum != -1) {
305 myTransactionsCounter--;
306 if (!myIsEmptyTr[myTransactionsCounter]) {
309 myIsEmptyTr.erase(myTransactionsCounter);
312 myIsEmptyTr[myTransactionsCounter] = allWasEmpty;
313 myTransactionsCounter++;
315 // Issue 151: if everything is empty, it is a problem for OCCT to work with it,
316 // just commit the empty that returns nothing
317 myDoc->CommitCommand();
319 myDoc->PerformDeltaCompaction();
324 void Model_Document::finishOperation()
326 // just to be sure that everybody knows that changes were performed
327 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
328 std::static_pointer_cast<Model_Session>(Model_Session::get())
329 ->setCheckTransactions(false); // for nested transaction commit
330 synchronizeBackRefs();
331 Events_Loop* aLoop = Events_Loop::loop();
332 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
333 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
334 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
335 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
336 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
337 // this must be here just after everything is finished but before real transaction stop
338 // to avoid messages about modifications outside of the transaction
339 // and to rebuild everything after all updates and creates
340 if (Model_Session::get()->moduleDocument().get() == this) { // once for root document
341 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
342 static std::shared_ptr<Events_Message> aFinishMsg
343 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
344 Events_Loop::loop()->send(aFinishMsg);
345 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
347 // to avoid "updated" message appearance by updater
348 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
350 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
351 std::static_pointer_cast<Model_Session>(Model_Session::get())
352 ->setCheckTransactions(true); // for nested transaction commit
354 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
355 const std::set<std::string> aSubs = subDocuments(true);
356 std::set<std::string>::iterator aSubIter = aSubs.begin();
357 for (; aSubIter != aSubs.end(); aSubIter++)
358 subDoc(*aSubIter)->finishOperation();
360 if (myNestedNum != -1) // this nested transaction is owervritten
362 if (!myDoc->HasOpenCommand()) {
363 if (myNestedNum != -1) {
368 // returns false if delta is empty and no transaction was made
369 myIsEmptyTr[myTransactionsCounter] = !myDoc->CommitCommand(); // && (myNestedNum == -1);
370 myTransactionsCounter++;
374 void Model_Document::abortOperation()
376 if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
377 // first compact all nested
378 if (compactNested()) {
379 myDoc->Undo(); // undo only compacted, if not: do not undo the empty transaction
382 myTransactionsCounter--;
383 myIsEmptyTr.erase(myTransactionsCounter);
385 if (myNestedNum == 0) // abort only high-level
387 myDoc->AbortCommand();
389 synchronizeFeatures(true, false); // references were not changed since transaction start
390 // abort for all subs
391 const std::set<std::string> aSubs = subDocuments(true);
392 std::set<std::string>::iterator aSubIter = aSubs.begin();
393 for (; aSubIter != aSubs.end(); aSubIter++)
394 subDoc(*aSubIter)->abortOperation();
397 bool Model_Document::isOperation()
399 // operation is opened for all documents: no need to check subs
400 return myDoc->HasOpenCommand() == Standard_True ;
403 bool Model_Document::isModified()
405 // is modified if at least one operation was commited and not undoed
406 return myTransactionsCounter != myTransactionSave || isOperation();
409 bool Model_Document::canUndo()
411 if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
412 && myTransactionsCounter != 0 /* for omitting the first useless transaction */)
414 // check other subs contains operation that can be undoed
415 const std::set<std::string> aSubs = subDocuments(true);
416 std::set<std::string>::iterator aSubIter = aSubs.begin();
417 for (; aSubIter != aSubs.end(); aSubIter++)
418 if (subDoc(*aSubIter)->canUndo())
423 void Model_Document::undo()
425 myTransactionsCounter--;
428 if (!myIsEmptyTr[myTransactionsCounter])
430 synchronizeFeatures(true, true);
432 const std::set<std::string> aSubs = subDocuments(true);
433 std::set<std::string>::iterator aSubIter = aSubs.begin();
434 for (; aSubIter != aSubs.end(); aSubIter++)
435 subDoc(*aSubIter)->undo();
438 bool Model_Document::canRedo()
440 if (myDoc->GetAvailableRedos() > 0)
442 // check other subs contains operation that can be redoed
443 const std::set<std::string> aSubs = subDocuments(true);
444 std::set<std::string>::iterator aSubIter = aSubs.begin();
445 for (; aSubIter != aSubs.end(); aSubIter++)
446 if (subDoc(*aSubIter)->canRedo())
451 void Model_Document::redo()
453 if (myNestedNum != -1)
455 if (!myIsEmptyTr[myTransactionsCounter])
457 myTransactionsCounter++;
458 synchronizeFeatures(true, true);
460 const std::set<std::string> aSubs = subDocuments(true);
461 std::set<std::string>::iterator aSubIter = aSubs.begin();
462 for (; aSubIter != aSubs.end(); aSubIter++)
463 subDoc(*aSubIter)->redo();
466 /// Appenad to the array of references a new referenced label
467 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
469 Handle(TDataStd_ReferenceArray) aRefs;
470 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
471 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
472 aRefs->SetValue(0, theReferenced);
473 } else { // extend array by one more element
474 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
476 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
477 aNewArray->SetValue(a, aRefs->Value(a));
479 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
480 aRefs->SetInternalArray(aNewArray);
484 FeaturePtr Model_Document::addFeature(std::string theID)
486 TDF_Label anEmptyLab;
487 FeaturePtr anEmptyFeature;
488 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
491 std::shared_ptr<Model_Document> aDocToAdd = std::dynamic_pointer_cast<Model_Document>(
492 aFeature->documentToAdd());
494 TDF_Label aFeatureLab;
495 if (!aFeature->isAction()) { // do not add action to the data model
496 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
497 aFeatureLab = aFeaturesLab.NewChild();
498 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
499 // keep the feature ID to restore document later correctly
500 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
501 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
502 // store feature in the history of features array
503 if (aFeature->isInHistory()) {
504 AddToRefArray(aFeaturesLab, aFeatureLab);
507 if (!aFeature->isAction()) { // do not add action to the data model
508 // event: feature is added
509 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
510 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
511 } else { // feature must be executed
512 // no creation event => updater not working, problem with remove part
519 /// Appenad to the array of references a new referenced label.
520 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
521 /// \returns the index of removed element
522 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
525 int aResult = -1; // no returned
526 Handle(TDataStd_ReferenceArray) aRefs;
527 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
528 if (aRefs->Length() == 1) { // just erase an array
529 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
530 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
533 } else { // reduce the array
534 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
536 int aCount = aRefs->Lower();
537 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
538 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
542 aNewArray->SetValue(aCount, aRefs->Value(a));
545 aRefs->SetInternalArray(aNewArray);
551 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
554 // check the feature: it must have no depended objects on it
555 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
556 for(; aResIter != theFeature->results().cend(); aResIter++) {
557 std::shared_ptr<Model_Data> aData =
558 std::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
559 if (aData && !aData->refsToMe().empty()) {
561 "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
567 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
569 TDF_Label aFeatureLabel = aData->label().Father();
570 if (myObjs.IsBound(aFeatureLabel))
571 myObjs.UnBind(aFeatureLabel);
573 return; // not found feature => do not remove
576 // erase all attributes under the label of feature
577 aFeatureLabel.ForgetAllAttributes();
578 // remove it from the references array
579 if (theFeature->isInHistory()) {
580 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
583 // event: feature is deleted
584 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
587 FeaturePtr Model_Document::feature(TDF_Label& theLabel) const
589 if (myObjs.IsBound(theLabel))
590 return myObjs.Find(theLabel);
591 return FeaturePtr(); // not found
594 ObjectPtr Model_Document::object(TDF_Label theLabel)
596 // try feature by label
597 FeaturePtr aFeature = feature(theLabel);
599 return feature(theLabel);
600 TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
601 aFeature = feature(aFeatureLabel);
603 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
604 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
605 for (; aRIter != aResults.cend(); aRIter++) {
606 std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
608 if (aResData->label().Father().IsEqual(theLabel))
612 return FeaturePtr(); // not found
615 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
617 return Model_Application::getApplication()->getDocument(theDocID);
620 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
622 std::set<std::string> aResult;
623 // comment must be in any feature: it is kind
625 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
626 for (; aLabIter.More(); aLabIter.Next()) {
627 TDF_Label aFLabel = aLabIter.Value()->Label();
628 FeaturePtr aFeature = feature(aFLabel);
629 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
630 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
631 for (; aRIter != aResults.cend(); aRIter++) {
632 if ((*aRIter)->groupName() != ModelAPI_ResultPart::group()) continue;
633 if ((*aRIter)->isInHistory()) {
634 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aRIter);
635 if (aPart && (!theActivatedOnly || aPart->isActivated()))
636 aResult.insert(aPart->data()->name());
643 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
645 // just store sub-document identifier here to manage it later
646 return std::dynamic_pointer_cast<Model_Document>(
647 Model_Application::getApplication()->getDocument(theDocID));
650 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
651 const bool theHidden)
653 if (theGroupID == ModelAPI_Feature::group()) {
656 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
657 for (; aLabIter.More(); aLabIter.Next()) {
658 if (theIndex == anIndex) {
659 TDF_Label aFLabel = aLabIter.Value()->Label();
660 return feature(aFLabel);
665 Handle(TDataStd_ReferenceArray) aRefs;
666 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
668 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
670 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
671 return feature(aFeatureLabel);
674 // comment must be in any feature: it is kind
676 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
677 for (; aLabIter.More(); aLabIter.Next()) {
678 TDF_Label aFLabel = aLabIter.Value()->Label();
679 FeaturePtr aFeature = feature(aFLabel);
680 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
681 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
682 for (; aRIter != aResults.cend(); aRIter++) {
683 if ((*aRIter)->groupName() != theGroupID) continue;
684 bool isIn = theHidden && (*aRIter)->isInHistory();
685 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
686 isIn = !(*aRIter)->isConcealed();
689 if (anIndex == theIndex)
700 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
703 if (theGroupID == ModelAPI_Feature::group()) {
705 return myObjs.Size();
707 Handle(TDataStd_ReferenceArray) aRefs;
708 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
709 return aRefs->Length();
712 // comment must be in any feature: it is kind
713 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
714 for (; aLabIter.More(); aLabIter.Next()) {
715 TDF_Label aFLabel = aLabIter.Value()->Label();
716 FeaturePtr aFeature = feature(aFLabel);
717 if (!aFeature) // may be on close
719 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
720 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
721 for (; aRIter != aResults.cend(); aRIter++) {
722 if ((*aRIter)->groupName() != theGroupID) continue;
723 bool isIn = theHidden;
724 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
725 isIn = !(*aRIter)->isConcealed();
732 // group is not found
736 TDF_Label Model_Document::featuresLabel() const
738 return myDoc->Main().FindChild(TAG_OBJECTS);
741 void Model_Document::setUniqueName(FeaturePtr theFeature)
743 if (!theFeature->data()->name().empty())
744 return; // not needed, name is already defined
745 std::string aName; // result
746 // first count all objects of such kind to start with index = count + 1
748 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
749 for (; aFIter.More(); aFIter.Next()) {
750 if (aFIter.Value()->getKind() == theFeature->getKind())
753 // generate candidate name
754 std::stringstream aNameStream;
755 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
756 aName = aNameStream.str();
757 // check this is unique, if not, increase index by 1
758 for (aFIter.Initialize(myObjs); aFIter.More();) {
759 FeaturePtr aFeature = aFIter.Value();
760 bool isSameName = aFeature->data()->name() == aName;
761 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
762 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
763 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
764 for (; aRIter != aResults.cend(); aRIter++) {
765 isSameName = (*aRIter)->data()->name() == aName;
770 std::stringstream aNameStream;
771 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
772 aName = aNameStream.str();
773 // reinitialize iterator to make sure a new name is unique
774 aFIter.Initialize(myObjs);
778 theFeature->data()->setName(aName);
781 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
783 std::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
785 std::shared_ptr<Model_Data> aData(new Model_Data);
786 aData->setLabel(theLab.FindChild(theTag));
787 aData->setObject(theObj);
788 theObj->setDoc(aThis);
789 theObj->setData(aData);
790 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
792 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
793 aFeature->initAttributes();
797 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
799 std::shared_ptr<ModelAPI_Document> aThis =
800 Model_Application::getApplication()->getDocument(myID);
801 // after all updates, sends a message that groups of features were created or updated
802 std::static_pointer_cast<Model_Session>(Model_Session::get())
803 ->setCheckTransactions(false);
804 Events_Loop* aLoop = Events_Loop::loop();
805 aLoop->activateFlushes(false);
807 // update all objects by checking are they of labels or not
808 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
809 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
810 for (; aLabIter.More(); aLabIter.Next()) {
811 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
813 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
815 aFeature = ModelAPI_Session::get()->createFeature(
816 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
818 if (!aFeature) { // somethig is wrong, most probably, the opened document has invalid structure
819 Events_Error::send("Invalid type of object in the document");
820 aLabIter.Value()->Label().ForgetAllAttributes();
823 // this must be before "setData" to redo the sketch line correctly
824 myObjs.Bind(aFeatureLabel, aFeature);
825 aNewFeatures.insert(aFeature);
826 initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
828 // event: model is updated
829 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
830 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
831 } else { // nothing is changed, both iterators are incremented
832 aFeature = myObjs.Find(aFeatureLabel);
833 aKeptFeatures.insert(aFeature);
834 if (theMarkUpdated) {
835 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
836 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
840 // update results of thefeatures (after features created because they may be connected, like sketch and sub elements)
841 TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
842 for (; aLabIter2.More(); aLabIter2.Next()) {
843 TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
844 if (myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
845 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
846 updateResults(aFeature);
850 // check all features are checked: if not => it was removed
851 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
852 while (aFIter.More()) {
853 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
854 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
855 FeaturePtr aFeature = aFIter.Value();
856 // event: model is updated
857 //if (aFeature->isInHistory()) {
858 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
860 // results of this feature must be redisplayed (hided)
861 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
862 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
863 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
864 // redisplay also removed feature (used for sketch and AISObject)
865 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
867 // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
868 TDF_Label aLab = aFIter.Key();
875 if (theUpdateReferences) {
876 synchronizeBackRefs();
879 myExecuteFeatures = false;
880 aLoop->activateFlushes(true);
882 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
883 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
884 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
885 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
886 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
887 std::static_pointer_cast<Model_Session>(Model_Session::get())
888 ->setCheckTransactions(true);
889 myExecuteFeatures = true;
892 void Model_Document::synchronizeBackRefs()
894 std::shared_ptr<ModelAPI_Document> aThis =
895 Model_Application::getApplication()->getDocument(myID);
896 // keeps the concealed flags of result to catch the change and create created/deleted events
897 std::list<std::pair<ResultPtr, bool> > aConcealed;
898 // first cycle: erase all data about back-references
899 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
900 for(; aFeatures.More(); aFeatures.Next()) {
901 FeaturePtr aFeature = aFeatures.Value();
902 std::shared_ptr<Model_Data> aFData =
903 std::dynamic_pointer_cast<Model_Data>(aFeature->data());
905 aFData->eraseBackReferences();
907 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
908 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
909 for (; aRIter != aResults.cend(); aRIter++) {
910 std::shared_ptr<Model_Data> aResData =
911 std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
913 aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
914 aResData->eraseBackReferences();
919 // second cycle: set new back-references: only features may have reference, iterate only them
920 ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
921 for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
922 FeaturePtr aFeature = aFeatures.Value();
923 std::shared_ptr<Model_Data> aFData =
924 std::dynamic_pointer_cast<Model_Data>(aFeature->data());
926 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
927 aFData->referencesToObjects(aRefs);
928 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
929 for(; aRefsIter != aRefs.end(); aRefsIter++) {
930 std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
931 for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
933 std::shared_ptr<Model_Data> aRefData =
934 std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
935 aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
941 std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
942 for(; aCIter != aConcealed.end(); aCIter++) {
943 if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
944 if (aCIter->second) { // was concealed become not => creation event
945 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
946 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
947 } else { // was not concealed become concealed => delete event
948 ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
949 // redisplay for the viewer (it must be disappeared also)
950 static Events_ID EVENT_DISP =
951 Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
952 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
958 TDF_Label Model_Document::resultLabel(
959 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
961 const std::shared_ptr<Model_Data>& aData =
962 std::dynamic_pointer_cast<Model_Data>(theFeatureData);
963 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
966 void Model_Document::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
967 std::shared_ptr<ModelAPI_Result> theResult,
968 const int theResultIndex)
970 std::shared_ptr<ModelAPI_Document> aThis =
971 Model_Application::getApplication()->getDocument(myID);
972 theResult->setDoc(aThis);
973 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
974 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
975 theResult->data()->setName(theFeatureData->name());
979 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
980 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
982 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
983 TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
984 ObjectPtr anOldObject = object(aLab);
985 std::shared_ptr<ModelAPI_ResultConstruction> aResult;
987 aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
990 aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
991 storeResult(theFeatureData, aResult, theIndex);
996 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
997 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
999 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1000 TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1001 ObjectPtr anOldObject = object(aLab);
1002 std::shared_ptr<ModelAPI_ResultBody> aResult;
1004 aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1007 aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1008 storeResult(theFeatureData, aResult, theIndex);
1013 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1014 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1016 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1017 TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1018 ObjectPtr anOldObject = object(aLab);
1019 std::shared_ptr<ModelAPI_ResultPart> aResult;
1021 aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1024 aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1025 storeResult(theFeatureData, aResult, theIndex);
1030 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1031 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1033 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1034 TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1035 ObjectPtr anOldObject = object(aLab);
1036 std::shared_ptr<ModelAPI_ResultGroup> aResult;
1038 aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1041 aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1042 storeResult(theFeatureData, aResult, theIndex);
1047 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1048 const std::shared_ptr<ModelAPI_Result>& theResult)
1050 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1052 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1053 return feature(aFeatureLab);
1055 return FeaturePtr();
1058 void Model_Document::updateResults(FeaturePtr theFeature)
1060 // for not persistent is will be done by parametric updater automatically
1061 //if (!theFeature->isPersistentResult()) return;
1062 // check the existing results and remove them if there is nothing on the label
1063 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1064 while(aResIter != theFeature->results().cend()) {
1065 ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1067 if (!aBody->data()->isValid()) {
1068 // found a disappeared result => remove it
1069 theFeature->removeResult(aBody);
1070 // start iterate from beginning because iterator is corrupted by removing
1071 aResIter = theFeature->results().cbegin();
1077 // it may be on undo
1078 if (!theFeature->data() || !theFeature->data()->isValid())
1080 // check that results are presented on all labels
1081 int aResSize = theFeature->results().size();
1082 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1083 for(; aLabIter.More(); aLabIter.Next()) {
1084 // here must be GUID of the feature
1085 int aResIndex = aLabIter.Value().Tag() - 1;
1087 if (aResSize <= aResIndex) {
1088 TDF_Label anArgLab = aLabIter.Value();
1089 Handle(TDataStd_Comment) aGroup;
1090 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1091 if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1092 aNewBody = createBody(theFeature->data(), aResIndex);
1093 } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1094 aNewBody = createPart(theFeature->data(), aResIndex);
1095 } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1096 theFeature->execute(); // construction shapes are needed for sketch solver
1098 } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1099 aNewBody = createGroup(theFeature->data(), aResIndex);
1101 Events_Error::send(std::string("Unknown type of result is found in the document:") +
1102 TCollection_AsciiString(aGroup->Get()).ToCString());
1106 theFeature->setResult(aNewBody, aResIndex);
1112 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1114 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1117 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1119 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1122 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1124 myNamingNames[theName] = theLabel;
1127 TDF_Label Model_Document::findNamingName(std::string theName)
1129 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
1130 if (aFind == myNamingNames.end())
1131 return TDF_Label(); // not found
1132 return aFind->second;