1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: Model_Document.cxx
4 // Created: 28 Feb 2014
5 // Author: Mikhail PONIKAROV
7 #include <Model_Document.h>
8 #include <Model_Data.h>
9 #include <Model_Objects.h>
10 #include <Model_Application.h>
11 #include <Model_Session.h>
12 #include <Model_Events.h>
13 #include <ModelAPI_ResultPart.h>
14 #include <ModelAPI_Validator.h>
15 #include <ModelAPI_CompositeFeature.h>
16 #include <ModelAPI_AttributeSelectionList.h>
17 #include <ModelAPI_Tools.h>
19 #include <Events_Loop.h>
20 #include <Events_Error.h>
22 #include <TDataStd_Integer.hxx>
23 #include <TDataStd_Comment.hxx>
24 #include <TDF_ChildIDIterator.hxx>
25 #include <TDataStd_ReferenceArray.hxx>
26 #include <TDataStd_HLabelArray1.hxx>
27 #include <TDataStd_Name.hxx>
28 #include <TDF_Reference.hxx>
29 #include <TDF_ChildIDIterator.hxx>
30 #include <TDF_LabelMapHasher.hxx>
31 #include <TDF_Delta.hxx>
32 #include <OSD_File.hxx>
33 #include <OSD_Path.hxx>
34 #include <TDF_AttributeDelta.hxx>
35 #include <TDF_AttributeDeltaList.hxx>
36 #include <TDF_ListIteratorOfAttributeDeltaList.hxx>
37 #include <TDF_ListIteratorOfLabelList.hxx>
45 # define _separator_ '\\'
47 # define _separator_ '/'
50 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
52 static const int TAG_GENERAL = 1; // general properties tag
55 static const int TAG_CURRENT_FEATURE = 1; ///< where the reference to the current feature label is located (or no attribute if null feature)
56 static const int TAG_CURRENT_TRANSACTION = 2; ///< integer, index of the cransaction
57 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
59 Model_Document::Model_Document(const std::string theID, const std::string theKind)
60 : myID(theID), myKind(theKind), myIsActive(false),
61 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
63 myObjs = new Model_Objects(myDoc->Main());
64 myDoc->SetUndoLimit(UNDO_LIMIT);
65 myTransactionSave = 0;
66 myExecuteFeatures = true;
67 // to have something in the document and avoid empty doc open/save problem
68 // in transaction for nesting correct working
70 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
71 myDoc->CommitCommand();
74 void Model_Document::setThis(DocumentPtr theDoc)
76 myObjs->setOwner(theDoc);
79 /// Returns the file name of this document by the nameof directory and identifuer of a document
80 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
82 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
83 // remove end-separators
84 while(aPath.Length() &&
85 (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
86 aPath.Remove(aPath.Length());
88 aPath += theID.c_str();
89 aPath += ".cbf"; // standard binary file extension
93 bool Model_Document::isRoot() const
95 return this == Model_Session::get()->moduleDocument().get();
98 bool Model_Document::load(const char* theFileName, DocumentPtr theThis)
100 Handle(Model_Application) anApp = Model_Application::getApplication();
102 anApp->setLoadPath(theFileName);
104 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
105 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
107 aStatus = anApp->Open(aPath, myDoc);
108 } catch (Standard_Failure) {
109 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
111 std::string("Exception in opening of document: ") + aFail->GetMessageString());
114 bool isError = aStatus != PCDM_RS_OK;
117 case PCDM_RS_UnknownDocument:
118 Events_Error::send(std::string("Can not open document"));
120 case PCDM_RS_AlreadyRetrieved:
121 Events_Error::send(std::string("Can not open document: already opened"));
123 case PCDM_RS_AlreadyRetrievedAndModified:
125 std::string("Can not open document: already opened and modified"));
127 case PCDM_RS_NoDriver:
128 Events_Error::send(std::string("Can not open document: driver library is not found"));
130 case PCDM_RS_UnknownFileDriver:
131 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
133 case PCDM_RS_OpenError:
134 Events_Error::send(std::string("Can not open document: file open error"));
136 case PCDM_RS_NoVersion:
137 Events_Error::send(std::string("Can not open document: invalid version"));
139 case PCDM_RS_NoModel:
140 Events_Error::send(std::string("Can not open document: no data model"));
142 case PCDM_RS_NoDocument:
143 Events_Error::send(std::string("Can not open document: no document inside"));
145 case PCDM_RS_FormatFailure:
146 Events_Error::send(std::string("Can not open document: format failure"));
148 case PCDM_RS_TypeNotFoundInSchema:
149 Events_Error::send(std::string("Can not open document: invalid object"));
151 case PCDM_RS_UnrecognizedFileFormat:
152 Events_Error::send(std::string("Can not open document: unrecognized file format"));
154 case PCDM_RS_MakeFailure:
155 Events_Error::send(std::string("Can not open document: make failure"));
157 case PCDM_RS_PermissionDenied:
158 Events_Error::send(std::string("Can not open document: permission denied"));
160 case PCDM_RS_DriverFailure:
161 Events_Error::send(std::string("Can not open document: driver failure"));
164 Events_Error::send(std::string("Can not open document: unknown error"));
169 myDoc->SetUndoLimit(UNDO_LIMIT);
170 // to avoid the problem that feature is created in the current, not this, document
171 std::shared_ptr<Model_Session> aSession =
172 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
173 aSession->setActiveDocument(anApp->getDocument(myID), false);
174 aSession->setCheckTransactions(false);
177 myObjs = new Model_Objects(myDoc->Main()); // synchronisation is inside
178 myObjs->setOwner(theThis);
179 // update the current features status
180 setCurrentFeature(currentFeature(false), false);
181 aSession->setCheckTransactions(true);
182 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
183 // this is done in Part result "activate", so no needed here. Causes not-blue active part.
184 // aSession->setActiveDocument(anApp->getDocument(myID), true);
189 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
191 // create a directory in the root document if it is not yet exist
192 Handle(Model_Application) anApp = Model_Application::getApplication();
195 CreateDirectory(theFileName, NULL);
197 mkdir(theFileName, 0x1ff);
200 // filename in the dir is id of document inside of the given directory
201 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
202 PCDM_StoreStatus aStatus;
204 aStatus = anApp->SaveAs(myDoc, aPath);
205 } catch (Standard_Failure) {
206 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
208 std::string("Exception in saving of document: ") + aFail->GetMessageString());
211 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
214 case PCDM_SS_DriverFailure:
215 Events_Error::send(std::string("Can not save document: save driver-library failure"));
217 case PCDM_SS_WriteFailure:
218 Events_Error::send(std::string("Can not save document: file writing failure"));
220 case PCDM_SS_Failure:
222 Events_Error::send(std::string("Can not save document"));
226 myTransactionSave = myTransactions.size();
227 if (isDone) { // save also sub-documents if any
228 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
229 const std::set<std::string> aSubs = subDocuments(false);
230 std::set<std::string>::iterator aSubIter = aSubs.begin();
231 for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
232 if (anApp->isLoadByDemand(*aSubIter)) {
233 // copy not-activated document that is not in the memory
234 std::string aDocName = *aSubIter;
235 if (!aDocName.empty()) {
237 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
238 OSD_Path aPath(aSubPath);
239 OSD_File aFile(aPath);
240 if (aFile.Exists()) {
241 TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
242 OSD_Path aDestination(aDestinationDir);
243 aFile.Copy(aDestination);
244 theResults.push_back(aDestinationDir.ToCString());
247 std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
250 } else { // simply save opened document
251 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
258 void Model_Document::close(const bool theForever)
260 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
261 if (!isRoot() && this == aPM->activeDocument().get()) {
262 aPM->setActiveDocument(aPM->moduleDocument());
263 } else if (isRoot()) {
264 // erase the active document if root is closed
265 aPM->setActiveDocument(DocumentPtr());
268 const std::set<std::string> aSubs = subDocuments(true);
269 std::set<std::string>::iterator aSubIter = aSubs.begin();
270 for (; aSubIter != aSubs.end(); aSubIter++) {
271 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
272 if (aSub->myObjs) // if it was not closed before
273 aSub->close(theForever);
276 // close for thid document needs no transaction in this document
277 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
279 // close all only if it is really asked, otherwise it can be undoed/redoed
283 if (myDoc->CanClose() == CDM_CCS_OK)
285 mySelectionFeature.reset();
287 setCurrentFeature(FeaturePtr(), false); // disables all features
290 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
293 void Model_Document::startOperation()
295 if (myDoc->HasOpenCommand()) { // start of nested command
296 if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
297 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
299 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
300 myDoc->OpenCommand();
301 } else { // start the simple command
304 // starts a new operation
305 incrementTransactionID();
306 myTransactions.push_back(Transaction());
307 if (!myNestedNum.empty())
308 (*myNestedNum.rbegin())++;
310 // new command for all subs
311 const std::set<std::string> aSubs = subDocuments(true);
312 std::set<std::string>::iterator aSubIter = aSubs.begin();
313 for (; aSubIter != aSubs.end(); aSubIter++)
314 subDoc(*aSubIter)->startOperation();
317 void Model_Document::compactNested()
319 if (!myNestedNum.empty()) {
320 int aNumToCompact = *(myNestedNum.rbegin());
321 int aSumOfTransaction = 0;
322 for(int a = 0; a < aNumToCompact; a++) {
323 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
324 myTransactions.pop_back();
326 // the latest transaction is the start of lower-level operation which startes the nested
327 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
328 myNestedNum.pop_back();
332 bool Model_Document::finishOperation()
334 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
335 static std::shared_ptr<Model_Session> aSession =
336 std::static_pointer_cast<Model_Session>(Model_Session::get());
337 myObjs->synchronizeBackRefs();
338 Events_Loop* aLoop = Events_Loop::loop();
339 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
340 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
341 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
342 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
343 // this must be here just after everything is finished but before real transaction stop
344 // to avoid messages about modifications outside of the transaction
345 // and to rebuild everything after all updates and creates
346 if (isRoot()) { // once for root document
347 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
348 static std::shared_ptr<Events_Message> aFinishMsg
349 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
350 Events_Loop::loop()->send(aFinishMsg);
351 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
353 // to avoid "updated" message appearance by updater
354 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
356 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
357 bool aResult = false;
358 const std::set<std::string> aSubs = subDocuments(true);
359 std::set<std::string>::iterator aSubIter = aSubs.begin();
360 for (; aSubIter != aSubs.end(); aSubIter++)
361 if (subDoc(*aSubIter)->finishOperation())
364 // transaction may be empty if this document was created during this transaction (create part)
365 if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
366 myTransactions.rbegin()->myOCAFNum++;
370 if (isNestedClosed) {
373 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
374 aResult = myTransactions.rbegin()->myOCAFNum != 0;
376 if (!aResult && isRoot()) {
377 // nothing inside in all documents, so remove this transaction from the transactions list
378 undoInternal(true, false);
380 // on finish clear redos in any case (issue 446) and for all subs (issue 408)
383 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
384 subDoc(*aSubIter)->myDoc->ClearRedos();
385 subDoc(*aSubIter)->myRedos.clear();
391 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
392 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
393 const bool isRedo = false) {
394 Handle(TDF_Delta) aDelta;
396 aDelta = theDoc->GetRedos().First();
398 aDelta = theDoc->GetUndos().Last();
399 TDF_LabelList aDeltaList;
400 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
401 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
402 theDelta.Append(aListIter.Value());
404 // add also label of the modified attributes
405 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
406 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
407 theDelta.Append(anAttr.Value()->Label());
411 void Model_Document::abortOperation()
413 TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
414 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
416 // store undo-delta here as undo actually does in the method later
417 int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
418 for(a = 0; a < aNumTransactions; a++) {
419 modifiedLabels(myDoc, aDeltaLabels);
422 for(a = 0; a < aNumTransactions; a++) {
426 undoInternal(false, false);
429 } else { // abort the current
430 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
431 myTransactions.pop_back();
432 if (!myNestedNum.empty())
433 (*myNestedNum.rbegin())--;
434 // roll back the needed number of transactions
435 // make commit/undo to get the modification delta
436 //myDoc->AbortCommand();
437 if (myDoc->CommitCommand()) {
438 modifiedLabels(myDoc, aDeltaLabels);
441 for(int a = 0; a < aNumTransactions; a++) {
442 modifiedLabels(myDoc, aDeltaLabels);
447 // abort for all subs, flushes will be later, in the end of root abort
448 const std::set<std::string> aSubs = subDocuments(true);
449 std::set<std::string>::iterator aSubIter = aSubs.begin();
450 for (; aSubIter != aSubs.end(); aSubIter++)
451 subDoc(*aSubIter)->abortOperation();
452 // references may be changed because they are set in attributes on the fly
453 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
456 bool Model_Document::isOperation() const
458 // operation is opened for all documents: no need to check subs
459 return myDoc->HasOpenCommand() == Standard_True ;
462 bool Model_Document::isModified()
464 // is modified if at least one operation was commited and not undoed
465 return myTransactions.size() != myTransactionSave || isOperation();
468 bool Model_Document::canUndo()
470 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
471 int aCurrentNum = isOperation() ? 1 : 0;
472 if (myDoc->GetAvailableUndos() > 0 &&
473 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
474 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
476 // check other subs contains operation that can be undoed
477 const std::set<std::string> aSubs = subDocuments(true);
478 std::set<std::string>::iterator aSubIter = aSubs.begin();
479 for (; aSubIter != aSubs.end(); aSubIter++) {
480 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
481 if (aSub->myObjs) {// if it was not closed before
490 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
492 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
493 myRedos.push_back(*myTransactions.rbegin());
494 myTransactions.pop_back();
495 if (!myNestedNum.empty())
496 (*myNestedNum.rbegin())--;
497 // roll back the needed number of transactions
498 TDF_LabelList aDeltaLabels;
499 for(int a = 0; a < aNumTransactions; a++) {
501 modifiedLabels(myDoc, aDeltaLabels);
507 const std::set<std::string> aSubs = subDocuments(true);
508 std::set<std::string>::iterator aSubIter = aSubs.begin();
509 for (; aSubIter != aSubs.end(); aSubIter++) {
510 if (!subDoc(*aSubIter)->myObjs)
512 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
515 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
516 if (theSynchronize) {
517 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
518 // update the current features status
519 setCurrentFeature(currentFeature(false), false);
523 void Model_Document::undo()
525 undoInternal(true, true);
528 bool Model_Document::canRedo()
530 if (!myRedos.empty())
532 // check other subs contains operation that can be redoed
533 const std::set<std::string> aSubs = subDocuments(true);
534 std::set<std::string>::iterator aSubIter = aSubs.begin();
535 for (; aSubIter != aSubs.end(); aSubIter++) {
536 if (!subDoc(*aSubIter)->myObjs)
538 if (subDoc(*aSubIter)->canRedo())
544 void Model_Document::redo()
546 if (!myNestedNum.empty())
547 (*myNestedNum.rbegin())++;
548 int aNumRedos = myRedos.rbegin()->myOCAFNum;
549 myTransactions.push_back(*myRedos.rbegin());
551 TDF_LabelList aDeltaLabels;
552 for(int a = 0; a < aNumRedos; a++) {
553 modifiedLabels(myDoc, aDeltaLabels, true);
558 const std::set<std::string> aSubs = subDocuments(true);
559 std::set<std::string>::iterator aSubIter = aSubs.begin();
560 for (; aSubIter != aSubs.end(); aSubIter++)
561 subDoc(*aSubIter)->redo();
563 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
564 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
565 // update the current features status
566 setCurrentFeature(currentFeature(false), false);
569 std::list<std::string> Model_Document::undoList() const
571 std::list<std::string> aResult;
572 // the number of skipped current operations (on undo they will be aborted)
573 int aSkipCurrent = isOperation() ? 1 : 0;
574 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
575 int aNumUndo = myTransactions.size();
576 if (!myNestedNum.empty())
577 aNumUndo = *myNestedNum.rbegin();
578 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
579 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
585 std::list<std::string> Model_Document::redoList() const
587 std::list<std::string> aResult;
588 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
589 for( ; aTrIter != myRedos.crend(); aTrIter++) {
590 aResult.push_back(aTrIter->myId);
595 void Model_Document::operationId(const std::string& theId)
597 myTransactions.rbegin()->myId = theId;
600 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
602 std::shared_ptr<Model_Session> aSession =
603 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
604 FeaturePtr aFeature = aSession->createFeature(theID, this);
607 Model_Document* aDocToAdd;
608 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
609 if (aFeature->documentToAdd() != kind()) { // the root document by default
610 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
614 } else { // if customized is not presented, add to "this" document
618 // searching for feature after which must be added the next feature: this is the current feature
619 // but also all sub-features of this feature
620 FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
621 bool isModified = true;
622 for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
623 aComp.get() && isModified;
624 aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
626 int aSubs = aComp->numberOfSubs(false);
627 for(int a = 0; a < aSubs; a++) {
628 FeaturePtr aSub = aComp->subFeature(a, false);
629 if (myObjs->isLater(aSub, aCurrent)) {
635 aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
636 if (!aFeature->isAction()) { // do not add action to the data model
637 if (theMakeCurrent) // after all this feature stays in the document, so make it current
638 aDocToAdd->setCurrentFeature(aFeature, false);
639 } else { // feature must be executed
640 // no creation event => updater not working, problem with remove part
648 void Model_Document::refsToFeature(FeaturePtr theFeature,
649 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
651 myObjs->refsToFeature(theFeature, theRefs, isSendError);
654 void Model_Document::removeFeature(FeaturePtr theFeature)
656 myObjs->removeFeature(theFeature);
659 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
661 myObjs->moveFeature(theMoved, theAfterThis);
664 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
666 myObjs->updateHistory(theObject);
669 void Model_Document::updateHistory(const std::string theGroup)
671 myObjs->updateHistory(theGroup);
674 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
676 return Model_Application::getApplication()->getDocument(theDocID);
679 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
681 std::set<std::string> aResult;
682 std::list<ResultPtr> aPartResults;
683 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
684 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
685 for(; aPartRes != aPartResults.end(); aPartRes++) {
686 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
687 if (aPart && (!theActivatedOnly || aPart->isActivated())) {
688 aResult.insert(aPart->original()->data()->name());
694 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
696 // just store sub-document identifier here to manage it later
697 return std::dynamic_pointer_cast<Model_Document>(
698 Model_Application::getApplication()->getDocument(theDocID));
701 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
703 return myObjs->object(theGroupID, theIndex);
706 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
707 const std::string& theGroupID, const std::string& theName)
709 return myObjs->objectByName(theGroupID, theName);
712 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
714 return myObjs->index(theObject);
717 int Model_Document::size(const std::string& theGroupID)
719 return myObjs->size(theGroupID);
722 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
724 if (!myObjs) // on close document feature destruction it may call this method
725 return std::shared_ptr<ModelAPI_Feature>();
726 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
727 Handle(TDF_Reference) aRef;
728 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
729 TDF_Label aLab = aRef->Get();
730 FeaturePtr aResult = myObjs->feature(aLab);
731 if (theVisible) { // get nearest visible (in history) going up
732 while(aResult.get() && // sub-composites are never in history
733 (!aResult->isInHistory() || ModelAPI_Tools::compositeOwner(aResult).get())) {
734 aResult = myObjs->nextFeature(aResult, true);
739 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
742 void Model_Document::setCurrentFeature(std::shared_ptr<ModelAPI_Feature> theCurrent,
743 const bool theVisible)
745 // blocks the flush signals to avoid each objects visualization in the viewer
746 // they should not be shown once after all modifications are performed
747 Events_Loop* aLoop = Events_Loop::loop();
748 bool isActive = aLoop->activateFlushes(false);
750 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
751 CompositeFeaturePtr aMain; // main feature that may nest the new current
752 if (theCurrent.get()) {
753 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
755 // if feature nests into compisite feature, make the composite feature as current
756 const std::set<AttributePtr>& aRefsToMe = theCurrent->data()->refsToMe();
757 std::set<AttributePtr>::const_iterator aRefToMe = aRefsToMe.begin();
758 for(; aRefToMe != aRefsToMe.end(); aRefToMe++) {
759 CompositeFeaturePtr aComposite =
760 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>((*aRefToMe)->owner());
761 if (aComposite.get() && aComposite->isSub(theCurrent)) {
769 if (theVisible) { // make features below which are not in history also enabled: sketch subs
771 theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
772 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
773 if (aNext->isInHistory()) {
774 break; // next in history is not needed
775 } else { // next not in history is good for making current
780 if (theCurrent.get()) {
781 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
782 if (!aData.get() || !aData->isValid()) {
783 aLoop->activateFlushes(isActive);
786 TDF_Label aFeatureLabel = aData->label().Father();
788 Handle(TDF_Reference) aRef;
789 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
790 aRef->Set(aFeatureLabel);
792 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
794 } else { // remove reference for the null feature
795 aRefLab.ForgetAttribute(TDF_Reference::GetID());
797 // make all features after this feature disabled in reversed order (to remove results without deps)
798 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
799 static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
800 static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
802 bool aPassed = false; // flag that the current object is already passed in cycle
803 FeaturePtr anIter = myObjs->lastFeature();
804 bool aWasChanged = false;
805 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
806 // check this before passed become enabled: the current feature is enabled!
807 if (anIter == theCurrent) aPassed = true;
809 bool aDisabledFlag = !aPassed;
810 if (aMain.get() && aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
811 aDisabledFlag = false;
812 if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
813 if (theCurrent.get() && theCurrent->getKind() != "Parameter")
814 aDisabledFlag = false;
816 if (anIter->setDisabled(aDisabledFlag)) {
817 // state of feature is changed => so feature become updated
818 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
819 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
820 // flush is in the end of this method
821 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
824 // update for everyone the concealment flag immideately: on edit feature in the midle of history
826 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = anIter->results();
827 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
828 for(; aRes != aResList.end(); aRes++) {
829 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
830 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
835 // unblock the flush signals and up them after this
836 aLoop->activateFlushes(isActive);
838 aLoop->flush(aCreateEvent);
839 aLoop->flush(aRedispEvent);
840 aLoop->flush(aDeleteEvent);
843 void Model_Document::setCurrentFeatureUp()
845 // on remove just go up for minimum step: highlight external objects in sketch causes
846 // problems if it is true: here and in "setCurrentFeature"
847 FeaturePtr aCurrent = currentFeature(false);
848 if (aCurrent.get()) { // if not, do nothing because null is the upper
849 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
850 setCurrentFeature(aPrev, false);
854 TDF_Label Model_Document::generalLabel() const
856 return myDoc->Main().FindChild(TAG_GENERAL);
859 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
860 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
862 return myObjs->createConstruction(theFeatureData, theIndex);
865 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
866 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
868 return myObjs->createBody(theFeatureData, theIndex);
871 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
872 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
874 return myObjs->createPart(theFeatureData, theIndex);
877 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
878 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
879 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
881 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
884 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
885 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
887 return myObjs->createGroup(theFeatureData, theIndex);
890 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
891 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
893 return myObjs->createParameter(theFeatureData, theIndex);
896 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
897 const std::shared_ptr<ModelAPI_Result>& theResult)
899 return myObjs->feature(theResult);
902 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
904 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
907 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
909 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
912 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
914 myNamingNames[theName] = theLabel;
917 TDF_Label Model_Document::findNamingName(std::string theName)
919 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
920 if (aFind == myNamingNames.end())
921 return TDF_Label(); // not found
922 return aFind->second;
925 ResultPtr Model_Document::findByName(const std::string theName)
927 return myObjs->findByName(theName);
930 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
932 return myObjs->allFeatures();
935 void Model_Document::setActive(const bool theFlag)
937 if (theFlag != myIsActive) {
938 myIsActive = theFlag;
939 // redisplay all the objects of this part
940 static Events_Loop* aLoop = Events_Loop::loop();
941 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
943 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
944 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
945 object(ModelAPI_Feature::group(), a));
946 if (aFeature.get() && aFeature->data()->isValid()) {
947 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
948 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
949 for(; aRes != aResList.end(); aRes++) {
950 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
957 bool Model_Document::isActive() const
962 int Model_Document::transactionID()
964 Handle(TDataStd_Integer) anIndex;
965 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
966 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
967 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
969 return anIndex->Get();
972 void Model_Document::incrementTransactionID()
974 int aNewVal = transactionID() + 1;
975 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
977 void Model_Document::decrementTransactionID()
979 int aNewVal = transactionID() - 1;
980 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
983 bool Model_Document::isOpened()
985 return myObjs && !myDoc.IsNull();
988 int Model_Document::numInternalFeatures()
990 return myObjs->numInternalFeatures();
993 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
995 return myObjs->internalFeature(theIndex);
998 // Feature that is used for selection in the Part document by the external request
999 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1001 /// Nothing to do in constructor
1002 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1004 /// Returns the unique kind of a feature
1005 virtual const std::string& getKind() {
1006 static std::string MY_KIND("InternalSelectionInPartFeature");
1009 /// Request for initialization of data model of the object: adding all attributes
1010 virtual void initAttributes() {
1011 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1013 /// Nothing to do in the execution function
1014 virtual void execute() {}
1018 //! Returns the feature that is used for calculation of selection externally from the document
1019 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1021 // return already created, otherwise create
1022 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1024 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1026 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1027 std::shared_ptr<Model_Data> aData(new Model_Data);
1028 aData->setLabel(aFeatureLab.FindChild(1));
1029 aData->setObject(mySelectionFeature);
1030 mySelectionFeature->setDoc(myObjs->owner());
1031 mySelectionFeature->setData(aData);
1032 std::string aName = id() + "_Part";
1033 mySelectionFeature->data()->setName(aName);
1034 mySelectionFeature->setDoc(myObjs->owner());
1035 mySelectionFeature->initAttributes();
1037 return mySelectionFeature->selectionList("selection");
1040 FeaturePtr Model_Document::lastFeature()
1043 return myObjs->lastFeature();
1044 return FeaturePtr();