1 // File: Model_Document.cxx
2 // Created: 28 Feb 2014
3 // Author: Mikhail PONIKAROV
5 #include <Model_Document.h>
6 #include <Model_Data.h>
7 #include <Model_Application.h>
8 #include <Model_Session.h>
9 #include <Model_Events.h>
10 #include <Model_ResultPart.h>
11 #include <Model_ResultConstruction.h>
12 #include <Model_ResultBody.h>
13 #include <Model_ResultGroup.h>
14 #include <ModelAPI_Validator.h>
15 #include <Events_Loop.h>
16 #include <Events_Error.h>
18 #include <TDataStd_Integer.hxx>
19 #include <TDataStd_Comment.hxx>
20 #include <TDF_ChildIDIterator.hxx>
21 #include <TDataStd_ReferenceArray.hxx>
22 #include <TDataStd_HLabelArray1.hxx>
23 #include <TDataStd_Name.hxx>
24 #include <TDF_Reference.hxx>
25 #include <TDF_ChildIDIterator.hxx>
26 #include <TDF_LabelMapHasher.hxx>
34 # define _separator_ '\\'
36 # define _separator_ '/'
39 static const int UNDO_LIMIT = 10; // number of possible undo operations
41 static const int TAG_GENERAL = 1; // general properties tag
42 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree (features, results)
43 static const int TAG_HISTORY = 3; // tag of the history sub-tree (python dump)
46 static const int TAG_FEATURE_ARGUMENTS = 1; ///< where the arguments are located
47 static const int TAG_FEATURE_RESULTS = 2; ///< where the results are located
49 Model_Document::Model_Document(const std::string theID, const std::string theKind)
50 : myID(theID), myKind(theKind),
51 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
53 myDoc->SetUndoLimit(UNDO_LIMIT);
54 myTransactionsAfterSave = 0;
56 myExecuteFeatures = true;
57 // to have something in the document and avoid empty doc open/save problem
58 // in transaction for nesting correct working
60 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
61 myDoc->CommitCommand();
64 /// Returns the file name of this document by the nameof directory and identifuer of a document
65 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
67 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
68 // remove end-separators
69 while(aPath.Length() && (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
70 aPath.Remove(aPath.Length());
72 aPath += theID.c_str();
73 aPath += ".cbf"; // standard binary file extension
77 bool Model_Document::load(const char* theFileName)
79 Handle(Model_Application) anApp = Model_Application::getApplication();
80 if (this == Model_Session::get()->moduleDocument().get()) {
81 anApp->setLoadPath(theFileName);
83 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
84 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
86 aStatus = anApp->Open(aPath, myDoc);
87 } catch (Standard_Failure) {
88 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
90 std::string("Exception in opening of document: ") + aFail->GetMessageString());
93 bool isError = aStatus != PCDM_RS_OK;
96 case PCDM_RS_UnknownDocument:
97 Events_Error::send(std::string("Can not open document: unknown format"));
99 case PCDM_RS_AlreadyRetrieved:
100 Events_Error::send(std::string("Can not open document: already opened"));
102 case PCDM_RS_AlreadyRetrievedAndModified:
104 std::string("Can not open document: already opened and modified"));
106 case PCDM_RS_NoDriver:
107 Events_Error::send(std::string("Can not open document: driver library is not found"));
109 case PCDM_RS_UnknownFileDriver:
110 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
112 case PCDM_RS_OpenError:
113 Events_Error::send(std::string("Can not open document: file open error"));
115 case PCDM_RS_NoVersion:
116 Events_Error::send(std::string("Can not open document: invalid version"));
118 case PCDM_RS_NoModel:
119 Events_Error::send(std::string("Can not open document: no data model"));
121 case PCDM_RS_NoDocument:
122 Events_Error::send(std::string("Can not open document: no document inside"));
124 case PCDM_RS_FormatFailure:
125 Events_Error::send(std::string("Can not open document: format failure"));
127 case PCDM_RS_TypeNotFoundInSchema:
128 Events_Error::send(std::string("Can not open document: invalid object"));
130 case PCDM_RS_UnrecognizedFileFormat:
131 Events_Error::send(std::string("Can not open document: unrecognized file format"));
133 case PCDM_RS_MakeFailure:
134 Events_Error::send(std::string("Can not open document: make failure"));
136 case PCDM_RS_PermissionDenied:
137 Events_Error::send(std::string("Can not open document: permission denied"));
139 case PCDM_RS_DriverFailure:
140 Events_Error::send(std::string("Can not open document: driver failure"));
143 Events_Error::send(std::string("Can not open document: unknown error"));
148 myDoc->SetUndoLimit(UNDO_LIMIT);
149 // to avoid the problem that feature is created in the current, not this, document
150 Model_Session::get()->setActiveDocument(anApp->getDocument(myID), false);
151 synchronizeFeatures(false, true);
152 Model_Session::get()->setActiveDocument(Model_Session::get()->moduleDocument(), false);
153 Model_Session::get()->setActiveDocument(anApp->getDocument(myID), true);
158 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
160 // create a directory in the root document if it is not yet exist
161 if (this == Model_Session::get()->moduleDocument().get()) {
163 CreateDirectory(theFileName, NULL);
165 mkdir(theFileName, 0x1ff);
168 // filename in the dir is id of document inside of the given directory
169 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
170 PCDM_StoreStatus aStatus;
172 aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
173 } catch (Standard_Failure) {
174 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
176 std::string("Exception in saving of document: ") + aFail->GetMessageString());
179 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
182 case PCDM_SS_DriverFailure:
183 Events_Error::send(std::string("Can not save document: save driver-library failure"));
185 case PCDM_SS_WriteFailure:
186 Events_Error::send(std::string("Can not save document: file writing failure"));
188 case PCDM_SS_Failure:
190 Events_Error::send(std::string("Can not save document"));
194 myTransactionsAfterSave = 0;
195 if (isDone) { // save also sub-documents if any
196 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
197 std::set<std::string>::iterator aSubIter = mySubs.begin();
198 for (; aSubIter != mySubs.end() && isDone; aSubIter++) {
199 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
205 void Model_Document::close()
207 boost::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
208 if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
209 aPM->setActiveDocument(aPM->moduleDocument());
212 std::set<std::string>::iterator aSubIter = mySubs.begin();
213 for (; aSubIter != mySubs.end(); aSubIter++)
214 subDoc(*aSubIter)->close();
216 // close this only if it is module document, otherwise it can be undoed
217 if (this == aPM->moduleDocument().get()) {
218 if (myDoc->CanClose() == CDM_CCS_OK)
220 Model_Application::getApplication()->deleteDocument(myID);
224 void Model_Document::startOperation()
226 if (myDoc->HasOpenCommand()) { // start of nested command
227 if (myNestedNum == -1) {
229 myDoc->InitDeltaCompaction();
231 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();
232 myTransactionsAfterSave++;
233 myDoc->OpenCommand();
234 } else { // start the simple command
237 // new command for all subs
238 std::set<std::string>::iterator aSubIter = mySubs.begin();
239 for (; aSubIter != mySubs.end(); aSubIter++)
240 subDoc(*aSubIter)->startOperation();
243 bool Model_Document::compactNested()
245 bool allWasEmpty = true;
246 while (myNestedNum != -1) {
247 myTransactionsAfterSave--;
248 if (!myIsEmptyTr[myTransactionsAfterSave]) {
251 myIsEmptyTr.erase(myTransactionsAfterSave);
254 myIsEmptyTr[myTransactionsAfterSave] = allWasEmpty;
255 myTransactionsAfterSave++;
257 // Issue 151: if everything is empty, it is a problem for OCCT to work with it,
258 // just commit the empty that returns nothing
259 myDoc->CommitCommand();
261 myDoc->PerformDeltaCompaction();
266 void Model_Document::finishOperation()
268 // just to be sure that everybody knows that changes were performed
269 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
270 boost::static_pointer_cast<Model_Session>(Model_Session::get())
271 ->setCheckTransactions(false); // for nested transaction commit
272 synchronizeBackRefs();
273 Events_Loop* aLoop = Events_Loop::loop();
274 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
275 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
276 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
277 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
278 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
279 // this must be here just after everything is finished but before real transaction stop
280 // to avoid messages about modifications outside of the transaction
281 // and to rebuild everything after all updates and creates
282 if (Model_Session::get()->moduleDocument().get() == this) { // once for root document
283 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
284 static boost::shared_ptr<Events_Message> aFinishMsg
285 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
286 Events_Loop::loop()->send(aFinishMsg);
287 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
289 // to avoid "updated" message appearance by updater
290 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
292 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
293 boost::static_pointer_cast<Model_Session>(Model_Session::get())
294 ->setCheckTransactions(true); // for nested transaction commit
296 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
297 std::set<std::string>::iterator aSubIter = mySubs.begin();
298 for (; aSubIter != mySubs.end(); aSubIter++)
299 subDoc(*aSubIter)->finishOperation();
301 if (myNestedNum != -1) // this nested transaction is owervritten
303 if (!myDoc->HasOpenCommand()) {
304 if (myNestedNum != -1) {
309 // returns false if delta is empty and no transaction was made
310 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand(); // && (myNestedNum == -1);
311 myTransactionsAfterSave++;
315 void Model_Document::abortOperation()
317 if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
318 // first compact all nested
322 myTransactionsAfterSave--;
323 myIsEmptyTr.erase(myTransactionsAfterSave);
325 if (myNestedNum == 0) // abort only high-level
327 myDoc->AbortCommand();
329 synchronizeFeatures(true, false); // references were not changed since transaction start
330 // abort for all subs
331 std::set<std::string>::iterator aSubIter = mySubs.begin();
332 for (; aSubIter != mySubs.end(); aSubIter++)
333 subDoc(*aSubIter)->abortOperation();
336 bool Model_Document::isOperation()
338 // operation is opened for all documents: no need to check subs
339 return myDoc->HasOpenCommand() == Standard_True ;
342 bool Model_Document::isModified()
344 // is modified if at least one operation was commited and not undoed
345 return myTransactionsAfterSave > 0 || isOperation();
348 bool Model_Document::canUndo()
350 if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
351 && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
353 // check other subs contains operation that can be undoed
354 std::set<std::string>::iterator aSubIter = mySubs.begin();
355 for (; aSubIter != mySubs.end(); aSubIter++)
356 if (subDoc(*aSubIter)->canUndo())
361 void Model_Document::undo()
363 myTransactionsAfterSave--;
366 if (!myIsEmptyTr[myTransactionsAfterSave])
368 synchronizeFeatures(true, true);
370 std::set<std::string>::iterator aSubIter = mySubs.begin();
371 for (; aSubIter != mySubs.end(); aSubIter++)
372 subDoc(*aSubIter)->undo();
375 bool Model_Document::canRedo()
377 if (myDoc->GetAvailableRedos() > 0)
379 // check other subs contains operation that can be redoed
380 std::set<std::string>::iterator aSubIter = mySubs.begin();
381 for (; aSubIter != mySubs.end(); aSubIter++)
382 if (subDoc(*aSubIter)->canRedo())
387 void Model_Document::redo()
389 if (myNestedNum != -1)
391 if (!myIsEmptyTr[myTransactionsAfterSave])
393 myTransactionsAfterSave++;
394 synchronizeFeatures(true, true);
396 std::set<std::string>::iterator aSubIter = mySubs.begin();
397 for (; aSubIter != mySubs.end(); aSubIter++)
398 subDoc(*aSubIter)->redo();
401 /// Appenad to the array of references a new referenced label
402 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
404 Handle(TDataStd_ReferenceArray) aRefs;
405 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
406 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
407 aRefs->SetValue(0, theReferenced);
408 } else { // extend array by one more element
409 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
411 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
412 aNewArray->SetValue(a, aRefs->Value(a));
414 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
415 aRefs->SetInternalArray(aNewArray);
419 FeaturePtr Model_Document::addFeature(std::string theID)
421 TDF_Label anEmptyLab;
422 FeaturePtr anEmptyFeature;
423 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
426 boost::shared_ptr<Model_Document> aDocToAdd = boost::dynamic_pointer_cast<Model_Document>(
427 aFeature->documentToAdd());
429 TDF_Label aFeatureLab;
430 if (!aFeature->isAction()) { // do not add action to the data model
431 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
432 aFeatureLab = aFeaturesLab.NewChild();
433 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
434 // keep the feature ID to restore document later correctly
435 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
436 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
437 // store feature in the history of features array
438 if (aFeature->isInHistory()) {
439 AddToRefArray(aFeaturesLab, aFeatureLab);
442 if (!aFeature->isAction()) { // do not add action to the data model
443 // event: feature is added
444 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
445 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
446 } else { // feature must be executed
447 // no creation event => updater not working, problem with remove part
454 /// Appenad to the array of references a new referenced label.
455 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
456 /// \returns the index of removed element
457 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
460 int aResult = -1; // no returned
461 Handle(TDataStd_ReferenceArray) aRefs;
462 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
463 if (aRefs->Length() == 1) { // just erase an array
464 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
465 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
468 } else { // reduce the array
469 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
471 int aCount = aRefs->Lower();
472 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
473 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
477 aNewArray->SetValue(aCount, aRefs->Value(a));
480 aRefs->SetInternalArray(aNewArray);
486 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
489 // check the feature: it must have no depended objects on it
490 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
491 for(; aResIter != theFeature->results().cend(); aResIter++) {
492 boost::shared_ptr<Model_Data> aData =
493 boost::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
494 if (aData && !aData->refsToMe().empty()) {
496 "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
502 boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
503 TDF_Label aFeatureLabel = aData->label().Father();
504 if (myObjs.IsBound(aFeatureLabel))
505 myObjs.UnBind(aFeatureLabel);
507 return; // not found feature => do not remove
510 // erase all attributes under the label of feature
511 aFeatureLabel.ForgetAllAttributes();
512 // remove it from the references array
513 if (theFeature->isInHistory()) {
514 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
516 // event: feature is deleted
517 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
520 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
522 if (myObjs.IsBound(theLabel))
523 return myObjs.Find(theLabel);
524 return FeaturePtr(); // not found
527 ObjectPtr Model_Document::object(TDF_Label theLabel)
529 // try feature by label
530 FeaturePtr aFeature = feature(theLabel);
532 return feature(theLabel);
533 TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
534 aFeature = feature(aFeatureLabel);
536 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
537 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
538 for (; aRIter != aResults.cend(); aRIter++) {
539 boost::shared_ptr<Model_Data> aResData = boost::dynamic_pointer_cast<Model_Data>(
541 if (aResData->label().Father().IsEqual(theLabel))
545 return FeaturePtr(); // not found
548 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
550 // just store sub-document identifier here to manage it later
551 if (mySubs.find(theDocID) == mySubs.end())
552 mySubs.insert(theDocID);
553 return Model_Application::getApplication()->getDocument(theDocID);
556 boost::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
558 // just store sub-document identifier here to manage it later
559 if (mySubs.find(theDocID) == mySubs.end())
560 mySubs.insert(theDocID);
561 return boost::dynamic_pointer_cast<Model_Document>(
562 Model_Application::getApplication()->getDocument(theDocID));
565 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
566 const bool theHidden)
568 if (theGroupID == ModelAPI_Feature::group()) {
571 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
572 for (; aLabIter.More(); aLabIter.Next()) {
573 if (theIndex == anIndex) {
574 TDF_Label aFLabel = aLabIter.Value()->Label();
575 return feature(aFLabel);
580 Handle(TDataStd_ReferenceArray) aRefs;
581 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
583 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
585 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
586 return feature(aFeatureLabel);
589 // comment must be in any feature: it is kind
591 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
592 for (; aLabIter.More(); aLabIter.Next()) {
593 TDF_Label aFLabel = aLabIter.Value()->Label();
594 FeaturePtr aFeature = feature(aFLabel);
595 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
596 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
597 for (; aRIter != aResults.cend(); aRIter++) {
598 if ((*aRIter)->groupName() != theGroupID) continue;
599 bool isIn = theHidden && (*aRIter)->isInHistory();
600 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
601 isIn = !(*aRIter)->isConcealed();
604 if (anIndex == theIndex)
615 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
618 if (theGroupID == ModelAPI_Feature::group()) {
620 return myObjs.Size();
622 Handle(TDataStd_ReferenceArray) aRefs;
623 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
624 return aRefs->Length();
627 // comment must be in any feature: it is kind
628 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
629 for (; aLabIter.More(); aLabIter.Next()) {
630 TDF_Label aFLabel = aLabIter.Value()->Label();
631 FeaturePtr aFeature = feature(aFLabel);
632 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
633 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
634 for (; aRIter != aResults.cend(); aRIter++) {
635 if ((*aRIter)->groupName() != theGroupID) continue;
636 bool isIn = theHidden;
637 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
638 isIn = !(*aRIter)->isConcealed();
645 // group is not found
649 TDF_Label Model_Document::featuresLabel()
651 return myDoc->Main().FindChild(TAG_OBJECTS);
654 void Model_Document::setUniqueName(FeaturePtr theFeature)
656 if (!theFeature->data()->name().empty())
657 return; // not needed, name is already defined
658 std::string aName; // result
659 // first count all objects of such kind to start with index = count + 1
661 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
662 for (; aFIter.More(); aFIter.Next()) {
663 if (aFIter.Value()->getKind() == theFeature->getKind())
666 // generate candidate name
667 std::stringstream aNameStream;
668 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
669 aName = aNameStream.str();
670 // check this is unique, if not, increase index by 1
671 for (aFIter.Initialize(myObjs); aFIter.More();) {
672 FeaturePtr aFeature = aFIter.Value();
673 bool isSameName = aFeature->data()->name() == aName;
674 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
675 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
676 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
677 for (; aRIter != aResults.cend(); aRIter++) {
678 isSameName = (*aRIter)->data()->name() == aName;
683 std::stringstream aNameStream;
684 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
685 aName = aNameStream.str();
686 // reinitialize iterator to make sure a new name is unique
687 aFIter.Initialize(myObjs);
691 theFeature->data()->setName(aName);
694 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
696 boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
698 boost::shared_ptr<Model_Data> aData(new Model_Data);
699 aData->setLabel(theLab.FindChild(theTag));
700 aData->setObject(theObj);
701 theObj->setDoc(aThis);
702 theObj->setData(aData);
703 FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
705 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
706 aFeature->initAttributes();
710 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
712 boost::shared_ptr<ModelAPI_Document> aThis =
713 Model_Application::getApplication()->getDocument(myID);
714 // after all updates, sends a message that groups of features were created or updated
715 boost::static_pointer_cast<Model_Session>(Model_Session::get())
716 ->setCheckTransactions(false);
717 Events_Loop* aLoop = Events_Loop::loop();
718 aLoop->activateFlushes(false);
720 // update all objects by checking are they of labels or not
721 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
722 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
723 for (; aLabIter.More(); aLabIter.Next()) {
724 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
726 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
728 aFeature = ModelAPI_Session::get()->createFeature(
729 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
731 if (!aFeature) { // somethig is wrong, most probably, the opened document has invalid structure
732 Events_Error::send("Invalid type of object in the document");
733 aLabIter.Value()->Label().ForgetAllAttributes();
736 // this must be before "setData" to redo the sketch line correctly
737 myObjs.Bind(aFeatureLabel, aFeature);
738 aNewFeatures.insert(aFeature);
739 initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
741 // event: model is updated
742 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
743 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
744 } else { // nothing is changed, both iterators are incremented
745 aFeature = myObjs.Find(aFeatureLabel);
746 aKeptFeatures.insert(aFeature);
747 if (theMarkUpdated) {
748 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
749 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
753 // update results of thefeatures (after features created because they may be connected, like sketch and sub elements)
754 TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
755 for (; aLabIter2.More(); aLabIter2.Next()) {
756 TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
757 if (myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
758 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
759 updateResults(aFeature);
763 // check all features are checked: if not => it was removed
764 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
765 while (aFIter.More()) {
766 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
767 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
768 FeaturePtr aFeature = aFIter.Value();
769 // event: model is updated
770 //if (aFeature->isInHistory()) {
771 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
773 // results of this feature must be redisplayed (hided)
774 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
775 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
776 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
777 // redisplay also removed feature (used for sketch and AISObject)
778 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
780 // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
781 TDF_Label aLab = aFIter.Key();
788 if (theUpdateReferences) {
789 synchronizeBackRefs();
792 myExecuteFeatures = false;
793 aLoop->activateFlushes(true);
795 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
796 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
797 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
798 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
799 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
800 boost::static_pointer_cast<Model_Session>(Model_Session::get())
801 ->setCheckTransactions(true);
802 myExecuteFeatures = true;
805 void Model_Document::synchronizeBackRefs()
807 boost::shared_ptr<ModelAPI_Document> aThis =
808 Model_Application::getApplication()->getDocument(myID);
809 // keeps the concealed flags of result to catch the change and create created/deleted events
810 std::list<std::pair<ResultPtr, bool> > aConcealed;
811 // first cycle: erase all data about back-references
812 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
813 for(; aFeatures.More(); aFeatures.Next()) {
814 FeaturePtr aFeature = aFeatures.Value();
815 boost::shared_ptr<Model_Data> aFData =
816 boost::dynamic_pointer_cast<Model_Data>(aFeature->data());
818 aFData->eraseBackReferences();
820 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
821 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
822 for (; aRIter != aResults.cend(); aRIter++) {
823 boost::shared_ptr<Model_Data> aResData =
824 boost::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
826 aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
827 aResData->eraseBackReferences();
832 // second cycle: set new back-references: only features may have reference, iterate only them
833 ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
834 for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
835 FeaturePtr aFeature = aFeatures.Value();
836 boost::shared_ptr<Model_Data> aFData =
837 boost::dynamic_pointer_cast<Model_Data>(aFeature->data());
839 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
840 aFData->referencesToObjects(aRefs);
841 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
842 for(; aRefsIter != aRefs.end(); aRefsIter++) {
843 std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
844 for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
846 boost::shared_ptr<Model_Data> aRefData =
847 boost::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
848 aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
854 std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
855 for(; aCIter != aConcealed.end(); aCIter++) {
856 if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
857 if (aCIter->second) { // was concealed become not => creation event
858 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
859 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
860 } else { // was not concealed become concealed => delete event
861 ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
867 TDF_Label Model_Document::resultLabel(
868 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
870 const boost::shared_ptr<Model_Data>& aData =
871 boost::dynamic_pointer_cast<Model_Data>(theFeatureData);
872 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
875 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
876 boost::shared_ptr<ModelAPI_Result> theResult,
877 const int theResultIndex)
879 boost::shared_ptr<ModelAPI_Document> aThis =
880 Model_Application::getApplication()->getDocument(myID);
881 theResult->setDoc(aThis);
882 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
883 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
884 theResult->data()->setName(theFeatureData->name());
888 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
889 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
891 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
892 TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
893 ObjectPtr anOldObject = object(aLab);
894 boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
896 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
899 aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
900 storeResult(theFeatureData, aResult, theIndex);
905 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
906 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
908 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
909 TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
910 ObjectPtr anOldObject = object(aLab);
911 boost::shared_ptr<ModelAPI_ResultBody> aResult;
913 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
916 aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
917 storeResult(theFeatureData, aResult, theIndex);
922 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
923 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
925 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
926 TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
927 ObjectPtr anOldObject = object(aLab);
928 boost::shared_ptr<ModelAPI_ResultPart> aResult;
930 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
933 aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
934 storeResult(theFeatureData, aResult, theIndex);
939 boost::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
940 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
942 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
943 TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
944 ObjectPtr anOldObject = object(aLab);
945 boost::shared_ptr<ModelAPI_ResultGroup> aResult;
947 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
950 aResult = boost::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
951 storeResult(theFeatureData, aResult, theIndex);
956 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
957 const boost::shared_ptr<ModelAPI_Result>& theResult)
959 boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
961 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
962 return feature(aFeatureLab);
967 void Model_Document::updateResults(FeaturePtr theFeature)
969 // for not persistent is will be done by parametric updater automatically
970 //if (!theFeature->isPersistentResult()) return;
971 // check the existing results and remove them if there is nothing on the label
972 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
973 while(aResIter != theFeature->results().cend()) {
974 ResultPtr aBody = boost::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
976 if (!aBody->data()->isValid()) {
977 // found a disappeared result => remove it
978 theFeature->removeResult(aBody);
979 // start iterate from beginning because iterator is corrupted by removing
980 aResIter = theFeature->results().cbegin();
986 // check that results are presented on all labels
987 int aResSize = theFeature->results().size();
988 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
989 for(; aLabIter.More(); aLabIter.Next()) {
990 // here must be GUID of the feature
991 int aResIndex = aLabIter.Value().Tag() - 1;
993 if (aResSize <= aResIndex) {
994 TDF_Label anArgLab = aLabIter.Value();
995 Handle(TDataStd_Comment) aGroup;
996 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
997 if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
998 aNewBody = createBody(theFeature->data(), aResIndex);
999 } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1000 aNewBody = createPart(theFeature->data(), aResIndex);
1001 } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1002 theFeature->execute(); // construction shapes are needed for sketch solver
1004 } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1005 aNewBody = createGroup(theFeature->data(), aResIndex);
1007 Events_Error::send(std::string("Unknown type of result is found in the document:") +
1008 TCollection_AsciiString(aGroup->Get()).ToCString());
1012 theFeature->setResult(aNewBody, aResIndex);
1018 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1020 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1023 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1025 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);