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 <Events_Loop.h>
14 #include <Events_Error.h>
16 #include <TDataStd_Integer.hxx>
17 #include <TDataStd_Comment.hxx>
18 #include <TDataStd_UAttribute.hxx>
19 #include <TDF_ChildIDIterator.hxx>
20 #include <TDataStd_ReferenceArray.hxx>
21 #include <TDataStd_HLabelArray1.hxx>
22 #include <TDataStd_Name.hxx>
23 #include <TDF_Reference.hxx>
24 #include <TDF_ChildIDIterator.hxx>
25 #include <TDF_LabelMapHasher.hxx>
33 # define _separator_ '\\'
35 # define _separator_ '/'
38 static const int UNDO_LIMIT = 10; // number of possible undo operations
40 static const int TAG_GENERAL = 1; // general properties tag
41 static const int TAG_OBJECTS = 2; // tag of the objects sub-tree (features, results)
42 static const int TAG_HISTORY = 3; // tag of the history sub-tree (python dump)
45 static const int TAG_FEATURE_ARGUMENTS = 1; ///< where the arguments are located
46 static const int TAG_FEATURE_RESULTS = 2; ///< where the results are located
48 Model_Document::Model_Document(const std::string theID, const std::string theKind)
49 : myID(theID), myKind(theKind),
50 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
52 myDoc->SetUndoLimit(UNDO_LIMIT);
53 myTransactionsAfterSave = 0;
55 myExecuteFeatures = true;
56 //myDoc->SetNestedTransactionMode();
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));
151 synchronizeFeatures();
156 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
158 // create a directory in the root document if it is not yet exist
159 if (this == Model_Session::get()->moduleDocument().get()) {
161 CreateDirectory(theFileName, NULL);
163 mkdir(theFileName, 0x1ff);
166 // filename in the dir is id of document inside of the given directory
167 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
168 PCDM_StoreStatus aStatus;
170 aStatus = Model_Application::getApplication()->SaveAs(myDoc, aPath);
171 } catch (Standard_Failure) {
172 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
174 std::string("Exception in saving of document: ") + aFail->GetMessageString());
177 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
180 case PCDM_SS_DriverFailure:
181 Events_Error::send(std::string("Can not save document: save driver-library failure"));
183 case PCDM_SS_WriteFailure:
184 Events_Error::send(std::string("Can not save document: file writing failure"));
186 case PCDM_SS_Failure:
188 Events_Error::send(std::string("Can not save document"));
192 myTransactionsAfterSave = 0;
193 if (isDone) { // save also sub-documents if any
194 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
195 std::set<std::string>::iterator aSubIter = mySubs.begin();
196 for (; aSubIter != mySubs.end() && isDone; aSubIter++) {
197 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
203 void Model_Document::close()
205 boost::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
206 if (this != aPM->moduleDocument().get() && this == aPM->activeDocument().get()) {
207 aPM->setActiveDocument(aPM->moduleDocument());
210 std::set<std::string>::iterator aSubIter = mySubs.begin();
211 for (; aSubIter != mySubs.end(); aSubIter++)
212 subDoc(*aSubIter)->close();
215 /* do not close because it can be undoed
216 if (myDoc->CanClose() == CDM_CCS_OK)
218 Model_Application::getApplication()->deleteDocument(myID);
222 void Model_Document::startOperation()
224 if (myDoc->HasOpenCommand()) { // start of nested command
225 if (myNestedNum == -1) {
227 myDoc->InitDeltaCompaction();
229 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand();
230 myTransactionsAfterSave++;
231 myDoc->OpenCommand();
232 } else { // start the simple command
235 // new command for all subs
236 std::set<std::string>::iterator aSubIter = mySubs.begin();
237 for (; aSubIter != mySubs.end(); aSubIter++)
238 subDoc(*aSubIter)->startOperation();
241 bool Model_Document::compactNested()
243 bool allWasEmpty = true;
244 while (myNestedNum != -1) {
245 myTransactionsAfterSave--;
246 if (!myIsEmptyTr[myTransactionsAfterSave]) {
249 myIsEmptyTr.erase(myTransactionsAfterSave);
252 myIsEmptyTr[myTransactionsAfterSave] = allWasEmpty;
253 myTransactionsAfterSave++;
254 myDoc->PerformDeltaCompaction();
258 void Model_Document::finishOperation()
260 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
261 std::set<std::string>::iterator aSubIter = mySubs.begin();
262 for (; aSubIter != mySubs.end(); aSubIter++)
263 subDoc(*aSubIter)->finishOperation();
265 // just to be sure that everybody knows that changes were performed
266 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
267 boost::static_pointer_cast<Model_Session>(Model_Session::get())
268 ->setCheckTransactions(false); // for nested transaction commit
269 Events_Loop* aLoop = Events_Loop::loop();
270 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
271 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
272 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
273 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
274 if (!myDoc->HasOpenCommand() && myNestedNum != -1)
275 boost::static_pointer_cast<Model_Session>(Model_Session::get())
276 ->setCheckTransactions(true); // for nested transaction commit
278 if (myNestedNum != -1) // this nested transaction is owervritten
280 if (!myDoc->HasOpenCommand()) {
281 if (myNestedNum != -1) {
286 // returns false if delta is empty and no transaction was made
287 myIsEmptyTr[myTransactionsAfterSave] = !myDoc->CommitCommand(); // && (myNestedNum == -1);
288 myTransactionsAfterSave++;
293 void Model_Document::abortOperation()
295 if (myNestedNum > 0 && !myDoc->HasOpenCommand()) { // abort all what was done in nested
296 // first compact all nested
297 if (compactNested()) {
298 // for nested it is undo and clear redos
302 myTransactionsAfterSave--;
303 myIsEmptyTr.erase(myTransactionsAfterSave);
305 if (myNestedNum == 0) // abort only high-level
307 myDoc->AbortCommand();
309 synchronizeFeatures(true);
310 // abort for all subs
311 std::set<std::string>::iterator aSubIter = mySubs.begin();
312 for (; aSubIter != mySubs.end(); aSubIter++)
313 subDoc(*aSubIter)->abortOperation();
316 bool Model_Document::isOperation()
318 // operation is opened for all documents: no need to check subs
319 return myDoc->HasOpenCommand() == Standard_True ;
322 bool Model_Document::isModified()
324 // is modified if at least one operation was commited and not undoed
325 return myTransactionsAfterSave > 0 || isOperation();
328 bool Model_Document::canUndo()
330 if (myDoc->GetAvailableUndos() > 0 && myNestedNum != 0
331 && myTransactionsAfterSave != 0 /* for omitting the first useless transaction */)
333 // check other subs contains operation that can be undoed
334 std::set<std::string>::iterator aSubIter = mySubs.begin();
335 for (; aSubIter != mySubs.end(); aSubIter++)
336 if (subDoc(*aSubIter)->canUndo())
341 void Model_Document::undo()
343 myTransactionsAfterSave--;
346 if (!myIsEmptyTr[myTransactionsAfterSave])
348 synchronizeFeatures(true);
350 std::set<std::string>::iterator aSubIter = mySubs.begin();
351 for (; aSubIter != mySubs.end(); aSubIter++)
352 subDoc(*aSubIter)->undo();
355 bool Model_Document::canRedo()
357 if (myDoc->GetAvailableRedos() > 0)
359 // check other subs contains operation that can be redoed
360 std::set<std::string>::iterator aSubIter = mySubs.begin();
361 for (; aSubIter != mySubs.end(); aSubIter++)
362 if (subDoc(*aSubIter)->canRedo())
367 void Model_Document::redo()
369 if (myNestedNum != -1)
371 if (!myIsEmptyTr[myTransactionsAfterSave])
373 myTransactionsAfterSave++;
374 synchronizeFeatures(true);
376 std::set<std::string>::iterator aSubIter = mySubs.begin();
377 for (; aSubIter != mySubs.end(); aSubIter++)
378 subDoc(*aSubIter)->redo();
381 /// Appenad to the array of references a new referenced label
382 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced)
384 Handle(TDataStd_ReferenceArray) aRefs;
385 if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
386 aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
387 aRefs->SetValue(0, theReferenced);
388 } else { // extend array by one more element
389 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
391 for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
392 aNewArray->SetValue(a, aRefs->Value(a));
394 aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
395 aRefs->SetInternalArray(aNewArray);
399 FeaturePtr Model_Document::addFeature(std::string theID)
401 TDF_Label anEmptyLab;
402 FeaturePtr anEmptyFeature;
403 FeaturePtr aFeature = ModelAPI_Session::get()->createFeature(theID);
406 boost::shared_ptr<Model_Document> aDocToAdd = boost::dynamic_pointer_cast<Model_Document>(
407 aFeature->documentToAdd());
409 TDF_Label aFeatureLab;
410 if (!aFeature->isAction()) { // do not add action to the data model
411 TDF_Label aFeaturesLab = aDocToAdd->featuresLabel();
412 aFeatureLab = aFeaturesLab.NewChild();
413 aDocToAdd->initData(aFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
414 // keep the feature ID to restore document later correctly
415 TDataStd_Comment::Set(aFeatureLab, aFeature->getKind().c_str());
416 aDocToAdd->myObjs.Bind(aFeatureLab, aFeature);
417 // store feature in the history of features array
418 if (aFeature->isInHistory()) {
419 AddToRefArray(aFeaturesLab, aFeatureLab);
422 if (!aFeature->isAction()) { // do not add action to the data model
423 // event: feature is added
424 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
425 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
426 } else { // feature must be executed
427 // no creation event => updater not working, problem with remove part
434 /// Appenad to the array of references a new referenced label.
435 /// If theIndex is not -1, removes element at thisindex, not theReferenced.
436 /// \returns the index of removed element
437 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, const int theIndex =
440 int aResult = -1; // no returned
441 Handle(TDataStd_ReferenceArray) aRefs;
442 if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
443 if (aRefs->Length() == 1) { // just erase an array
444 if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
445 theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
448 } else { // reduce the array
449 Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
451 int aCount = aRefs->Lower();
452 for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
453 if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
457 aNewArray->SetValue(aCount, aRefs->Value(a));
460 aRefs->SetInternalArray(aNewArray);
466 void Model_Document::removeFeature(FeaturePtr theFeature, const bool theCheck)
469 // check the feature: it must have no depended objects on it
470 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
471 for(; aResIter != theFeature->results().cend(); aResIter++) {
472 if (myConcealedResults.find(*aResIter) != myConcealedResults.end()) {
473 Events_Error::send("Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
477 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myObjs);
478 for(; anObjIter.More(); anObjIter.Next()) {
479 DataPtr aData = anObjIter.Value()->data();
480 if (aData->referencesTo(theFeature)) {
481 Events_Error::send("Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
487 boost::shared_ptr<Model_Data> aData = boost::static_pointer_cast<Model_Data>(theFeature->data());
488 TDF_Label aFeatureLabel = aData->label().Father();
489 if (myObjs.IsBound(aFeatureLabel))
490 myObjs.UnBind(aFeatureLabel);
492 return; // not found feature => do not remove
495 // erase all attributes under the label of feature
496 aFeatureLabel.ForgetAllAttributes();
497 // remove it from the references array
498 RemoveFromRefArray(featuresLabel(), aFeatureLabel);
500 // event: feature is deleted
501 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
502 /* this is in "erase"
503 // results of this feature must be redisplayed
504 static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
505 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = theFeature->results();
506 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
507 for (; aRIter != aResults.cend(); aRIter++) {
508 boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
509 aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
510 ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
511 ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), aRes->groupName());
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;
596 if (!isIn && (*aRIter)->isInHistory()) { // check that there is nobody references this result
597 isIn = myConcealedResults.find(*aRIter) == myConcealedResults.end();
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 = myConcealedResults.find(*aRIter) == myConcealedResults.end();
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->isInHistory() && 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)->isInHistory() && (*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)
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();
721 if (!myObjs.IsBound(aFeatureLabel)) { // a new feature is inserted
723 FeaturePtr aNewObj = ModelAPI_Session::get()->createFeature(
724 TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
726 if (!aNewObj) { // somethig is wrong, most probably, the opened document has invalid structure
727 Events_Error::send("Invalid type of object in the document");
728 aLabIter.Value()->Label().ForgetAllAttributes();
731 // this must be before "setData" to redo the sketch line correctly
732 myObjs.Bind(aFeatureLabel, aNewObj);
733 aNewFeatures.insert(aNewObj);
734 initData(aNewObj, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
736 // event: model is updated
737 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
738 ModelAPI_EventCreator::get()->sendUpdated(aNewObj, anEvent);
740 // update results of the appeared feature
741 updateResults(aNewObj);
742 } else { // nothing is changed, both iterators are incremented
743 FeaturePtr aFeature = myObjs.Find(aFeatureLabel);
744 aKeptFeatures.insert(aFeature);
745 if (theMarkUpdated) {
746 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
747 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent);
749 updateResults(aFeature);
752 // execute new features to restore results: after features creation to make all references valid
753 /*std::set<FeaturePtr>::iterator aNewIter = aNewFeatures.begin();
754 for(; aNewIter != aNewFeatures.end(); aNewIter++) {
755 (*aNewIter)->execute();
757 // check all features are checked: if not => it was removed
758 NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myObjs);
759 while (aFIter.More()) {
760 if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
761 && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
762 FeaturePtr aFeature = aFIter.Value();
763 // event: model is updated
764 //if (aFeature->isInHistory()) {
765 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_Feature::group());
767 // results of this feature must be redisplayed (hided)
768 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
769 const std::list<boost::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
770 std::list<boost::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
772 for (; aRIter != aResults.cend(); aRIter++) {
773 boost::shared_ptr<ModelAPI_Result> aRes = *aRIter;
774 //aRes->setData(boost::shared_ptr<ModelAPI_Data>()); // deleted flag
775 ModelAPI_EventCreator::get()->sendUpdated(aRes, EVENT_DISP);
776 ModelAPI_EventCreator::get()->sendDeleted(aThis, aRes->groupName());
779 // redisplay also removed feature (used for sketch and AISObject)
780 ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
782 // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
783 TDF_Label aLab = aFIter.Key();
790 myExecuteFeatures = false;
791 aLoop->activateFlushes(true);
793 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
794 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
795 if (theMarkUpdated) {
796 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
798 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
799 boost::static_pointer_cast<Model_Session>(Model_Session::get())
800 ->setCheckTransactions(true);
801 myExecuteFeatures = true;
804 TDF_Label Model_Document::resultLabel(
805 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
807 const boost::shared_ptr<Model_Data>& aData =
808 boost::dynamic_pointer_cast<Model_Data>(theFeatureData);
809 return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
812 void Model_Document::storeResult(boost::shared_ptr<ModelAPI_Data> theFeatureData,
813 boost::shared_ptr<ModelAPI_Result> theResult,
814 const int theResultIndex)
816 boost::shared_ptr<ModelAPI_Document> aThis =
817 Model_Application::getApplication()->getDocument(myID);
818 theResult->setDoc(aThis);
819 initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
820 if (theResult->data()->name().empty()) { // if was not initialized, generate event and set a name
821 theResult->data()->setName(theFeatureData->name());
825 static const Standard_GUID ID_CONSTRUCTION("b59fa408-8ab1-42b8-980c-af5adeebe7e4");
826 static const Standard_GUID ID_BODY("c1148e9a-9b17-4e9c-9160-18e918fd0013");
827 static const Standard_GUID ID_PART("1b3319b9-3e0a-4298-a1dc-3fb5aaf9be59");
829 boost::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
830 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
832 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
833 TDataStd_UAttribute::Set(aLab, ID_CONSTRUCTION);
834 ObjectPtr anOldObject = object(aLab);
835 boost::shared_ptr<ModelAPI_ResultConstruction> aResult;
837 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
840 aResult = boost::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
841 storeResult(theFeatureData, aResult, theIndex);
846 boost::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
847 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
849 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
850 TDataStd_UAttribute::Set(aLab, ID_BODY);
851 ObjectPtr anOldObject = object(aLab);
852 boost::shared_ptr<ModelAPI_ResultBody> aResult;
854 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
857 aResult = boost::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
858 storeResult(theFeatureData, aResult, theIndex);
863 boost::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
864 const boost::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
866 TDF_Label aLab = resultLabel(theFeatureData, theIndex);
867 TDataStd_UAttribute::Set(aLab, ID_PART);
868 ObjectPtr anOldObject = object(aLab);
869 boost::shared_ptr<ModelAPI_ResultPart> aResult;
871 aResult = boost::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
874 aResult = boost::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
875 storeResult(theFeatureData, aResult, theIndex);
880 boost::shared_ptr<ModelAPI_Feature> Model_Document::feature(
881 const boost::shared_ptr<ModelAPI_Result>& theResult)
883 boost::shared_ptr<Model_Data> aData = boost::dynamic_pointer_cast<Model_Data>(theResult->data());
885 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
886 return feature(aFeatureLab);
891 void Model_Document::updateResults(FeaturePtr theFeature)
893 // for not persistent is will be done by parametric updater automatically
894 if (!theFeature->isPersistentResult()) return;
895 // check the existing results and remove them if there is nothing on the label
896 std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
897 while(aResIter != theFeature->results().cend()) {
898 ResultBodyPtr aBody = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(*aResIter);
900 if (!aBody->data()->isValid()) {
901 // found a disappeared result => remove it
902 theFeature->removeResult(aBody);
903 // start iterate from beginning because iterator is corrupted by removing
904 aResIter = theFeature->results().cbegin();
910 // check that results are presented on all labels
911 int aResSize = theFeature->results().size();
912 TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
913 for(; aLabIter.More(); aLabIter.Next()) {
914 // here must be GUID of the feature
915 int aResIndex = aLabIter.Value().Tag() - 1;
917 if (aResSize <= aResIndex) {
918 TDF_Label anArgLab = aLabIter.Value();
919 if (anArgLab.IsAttribute(ID_BODY)) {
920 aNewBody = createBody(theFeature->data(), aResIndex);
921 } else if (anArgLab.IsAttribute(ID_PART)) {
922 aNewBody = createPart(theFeature->data(), aResIndex);
923 } else if (!anArgLab.IsAttribute(ID_CONSTRUCTION) && anArgLab.FindChild(1).HasAttribute()) {
924 Events_Error::send("Unknown type of result is found in the document");
927 theFeature->setResult(aNewBody, aResIndex);
933 void Model_Document::objectIsReferenced(const ObjectPtr& theObject)
935 // only bodies are concealed now
936 ResultBodyPtr aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(theObject);
938 if (myConcealedResults.find(aResult) != myConcealedResults.end()) {
939 Events_Error::send(std::string("The object '") + aResult->data()->name() +
940 "' is already referenced");
942 myConcealedResults.insert(aResult);
943 boost::shared_ptr<ModelAPI_Document> aThis =
944 Model_Application::getApplication()->getDocument(myID);
945 ModelAPI_EventCreator::get()->sendDeleted(aThis, ModelAPI_ResultBody::group());
947 static Events_Loop* aLoop = Events_Loop::loop();
948 static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
949 static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
950 aECreator->sendUpdated(aResult, EVENT_DISP);
955 void Model_Document::objectIsNotReferenced(const ObjectPtr& theObject)
957 // only bodies are concealed now
958 ResultBodyPtr aResult = boost::dynamic_pointer_cast<ModelAPI_ResultBody>(theObject);
960 std::set<ResultPtr>::iterator aFind = myConcealedResults.find(aResult);
961 if (aFind != myConcealedResults.end()) {
962 ResultPtr aFeature = *aFind;
963 myConcealedResults.erase(aFind);
964 boost::shared_ptr<ModelAPI_Document> aThis =
965 Model_Application::getApplication()->getDocument(myID);
966 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
967 ModelAPI_EventCreator::get()->sendUpdated(aFeature, anEvent, false);
969 Events_Error::send(std::string("The object '") + aResult->data()->name() +
970 "' was not referenced '");
975 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
977 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
980 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
982 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);