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
53 Model_Document::Model_Document(const std::string theID, const std::string theKind)
54 : myID(theID), myKind(theKind),
55 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
57 myDoc->SetUndoLimit(UNDO_LIMIT);
58 myTransactionsCounter = 0;
59 myTransactionSave = 0;
61 myExecuteFeatures = true;
62 // to have something in the document and avoid empty doc open/save problem
63 // in transaction for nesting correct working
65 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
66 myDoc->CommitCommand();
69 /// Returns the file name of this document by the nameof directory and identifuer of a document
70 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
72 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
73 // remove end-separators
74 while(aPath.Length() && (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
75 aPath.Remove(aPath.Length());
77 aPath += theID.c_str();
78 aPath += ".cbf"; // standard binary file extension
82 bool Model_Document::load(const char* theFileName)
84 Handle(Model_Application) anApp = Model_Application::getApplication();
85 if (this == Model_Session::get()->moduleDocument().get()) {
86 anApp->setLoadPath(theFileName);
88 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
89 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
91 aStatus = anApp->Open(aPath, myDoc);
92 } catch (Standard_Failure) {
93 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
95 std::string("Exception in opening of document: ") + aFail->GetMessageString());
98 bool isError = aStatus != PCDM_RS_OK;
101 case PCDM_RS_UnknownDocument:
102 Events_Error::send(std::string("Can not open document: unknown format"));
104 case PCDM_RS_AlreadyRetrieved:
105 Events_Error::send(std::string("Can not open document: already opened"));
107 case PCDM_RS_AlreadyRetrievedAndModified:
109 std::string("Can not open document: already opened and modified"));
111 case PCDM_RS_NoDriver:
112 Events_Error::send(std::string("Can not open document: driver library is not found"));
114 case PCDM_RS_UnknownFileDriver:
115 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
117 case PCDM_RS_OpenError:
118 Events_Error::send(std::string("Can not open document: file open error"));
120 case PCDM_RS_NoVersion:
121 Events_Error::send(std::string("Can not open document: invalid version"));
123 case PCDM_RS_NoModel:
124 Events_Error::send(std::string("Can not open document: no data model"));
126 case PCDM_RS_NoDocument:
127 Events_Error::send(std::string("Can not open document: no document inside"));
129 case PCDM_RS_FormatFailure:
130 Events_Error::send(std::string("Can not open document: format failure"));
132 case PCDM_RS_TypeNotFoundInSchema:
133 Events_Error::send(std::string("Can not open document: invalid object"));
135 case PCDM_RS_UnrecognizedFileFormat:
136 Events_Error::send(std::string("Can not open document: unrecognized file format"));
138 case PCDM_RS_MakeFailure:
139 Events_Error::send(std::string("Can not open document: make failure"));
141 case PCDM_RS_PermissionDenied:
142 Events_Error::send(std::string("Can not open document: permission denied"));
144 case PCDM_RS_DriverFailure:
145 Events_Error::send(std::string("Can not open document: driver failure"));
148 Events_Error::send(std::string("Can not open document: unknown error"));
153 myDoc->SetUndoLimit(UNDO_LIMIT);
154 // to avoid the problem that feature is created in the current, not this, document
155 Model_Session::get()->setActiveDocument(anApp->getDocument(myID), false);
156 synchronizeFeatures(false, true);
157 Model_Session::get()->setActiveDocument(Model_Session::get()->moduleDocument(), false);
158 Model_Session::get()->setActiveDocument(anApp->getDocument(myID), true);
163 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
165 // create a directory in the root document if it is not yet exist
166 Handle(Model_Application) anApp = Model_Application::getApplication();
167 if (this == Model_Session::get()->moduleDocument().get()) {
169 CreateDirectory(theFileName, NULL);
171 mkdir(theFileName, 0x1ff);
174 // filename in the dir is id of document inside of the given directory
175 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
176 PCDM_StoreStatus aStatus;
178 aStatus = anApp->SaveAs(myDoc, aPath);
179 } catch (Standard_Failure) {
180 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
182 std::string("Exception in saving of document: ") + aFail->GetMessageString());
185 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
188 case PCDM_SS_DriverFailure:
189 Events_Error::send(std::string("Can not save document: save driver-library failure"));
191 case PCDM_SS_WriteFailure:
192 Events_Error::send(std::string("Can not save document: file writing failure"));
194 case PCDM_SS_Failure:
196 Events_Error::send(std::string("Can not save document"));
200 myTransactionSave = myTransactionsCounter;
201 if (isDone) { // save also sub-documents if any
202 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
203 std::set<std::string>::iterator aSubIter = mySubs.begin();
204 for (; aSubIter != mySubs.end() && isDone; aSubIter++) {
205 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
207 if (isDone) { // also try to copy the not-activated sub-documents
208 // they are not in mySubs but as ResultParts
209 int aPartsNum = size(ModelAPI_ResultPart::group());
210 for(int aPart = 0; aPart < aPartsNum; aPart++) {
211 ResultPartPtr aPartRes = std::dynamic_pointer_cast<ModelAPI_ResultPart>
212 (object(ModelAPI_ResultPart::group(), aPart));
214 std::string aDocName = aPartRes->data()->name();
215 if (!aDocName.empty() && mySubs.find(aDocName) == mySubs.end()) {
217 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
218 OSD_Path aPath(aSubPath);
219 OSD_File aFile(aPath);
220 if (aFile.Exists()) {
221 TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
222 OSD_Path aDestination(aDestinationDir);
223 aFile.Copy(aDestination);
226 std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
236 void Model_Document::close(const bool theForever)
238 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
239 if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
240 aPM->setActiveDocument(aPM->moduleDocument());
243 std::set<std::string>::iterator aSubIter = mySubs.begin();
244 for (; aSubIter != mySubs.end(); aSubIter++)
245 subDoc(*aSubIter)->close(theForever);
248 // close for thid document needs no transaction in this document
249 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
251 // delete all features of this document
252 std::shared_ptr<ModelAPI_Document> aThis =
253 Model_Application::getApplication()->getDocument(myID);
254 Events_Loop* aLoop = Events_Loop::loop();
255 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myObjs);
256 for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
257 FeaturePtr aFeature = aFeaturesIter.Value();
258 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
259 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
260 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
261 aFeature->eraseResults();
265 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
266 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
268 // close all only if it is really asked, otherwise it can be undoed/redoed
270 if (myDoc->CanClose() == CDM_CCS_OK)
274 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
277 void Model_Document::startOperation()
279 if (myDoc->HasOpenCommand()) { // start of nested command
280 if (myNestedNum == -1) {
282 myDoc->InitDeltaCompaction();
284 myIsEmptyTr[myTransactionsCounter] = !myDoc->CommitCommand();
285 myTransactionsCounter++;
286 myDoc->OpenCommand();
287 } else { // start the simple command
290 // new command for all subs
291 std::set<std::string>::iterator aSubIter = mySubs.begin();
292 for (; aSubIter != mySubs.end(); aSubIter++)
293 subDoc(*aSubIter)->startOperation();
296 bool Model_Document::compactNested()
298 bool allWasEmpty = true;
299 while (myNestedNum != -1) {
300 myTransactionsCounter--;
301 if (!myIsEmptyTr[myTransactionsCounter]) {
304 myIsEmptyTr.erase(myTransactionsCounter);
307 myIsEmptyTr[myTransactionsCounter] = allWasEmpty;
308 myTransactionsCounter++;
310 // Issue 151: if everything is empty, it is a problem for OCCT to work with it,
311 // just commit the empty that returns nothing
312 myDoc->CommitCommand();
314 myDoc->PerformDeltaCompaction();
319 void Model_Document::finishOperation()
321 // just to be sure that everybody knows that changes were performed
322 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
323 std::static_pointer_cast<Model_Session>(Model_Session::get())
324 ->setCheckTransactions(false); // for nested transaction commit
325 synchronizeBackRefs();
326 Events_Loop* aLoop = Events_Loop::loop();
327 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
328 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
329 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
330 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
331 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
332 // this must be here just after everything is finished but before real transaction stop
333 // to avoid messages about modifications outside of the transaction
334 // and to rebuild everything after all updates and creates
335 if (Model_Session::get()->moduleDocument().get() == this) { // once for root document
336 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
337 static std::shared_ptr<Events_Message> aFinishMsg
338 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
339 Events_Loop::loop()->send(aFinishMsg);
340 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
342 // to avoid "updated" message appearance by updater
343 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
345 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
346 std::static_pointer_cast<Model_Session>(Model_Session::get())
347 ->setCheckTransactions(true); // for nested transaction commit
349 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
350 std::set<std::string>::iterator aSubIter = mySubs.begin();
351 for (; aSubIter != mySubs.end(); aSubIter++)
352 subDoc(*aSubIter)->finishOperation();
354 if (myNestedNum != -1) // this nested transaction is owervritten
356 if (!myDoc->HasOpenCommand()) {
357 if (myNestedNum != -1) {
362 // returns false if delta is empty and no transaction was made
363 myIsEmptyTr[myTransactionsCounter] = !myDoc->CommitCommand(); // && (myNestedNum == -1);
364 myTransactionsCounter++;
368 void Model_Document::abortOperation()
370 if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
371 // first compact all nested
372 if (compactNested()) {
373 myDoc->Undo(); // undo only compacted, if not: do not undo the empty transaction
376 myTransactionsCounter--;
377 myIsEmptyTr.erase(myTransactionsCounter);
379 if (myNestedNum == 0) // abort only high-level
381 myDoc->AbortCommand();
383 synchronizeFeatures(true, false); // references were not changed since transaction start
384 // abort for all subs
385 std::set<std::string>::iterator aSubIter = mySubs.begin();
386 for (; aSubIter != mySubs.end(); aSubIter++)
387 subDoc(*aSubIter)->abortOperation();
390 bool Model_Document::isOperation()
392 // operation is opened for all documents: no need to check subs
393 return myDoc->HasOpenCommand() == Standard_True ;
396 bool Model_Document::isModified()
398 // is modified if at least one operation was commited and not undoed
399 return myTransactionsCounter != myTransactionSave || isOperation();
402 bool Model_Document::canUndo()
404 if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
405 && myTransactionsCounter != 0 /* for omitting the first useless transaction */)
407 // check other subs contains operation that can be undoed
408 std::set<std::string>::iterator aSubIter = mySubs.begin();
409 for (; aSubIter != mySubs.end(); aSubIter++)
410 if (subDoc(*aSubIter)->canUndo())
415 void Model_Document::undo()
417 myTransactionsCounter--;
420 if (!myIsEmptyTr[myTransactionsCounter])
422 synchronizeFeatures(true, true);
424 std::set<std::string>::iterator aSubIter = mySubs.begin();
425 for (; aSubIter != mySubs.end(); aSubIter++)
426 subDoc(*aSubIter)->undo();
429 bool Model_Document::canRedo()
431 if (myDoc->GetAvailableRedos() > 0)
433 // check other subs contains operation that can be redoed
434 std::set<std::string>::iterator aSubIter = mySubs.begin();
435 for (; aSubIter != mySubs.end(); aSubIter++)
436 if (subDoc(*aSubIter)->canRedo())
441 void Model_Document::redo()
443 if (myNestedNum != -1)
445 if (!myIsEmptyTr[myTransactionsCounter])
447 myTransactionsCounter++;
448 synchronizeFeatures(true, true);
450 std::set<std::string>::iterator aSubIter = mySubs.begin();
451 for (; aSubIter != mySubs.end(); aSubIter++)
452 subDoc(*aSubIter)->redo();
455 /// Appenad to the array of references a new referenced label
456 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
458 Handle(TDataStd_ReferenceArray) aRefs;
459 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
460 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
461 aRefs->SetValue(0, theReferenced);
462 } else { // extend array by one more element
463 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
465 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
466 aNewArray->SetValue(a, aRefs->Value(a));
468 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
469 aRefs->SetInternalArray(aNewArray);
473 FeaturePtr Model_Document::addFeature(std::string theID)
475 TDF_Label anEmptyLab;
476 FeaturePtr anEmptyFeature;
477 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
480 std::shared_ptr<Model_Document> aDocToAdd = std::dynamic_pointer_cast<Model_Document>(
481 aFeature->documentToAdd());
483 TDF_Label aFeatureLab;
484 if (!aFeature->isAction()) { // do not add action to the data model
485 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
486 aFeatureLab = aFeaturesLab.NewChild();
487 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
488 // keep the feature ID to restore document later correctly
489 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
490 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
491 // store feature in the history of features array
492 if (aFeature->isInHistory()) {
493 AddToRefArray(aFeaturesLab, aFeatureLab);
496 if (!aFeature->isAction()) { // do not add action to the data model
497 // event: feature is added
498 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
499 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
500 } else { // feature must be executed
501 // no creation event => updater not working, problem with remove part
508 /// Appenad to the array of references a new referenced label.
509 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
510 /// \returns the index of removed element
511 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
514 int aResult = -1; // no returned
515 Handle(TDataStd_ReferenceArray) aRefs;
516 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
517 if (aRefs->Length() == 1) { // just erase an array
518 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
519 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
522 } else { // reduce the array
523 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
525 int aCount = aRefs->Lower();
526 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
527 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
531 aNewArray->SetValue(aCount, aRefs->Value(a));
534 aRefs->SetInternalArray(aNewArray);
540 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
543 // check the feature: it must have no depended objects on it
544 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
545 for(; aResIter != theFeature->results().cend(); aResIter++) {
546 std::shared_ptr<Model_Data> aData =
547 std::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
548 if (aData && !aData->refsToMe().empty()) {
550 "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
556 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
558 TDF_Label aFeatureLabel = aData->label().Father();
559 if (myObjs.IsBound(aFeatureLabel))
560 myObjs.UnBind(aFeatureLabel);
562 return; // not found feature => do not remove
565 // erase all attributes under the label of feature
566 aFeatureLabel.ForgetAllAttributes();
567 // remove it from the references array
568 if (theFeature->isInHistory()) {
569 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
572 // event: feature is deleted
573 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
576 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
578 if (myObjs.IsBound(theLabel))
579 return myObjs.Find(theLabel);
580 return FeaturePtr(); // not found
583 ObjectPtr Model_Document::object(TDF_Label theLabel)
585 // try feature by label
586 FeaturePtr aFeature = feature(theLabel);
588 return feature(theLabel);
589 TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
590 aFeature = feature(aFeatureLabel);
592 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
593 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
594 for (; aRIter != aResults.cend(); aRIter++) {
595 std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
597 if (aResData->label().Father().IsEqual(theLabel))
601 return FeaturePtr(); // not found
604 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
606 // just store sub-document identifier here to manage it later
607 if (mySubs.find(theDocID) == mySubs.end())
608 mySubs.insert(theDocID);
609 return Model_Application::getApplication()->getDocument(theDocID);
612 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
614 // just store sub-document identifier here to manage it later
615 if (mySubs.find(theDocID) == mySubs.end())
616 mySubs.insert(theDocID);
617 return std::dynamic_pointer_cast<Model_Document>(
618 Model_Application::getApplication()->getDocument(theDocID));
621 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
622 const bool theHidden)
624 if (theGroupID == ModelAPI_Feature::group()) {
627 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
628 for (; aLabIter.More(); aLabIter.Next()) {
629 if (theIndex == anIndex) {
630 TDF_Label aFLabel = aLabIter.Value()->Label();
631 return feature(aFLabel);
636 Handle(TDataStd_ReferenceArray) aRefs;
637 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
639 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
641 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
642 return feature(aFeatureLabel);
645 // comment must be in any feature: it is kind
647 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
648 for (; aLabIter.More(); aLabIter.Next()) {
649 TDF_Label aFLabel = aLabIter.Value()->Label();
650 FeaturePtr aFeature = feature(aFLabel);
651 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
652 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
653 for (; aRIter != aResults.cend(); aRIter++) {
654 if ((*aRIter)->groupName() != theGroupID) continue;
655 bool isIn = theHidden && (*aRIter)->isInHistory();
656 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
657 isIn = !(*aRIter)->isConcealed();
660 if (anIndex == theIndex)
671 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
674 if (theGroupID == ModelAPI_Feature::group()) {
676 return myObjs.Size();
678 Handle(TDataStd_ReferenceArray) aRefs;
679 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
680 return aRefs->Length();
683 // comment must be in any feature: it is kind
684 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
685 for (; aLabIter.More(); aLabIter.Next()) {
686 TDF_Label aFLabel = aLabIter.Value()->Label();
687 FeaturePtr aFeature = feature(aFLabel);
688 if (!aFeature) // may be on close
690 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
691 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
692 for (; aRIter != aResults.cend(); aRIter++) {
693 if ((*aRIter)->groupName() != theGroupID) continue;
694 bool isIn = theHidden;
695 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
696 isIn = !(*aRIter)->isConcealed();
703 // group is not found
707 TDF_Label Model_Document::featuresLabel()
709 return myDoc->Main().FindChild(TAG_OBJECTS);
712 void Model_Document::setUniqueName(FeaturePtr theFeature)
714 if (!theFeature->data()->name().empty())
715 return; // not needed, name is already defined
716 std::string aName; // result
717 // first count all objects of such kind to start with index = count + 1
719 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
720 for (; aFIter.More(); aFIter.Next()) {
721 if (aFIter.Value()->getKind() == theFeature->getKind())
724 // generate candidate name
725 std::stringstream aNameStream;
726 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
727 aName = aNameStream.str();
728 // check this is unique, if not, increase index by 1
729 for (aFIter.Initialize(myObjs); aFIter.More();) {
730 FeaturePtr aFeature = aFIter.Value();
731 bool isSameName = aFeature->data()->name() == aName;
732 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
733 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
734 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
735 for (; aRIter != aResults.cend(); aRIter++) {
736 isSameName = (*aRIter)->data()->name() == aName;
741 std::stringstream aNameStream;
742 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
743 aName = aNameStream.str();
744 // reinitialize iterator to make sure a new name is unique
745 aFIter.Initialize(myObjs);
749 theFeature->data()->setName(aName);
752 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
754 std::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
756 std::shared_ptr<Model_Data> aData(new Model_Data);
757 aData->setLabel(theLab.FindChild(theTag));
758 aData->setObject(theObj);
759 theObj->setDoc(aThis);
760 theObj->setData(aData);
761 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
763 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
764 aFeature->initAttributes();
768 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
770 std::shared_ptr<ModelAPI_Document> aThis =
771 Model_Application::getApplication()->getDocument(myID);
772 // after all updates, sends a message that groups of features were created or updated
773 std::static_pointer_cast<Model_Session>(Model_Session::get())
774 ->setCheckTransactions(false);
775 Events_Loop* aLoop = Events_Loop::loop();
776 aLoop->activateFlushes(false);
778 // update all objects by checking are they of labels or not
779 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
780 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
781 for (; aLabIter.More(); aLabIter.Next()) {
782 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
784 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
786 aFeature = ModelAPI_Session::get()->createFeature(
787 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
789 if (!aFeature) { // somethig is wrong, most probably, the opened document has invalid structure
790 Events_Error::send("Invalid type of object in the document");
791 aLabIter.Value()->Label().ForgetAllAttributes();
794 // this must be before "setData" to redo the sketch line correctly
795 myObjs.Bind(aFeatureLabel, aFeature);
796 aNewFeatures.insert(aFeature);
797 initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
799 // event: model is updated
800 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
801 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
802 } else { // nothing is changed, both iterators are incremented
803 aFeature = myObjs.Find(aFeatureLabel);
804 aKeptFeatures.insert(aFeature);
805 if (theMarkUpdated) {
806 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
807 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
811 // update results of thefeatures (after features created because they may be connected, like sketch and sub elements)
812 TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
813 for (; aLabIter2.More(); aLabIter2.Next()) {
814 TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
815 if (myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
816 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
817 updateResults(aFeature);
821 // check all features are checked: if not => it was removed
822 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
823 while (aFIter.More()) {
824 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
825 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
826 FeaturePtr aFeature = aFIter.Value();
827 // event: model is updated
828 //if (aFeature->isInHistory()) {
829 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
831 // results of this feature must be redisplayed (hided)
832 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
833 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
834 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
835 // redisplay also removed feature (used for sketch and AISObject)
836 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
838 // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
839 TDF_Label aLab = aFIter.Key();
846 if (theUpdateReferences) {
847 synchronizeBackRefs();
850 myExecuteFeatures = false;
851 aLoop->activateFlushes(true);
853 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
854 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
855 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
856 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
857 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
858 std::static_pointer_cast<Model_Session>(Model_Session::get())
859 ->setCheckTransactions(true);
860 myExecuteFeatures = true;
863 void Model_Document::synchronizeBackRefs()
865 std::shared_ptr<ModelAPI_Document> aThis =
866 Model_Application::getApplication()->getDocument(myID);
867 // keeps the concealed flags of result to catch the change and create created/deleted events
868 std::list<std::pair<ResultPtr, bool> > aConcealed;
869 // first cycle: erase all data about back-references
870 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
871 for(; aFeatures.More(); aFeatures.Next()) {
872 FeaturePtr aFeature = aFeatures.Value();
873 std::shared_ptr<Model_Data> aFData =
874 std::dynamic_pointer_cast<Model_Data>(aFeature->data());
876 aFData->eraseBackReferences();
878 const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
879 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
880 for (; aRIter != aResults.cend(); aRIter++) {
881 std::shared_ptr<Model_Data> aResData =
882 std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
884 aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
885 aResData->eraseBackReferences();
890 // second cycle: set new back-references: only features may have reference, iterate only them
891 ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
892 for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
893 FeaturePtr aFeature = aFeatures.Value();
894 std::shared_ptr<Model_Data> aFData =
895 std::dynamic_pointer_cast<Model_Data>(aFeature->data());
897 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
898 aFData->referencesToObjects(aRefs);
899 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
900 for(; aRefsIter != aRefs.end(); aRefsIter++) {
901 std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
902 for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
904 std::shared_ptr<Model_Data> aRefData =
905 std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
906 aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
912 std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
913 for(; aCIter != aConcealed.end(); aCIter++) {
914 if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
915 if (aCIter->second) { // was concealed become not => creation event
916 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
917 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
918 } else { // was not concealed become concealed => delete event
919 ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
920 // redisplay for the viewer (it must be disappeared also)
921 static Events_ID EVENT_DISP =
922 Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
923 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
929 TDF_Label Model_Document::resultLabel(
930 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
932 const std::shared_ptr<Model_Data>& aData =
933 std::dynamic_pointer_cast<Model_Data>(theFeatureData);
934 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
937 void Model_Document::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
938 std::shared_ptr<ModelAPI_Result> theResult,
939 const int theResultIndex)
941 std::shared_ptr<ModelAPI_Document> aThis =
942 Model_Application::getApplication()->getDocument(myID);
943 theResult->setDoc(aThis);
944 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
945 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
946 theResult->data()->setName(theFeatureData->name());
950 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
951 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
953 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
954 TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
955 ObjectPtr anOldObject = object(aLab);
956 std::shared_ptr<ModelAPI_ResultConstruction> aResult;
958 aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
961 aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
962 storeResult(theFeatureData, aResult, theIndex);
967 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
968 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
970 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
971 TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
972 ObjectPtr anOldObject = object(aLab);
973 std::shared_ptr<ModelAPI_ResultBody> aResult;
975 aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
978 aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
979 storeResult(theFeatureData, aResult, theIndex);
984 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
985 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
987 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
988 TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
989 ObjectPtr anOldObject = object(aLab);
990 std::shared_ptr<ModelAPI_ResultPart> aResult;
992 aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
995 aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
996 storeResult(theFeatureData, aResult, theIndex);
1001 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1002 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1004 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1005 TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1006 ObjectPtr anOldObject = object(aLab);
1007 std::shared_ptr<ModelAPI_ResultGroup> aResult;
1009 aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1012 aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1013 storeResult(theFeatureData, aResult, theIndex);
1018 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1019 const std::shared_ptr<ModelAPI_Result>& theResult)
1021 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1023 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1024 return feature(aFeatureLab);
1026 return FeaturePtr();
1029 void Model_Document::updateResults(FeaturePtr theFeature)
1031 // for not persistent is will be done by parametric updater automatically
1032 //if (!theFeature->isPersistentResult()) return;
1033 // check the existing results and remove them if there is nothing on the label
1034 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1035 while(aResIter != theFeature->results().cend()) {
1036 ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1038 if (!aBody->data()->isValid()) {
1039 // found a disappeared result => remove it
1040 theFeature->removeResult(aBody);
1041 // start iterate from beginning because iterator is corrupted by removing
1042 aResIter = theFeature->results().cbegin();
1048 // it may be on undo
1049 if (!theFeature->data() || !theFeature->data()->isValid())
1051 // check that results are presented on all labels
1052 int aResSize = theFeature->results().size();
1053 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1054 for(; aLabIter.More(); aLabIter.Next()) {
1055 // here must be GUID of the feature
1056 int aResIndex = aLabIter.Value().Tag() - 1;
1058 if (aResSize <= aResIndex) {
1059 TDF_Label anArgLab = aLabIter.Value();
1060 Handle(TDataStd_Comment) aGroup;
1061 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1062 if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1063 aNewBody = createBody(theFeature->data(), aResIndex);
1064 } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1065 aNewBody = createPart(theFeature->data(), aResIndex);
1066 } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1067 theFeature->execute(); // construction shapes are needed for sketch solver
1069 } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1070 aNewBody = createGroup(theFeature->data(), aResIndex);
1072 Events_Error::send(std::string("Unknown type of result is found in the document:") +
1073 TCollection_AsciiString(aGroup->Get()).ToCString());
1077 theFeature->setResult(aNewBody, aResIndex);
1083 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1085 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1088 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1090 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);