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++;
256 myDoc->PerformDeltaCompaction();
260 void Model_Document::finishOperation()
262 // just to be sure that everybody knows that changes were performed
263 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
264 boost::static_pointer_cast<Model_Session>(Model_Session::get())
265 ->setCheckTransactions(false); // for nested transaction commit
266 synchronizeBackRefs();
267 Events_Loop* aLoop = Events_Loop::loop();
268 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
269 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
270 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
271 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
272 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
273 // this must be here just after everything is finished but before real transaction stop
274 // to avoid messages about modifications outside of the transaction
275 // and to rebuild everything after all updates and creates
276 if (Model_Session::get()->moduleDocument().get() == this) { // once for root document
277 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
278 static boost::shared_ptr<Events_Message> aFinishMsg
279 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
280 Events_Loop::loop()->send(aFinishMsg);
281 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
283 // to avoid "updated" message appearance by updater
284 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
286 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
287 boost::static_pointer_cast<Model_Session>(Model_Session::get())
288 ->setCheckTransactions(true); // for nested transaction commit
290 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
291 std::set<std::string>::iterator aSubIter = mySubs.begin();
292 for (; aSubIter != mySubs.end(); aSubIter++)
293 subDoc(*aSubIter)->finishOperation();
295 if (myNestedNum != -1) // this nested transaction is owervritten
297 if (!myDoc->HasOpenCommand()) {
298 if (myNestedNum != -1) {
303 // returns false if delta is empty and no transaction was made
304 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand(); // && (myNestedNum == -1);
305 myTransactionsAfterSave++;
309 void Model_Document::abortOperation()
311 if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
312 // first compact all nested
313 if (compactNested()) {
314 // for nested it is undo and clear redos
318 myTransactionsAfterSave--;
319 myIsEmptyTr.erase(myTransactionsAfterSave);
321 if (myNestedNum == 0) // abort only high-level
323 myDoc->AbortCommand();
325 synchronizeFeatures(true, false); // references were not changed since transaction start
326 // abort for all subs
327 std::set<std::string>::iterator aSubIter = mySubs.begin();
328 for (; aSubIter != mySubs.end(); aSubIter++)
329 subDoc(*aSubIter)->abortOperation();
332 bool Model_Document::isOperation()
334 // operation is opened for all documents: no need to check subs
335 return myDoc->HasOpenCommand() == Standard_True ;
338 bool Model_Document::isModified()
340 // is modified if at least one operation was commited and not undoed
341 return myTransactionsAfterSave > 0 || isOperation();
344 bool Model_Document::canUndo()
346 if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
347 && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
349 // check other subs contains operation that can be undoed
350 std::set<std::string>::iterator aSubIter = mySubs.begin();
351 for (; aSubIter != mySubs.end(); aSubIter++)
352 if (subDoc(*aSubIter)->canUndo())
357 void Model_Document::undo()
359 myTransactionsAfterSave--;
362 if (!myIsEmptyTr[myTransactionsAfterSave])
364 synchronizeFeatures(true, true);
366 std::set<std::string>::iterator aSubIter = mySubs.begin();
367 for (; aSubIter != mySubs.end(); aSubIter++)
368 subDoc(*aSubIter)->undo();
371 bool Model_Document::canRedo()
373 if (myDoc->GetAvailableRedos() > 0)
375 // check other subs contains operation that can be redoed
376 std::set<std::string>::iterator aSubIter = mySubs.begin();
377 for (; aSubIter != mySubs.end(); aSubIter++)
378 if (subDoc(*aSubIter)->canRedo())
383 void Model_Document::redo()
385 if (myNestedNum != -1)
387 if (!myIsEmptyTr[myTransactionsAfterSave])
389 myTransactionsAfterSave++;
390 synchronizeFeatures(true, true);
392 std::set<std::string>::iterator aSubIter = mySubs.begin();
393 for (; aSubIter != mySubs.end(); aSubIter++)
394 subDoc(*aSubIter)->redo();
397 /// Appenad to the array of references a new referenced label
398 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
400 Handle(TDataStd_ReferenceArray) aRefs;
401 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
402 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
403 aRefs->SetValue(0, theReferenced);
404 } else { // extend array by one more element
405 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
407 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
408 aNewArray->SetValue(a, aRefs->Value(a));
410 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
411 aRefs->SetInternalArray(aNewArray);
415 FeaturePtr Model_Document::addFeature(std::string theID)
417 TDF_Label anEmptyLab;
418 FeaturePtr anEmptyFeature;
419 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
422 boost::shared_ptr<Model_Document> aDocToAdd = boost::dynamic_pointer_cast<Model_Document>(
423 aFeature->documentToAdd());
425 TDF_Label aFeatureLab;
426 if (!aFeature->isAction()) { // do not add action to the data model
427 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
428 aFeatureLab = aFeaturesLab.NewChild();
429 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
430 // keep the feature ID to restore document later correctly
431 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
432 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
433 // store feature in the history of features array
434 if (aFeature->isInHistory()) {
435 AddToRefArray(aFeaturesLab, aFeatureLab);
438 if (!aFeature->isAction()) { // do not add action to the data model
439 // event: feature is added
440 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
441 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
442 } else { // feature must be executed
443 // no creation event => updater not working, problem with remove part
450 /// Appenad to the array of references a new referenced label.
451 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
452 /// \returns the index of removed element
453 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
456 int aResult = -1; // no returned
457 Handle(TDataStd_ReferenceArray) aRefs;
458 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
459 if (aRefs->Length() == 1) { // just erase an array
460 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
461 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
464 } else { // reduce the array
465 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
467 int aCount = aRefs->Lower();
468 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
469 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
473 aNewArray->SetValue(aCount, aRefs->Value(a));
476 aRefs->SetInternalArray(aNewArray);
482 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
485 // check the feature: it must have no depended objects on it
486 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
487 for(; aResIter != theFeature->results().cend(); aResIter++) {
488 boost::shared_ptr<Model_Data> aData =
489 boost::dynamic_pointer_cast<Model_Data>((*aResIter)->data());
490 if (aData && !aData->refsToMe().empty()) {
492 "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
498 boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
499 TDF_Label aFeatureLabel = aData->label().Father();
500 if (myObjs.IsBound(aFeatureLabel))
501 myObjs.UnBind(aFeatureLabel);
503 return; // not found feature => do not remove
506 // erase all attributes under the label of feature
507 aFeatureLabel.ForgetAllAttributes();
508 // remove it from the references array
509 if (theFeature->isInHistory()) {
510 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
512 // event: feature is deleted
513 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
516 FeaturePtr Model_Document::feature(TDF_Label& theLabel)
518 if (myObjs.IsBound(theLabel))
519 return myObjs.Find(theLabel);
520 return FeaturePtr(); // not found
523 ObjectPtr Model_Document::object(TDF_Label theLabel)
525 // try feature by label
526 FeaturePtr aFeature = feature(theLabel);
528 return feature(theLabel);
529 TDF_Label aFeatureLabel = theLabel.Father().Father(); // let's suppose it is result
530 aFeature = feature(aFeatureLabel);
532 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
533 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
534 for (; aRIter != aResults.cend(); aRIter++) {
535 boost::shared_ptr<Model_Data> aResData = boost::dynamic_pointer_cast<Model_Data>(
537 if (aResData->label().Father().IsEqual(theLabel))
541 return FeaturePtr(); // not found
544 boost::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
546 // just store sub-document identifier here to manage it later
547 if (mySubs.find(theDocID) == mySubs.end())
548 mySubs.insert(theDocID);
549 return Model_Application::getApplication()->getDocument(theDocID);
552 boost::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
554 // just store sub-document identifier here to manage it later
555 if (mySubs.find(theDocID) == mySubs.end())
556 mySubs.insert(theDocID);
557 return boost::dynamic_pointer_cast<Model_Document>(
558 Model_Application::getApplication()->getDocument(theDocID));
561 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex,
562 const bool theHidden)
564 if (theGroupID == ModelAPI_Feature::group()) {
567 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
568 for (; aLabIter.More(); aLabIter.Next()) {
569 if (theIndex == anIndex) {
570 TDF_Label aFLabel = aLabIter.Value()->Label();
571 return feature(aFLabel);
576 Handle(TDataStd_ReferenceArray) aRefs;
577 if (!featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
579 if (aRefs->Lower() > theIndex || aRefs->Upper() < theIndex)
581 TDF_Label aFeatureLabel = aRefs->Value(theIndex);
582 return feature(aFeatureLabel);
585 // comment must be in any feature: it is kind
587 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
588 for (; aLabIter.More(); aLabIter.Next()) {
589 TDF_Label aFLabel = aLabIter.Value()->Label();
590 FeaturePtr aFeature = feature(aFLabel);
591 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
592 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
593 for (; aRIter != aResults.cend(); aRIter++) {
594 if ((*aRIter)->groupName() != theGroupID) continue;
595 bool isIn = theHidden && (*aRIter)->isInHistory();
596 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
597 isIn = !(*aRIter)->isConcealed();
600 if (anIndex == theIndex)
611 int Model_Document::size(const std::string& theGroupID, const bool theHidden)
614 if (theGroupID == ModelAPI_Feature::group()) {
616 return myObjs.Size();
618 Handle(TDataStd_ReferenceArray) aRefs;
619 if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
620 return aRefs->Length();
623 // comment must be in any feature: it is kind
624 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
625 for (; aLabIter.More(); aLabIter.Next()) {
626 TDF_Label aFLabel = aLabIter.Value()->Label();
627 FeaturePtr aFeature = feature(aFLabel);
628 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
629 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
630 for (; aRIter != aResults.cend(); aRIter++) {
631 if ((*aRIter)->groupName() != theGroupID) continue;
632 bool isIn = theHidden;
633 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
634 isIn = !(*aRIter)->isConcealed();
641 // group is not found
645 TDF_Label Model_Document::featuresLabel()
647 return myDoc->Main().FindChild(TAG_OBJECTS);
650 void Model_Document::setUniqueName(FeaturePtr theFeature)
652 if (!theFeature->data()->name().empty())
653 return; // not needed, name is already defined
654 std::string aName; // result
655 // first count all objects of such kind to start with index = count + 1
657 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
658 for (; aFIter.More(); aFIter.Next()) {
659 if (aFIter.Value()->getKind() == theFeature->getKind())
662 // generate candidate name
663 std::stringstream aNameStream;
664 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
665 aName = aNameStream.str();
666 // check this is unique, if not, increase index by 1
667 for (aFIter.Initialize(myObjs); aFIter.More();) {
668 FeaturePtr aFeature = aFIter.Value();
669 bool isSameName = aFeature->data()->name() == aName;
670 if (!isSameName) { // check also results to avoid same results names (actual for Parts)
671 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
672 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
673 for (; aRIter != aResults.cend(); aRIter++) {
674 isSameName = (*aRIter)->data()->name() == aName;
679 std::stringstream aNameStream;
680 aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
681 aName = aNameStream.str();
682 // reinitialize iterator to make sure a new name is unique
683 aFIter.Initialize(myObjs);
687 theFeature->data()->setName(aName);
690 void Model_Document::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
692 boost::shared_ptr<ModelAPI_Document> aThis = Model_Application::getApplication()->getDocument(
694 boost::shared_ptr<Model_Data> aData(new Model_Data);
695 aData->setLabel(theLab.FindChild(theTag));
696 aData->setObject(theObj);
697 theObj->setDoc(aThis);
698 theObj->setData(aData);
699 FeaturePtr aFeature = boost::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
701 setUniqueName(aFeature); // must be before "initAttributes" because duplicate part uses name
702 aFeature->initAttributes();
706 void Model_Document::synchronizeFeatures(const bool theMarkUpdated, const bool theUpdateReferences)
708 boost::shared_ptr<ModelAPI_Document> aThis =
709 Model_Application::getApplication()->getDocument(myID);
710 // after all updates, sends a message that groups of features were created or updated
711 boost::static_pointer_cast<Model_Session>(Model_Session::get())
712 ->setCheckTransactions(false);
713 Events_Loop* aLoop = Events_Loop::loop();
714 aLoop->activateFlushes(false);
716 // update all objects by checking are they of labels or not
717 std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
718 TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
719 for (; aLabIter.More(); aLabIter.Next()) {
720 TDF_Label aFeatureLabel = aLabIter.Value()->Label();
722 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
724 aFeature = ModelAPI_Session::get()->createFeature(
725 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
727 if (!aFeature) { // somethig is wrong, most probably, the opened document has invalid structure
728 Events_Error::send("Invalid type of object in the document");
729 aLabIter.Value()->Label().ForgetAllAttributes();
732 // this must be before "setData" to redo the sketch line correctly
733 myObjs.Bind(aFeatureLabel, aFeature);
734 aNewFeatures.insert(aFeature);
735 initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
737 // event: model is updated
738 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
739 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
741 // update results of the appeared feature
742 updateResults(aFeature);
743 } else { // nothing is changed, both iterators are incremented
744 aFeature = myObjs.Find(aFeatureLabel);
745 aKeptFeatures.insert(aFeature);
746 if (theMarkUpdated) {
747 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
748 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
750 updateResults(aFeature);
753 // check all features are checked: if not => it was removed
754 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
755 while (aFIter.More()) {
756 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
757 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
758 FeaturePtr aFeature = aFIter.Value();
759 // event: model is updated
760 //if (aFeature->isInHistory()) {
761 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
763 // results of this feature must be redisplayed (hided)
764 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
765 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
766 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
767 // redisplay also removed feature (used for sketch and AISObject)
768 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
770 // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
771 TDF_Label aLab = aFIter.Key();
778 if (theUpdateReferences) {
779 synchronizeBackRefs();
782 myExecuteFeatures = false;
783 aLoop->activateFlushes(true);
785 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
786 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
787 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
788 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
789 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TOHIDE));
790 boost::static_pointer_cast<Model_Session>(Model_Session::get())
791 ->setCheckTransactions(true);
792 myExecuteFeatures = true;
795 void Model_Document::synchronizeBackRefs()
797 boost::shared_ptr<ModelAPI_Document> aThis =
798 Model_Application::getApplication()->getDocument(myID);
799 // keeps the concealed flags of result to catch the change and create created/deleted events
800 std::list<std::pair<ResultPtr, bool> > aConcealed;
801 // first cycle: erase all data about back-references
802 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myObjs);
803 for(; aFeatures.More(); aFeatures.Next()) {
804 FeaturePtr aFeature = aFeatures.Value();
805 boost::shared_ptr<Model_Data> aFData =
806 boost::dynamic_pointer_cast<Model_Data>(aFeature->data());
808 aFData->eraseBackReferences();
810 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
811 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
812 for (; aRIter != aResults.cend(); aRIter++) {
813 boost::shared_ptr<Model_Data> aResData =
814 boost::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
816 aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
817 aResData->eraseBackReferences();
822 // second cycle: set new back-references: only features may have reference, iterate only them
823 ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
824 for(aFeatures.Initialize(myObjs); aFeatures.More(); aFeatures.Next()) {
825 FeaturePtr aFeature = aFeatures.Value();
826 boost::shared_ptr<Model_Data> aFData =
827 boost::dynamic_pointer_cast<Model_Data>(aFeature->data());
829 std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
830 aFData->referencesToObjects(aRefs);
831 std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIter = aRefs.begin();
832 for(; aRefsIter != aRefs.end(); aRefsIter++) {
833 std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
834 for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
836 boost::shared_ptr<Model_Data> aRefData =
837 boost::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
838 aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
844 std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
845 for(; aCIter != aConcealed.end(); aCIter++) {
846 if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
847 if (aCIter->second) { // was concealed become not => creation event
848 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
849 ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
850 } else { // was not concealed become concealed => delete event
851 ModelAPI_EventCreator::get()->sendDeleted(aThis, aCIter->first->groupName());
857 TDF_Label Model_Document::resultLabel(
858 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
860 const boost::shared_ptr<Model_Data>& aData =
861 boost::dynamic_pointer_cast<Model_Data>(theFeatureData);
862 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
865 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
866 boost::shared_ptr<ModelAPI_Result> theResult,
867 const int theResultIndex)
869 boost::shared_ptr<ModelAPI_Document> aThis =
870 Model_Application::getApplication()->getDocument(myID);
871 theResult->setDoc(aThis);
872 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
873 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
874 theResult->data()->setName(theFeatureData->name());
878 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
879 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
881 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
882 TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
883 ObjectPtr anOldObject = object(aLab);
884 boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
886 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
889 aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
890 storeResult(theFeatureData, aResult, theIndex);
895 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
896 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
898 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
899 TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
900 ObjectPtr anOldObject = object(aLab);
901 boost::shared_ptr<ModelAPI_ResultBody> aResult;
903 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
906 aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
907 storeResult(theFeatureData, aResult, theIndex);
912 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
913 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
915 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
916 TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
917 ObjectPtr anOldObject = object(aLab);
918 boost::shared_ptr<ModelAPI_ResultPart> aResult;
920 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
923 aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
924 storeResult(theFeatureData, aResult, theIndex);
929 boost::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
930 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
932 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
933 TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
934 ObjectPtr anOldObject = object(aLab);
935 boost::shared_ptr<ModelAPI_ResultGroup> aResult;
937 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
940 aResult = boost::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
941 storeResult(theFeatureData, aResult, theIndex);
946 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
947 const boost::shared_ptr<ModelAPI_Result>& theResult)
949 boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
951 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
952 return feature(aFeatureLab);
957 void Model_Document::updateResults(FeaturePtr theFeature)
959 // for not persistent is will be done by parametric updater automatically
960 if (!theFeature->isPersistentResult()) return;
961 // check the existing results and remove them if there is nothing on the label
962 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
963 while(aResIter != theFeature->results().cend()) {
964 ResultBodyPtr aBody = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
966 if (!aBody->data()->isValid()) {
967 // found a disappeared result => remove it
968 theFeature->removeResult(aBody);
969 // start iterate from beginning because iterator is corrupted by removing
970 aResIter = theFeature->results().cbegin();
976 // check that results are presented on all labels
977 int aResSize = theFeature->results().size();
978 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
979 for(; aLabIter.More(); aLabIter.Next()) {
980 // here must be GUID of the feature
981 int aResIndex = aLabIter.Value().Tag() - 1;
983 if (aResSize <= aResIndex) {
984 TDF_Label anArgLab = aLabIter.Value();
985 Handle(TDataStd_Comment) aGroup;
986 if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
987 if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
988 aNewBody = createBody(theFeature->data(), aResIndex);
989 } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
990 aNewBody = createPart(theFeature->data(), aResIndex);
991 } else if (aGroup->Get() != ModelAPI_ResultConstruction::group().c_str() &&
992 aGroup->Get() != ModelAPI_ResultGroup::group().c_str()) {
993 Events_Error::send(std::string("Unknown type of result is found in the document:") +
994 TCollection_AsciiString(aGroup->Get()).ToCString());
998 theFeature->setResult(aNewBody, aResIndex);
1004 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1006 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1009 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1011 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);