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 // this to avoid creation of integer attribute outside the transaction after undo
73 myDoc->CommitCommand();
76 void Model_Document::setThis(DocumentPtr theDoc)
78 myObjs->setOwner(theDoc);
81 /// Returns the file name of this document by the nameof directory and identifuer of a document
82 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
84 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
85 // remove end-separators
86 while(aPath.Length() &&
87 (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
88 aPath.Remove(aPath.Length());
90 aPath += theID.c_str();
91 aPath += ".cbf"; // standard binary file extension
95 bool Model_Document::isRoot() const
97 return this == Model_Session::get()->moduleDocument().get();
100 bool Model_Document::load(const char* theFileName, DocumentPtr theThis)
102 Handle(Model_Application) anApp = Model_Application::getApplication();
104 anApp->setLoadPath(theFileName);
106 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
107 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
108 Handle(TDocStd_Document) aLoaded;
110 aStatus = anApp->Open(aPath, aLoaded);
111 } catch (Standard_Failure) {
112 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
114 std::string("Exception in opening of document: ") + aFail->GetMessageString());
117 bool isError = aStatus != PCDM_RS_OK;
120 case PCDM_RS_UnknownDocument:
121 Events_Error::send(std::string("Can not open document"));
123 case PCDM_RS_AlreadyRetrieved:
124 Events_Error::send(std::string("Can not open document: already opened"));
126 case PCDM_RS_AlreadyRetrievedAndModified:
128 std::string("Can not open document: already opened and modified"));
130 case PCDM_RS_NoDriver:
131 Events_Error::send(std::string("Can not open document: driver library is not found"));
133 case PCDM_RS_UnknownFileDriver:
134 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
136 case PCDM_RS_OpenError:
137 Events_Error::send(std::string("Can not open document: file open error"));
139 case PCDM_RS_NoVersion:
140 Events_Error::send(std::string("Can not open document: invalid version"));
142 case PCDM_RS_NoModel:
143 Events_Error::send(std::string("Can not open document: no data model"));
145 case PCDM_RS_NoDocument:
146 Events_Error::send(std::string("Can not open document: no document inside"));
148 case PCDM_RS_FormatFailure:
149 Events_Error::send(std::string("Can not open document: format failure"));
151 case PCDM_RS_TypeNotFoundInSchema:
152 Events_Error::send(std::string("Can not open document: invalid object"));
154 case PCDM_RS_UnrecognizedFileFormat:
155 Events_Error::send(std::string("Can not open document: unrecognized file format"));
157 case PCDM_RS_MakeFailure:
158 Events_Error::send(std::string("Can not open document: make failure"));
160 case PCDM_RS_PermissionDenied:
161 Events_Error::send(std::string("Can not open document: permission denied"));
163 case PCDM_RS_DriverFailure:
164 Events_Error::send(std::string("Can not open document: driver failure"));
167 Events_Error::send(std::string("Can not open document: unknown error"));
173 myDoc->SetUndoLimit(UNDO_LIMIT);
174 // to avoid the problem that feature is created in the current, not this, document
175 std::shared_ptr<Model_Session> aSession =
176 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
177 aSession->setActiveDocument(anApp->getDocument(myID), false);
178 aSession->setCheckTransactions(false);
181 myObjs = new Model_Objects(myDoc->Main()); // synchronisation is inside
182 myObjs->setOwner(theThis);
183 // update the current features status
184 setCurrentFeature(currentFeature(false), false);
185 aSession->setCheckTransactions(true);
186 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
187 // this is done in Part result "activate", so no needed here. Causes not-blue active part.
188 // aSession->setActiveDocument(anApp->getDocument(myID), true);
193 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
195 // create a directory in the root document if it is not yet exist
196 Handle(Model_Application) anApp = Model_Application::getApplication();
199 CreateDirectory(theFileName, NULL);
201 mkdir(theFileName, 0x1ff);
204 // filename in the dir is id of document inside of the given directory
205 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
206 PCDM_StoreStatus aStatus;
208 aStatus = anApp->SaveAs(myDoc, aPath);
209 } catch (Standard_Failure) {
210 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
212 std::string("Exception in saving of document: ") + aFail->GetMessageString());
215 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
218 case PCDM_SS_DriverFailure:
219 Events_Error::send(std::string("Can not save document: save driver-library failure"));
221 case PCDM_SS_WriteFailure:
222 Events_Error::send(std::string("Can not save document: file writing failure"));
224 case PCDM_SS_Failure:
226 Events_Error::send(std::string("Can not save document"));
230 myTransactionSave = myTransactions.size();
231 if (isDone) { // save also sub-documents if any
232 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
233 const std::set<std::string> aSubs = subDocuments(false);
234 std::set<std::string>::iterator aSubIter = aSubs.begin();
235 for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
236 if (anApp->isLoadByDemand(*aSubIter)) {
237 // copy not-activated document that is not in the memory
238 std::string aDocName = *aSubIter;
239 if (!aDocName.empty()) {
241 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
242 OSD_Path aPath(aSubPath);
243 OSD_File aFile(aPath);
244 if (aFile.Exists()) {
245 TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
246 OSD_Path aDestination(aDestinationDir);
247 aFile.Copy(aDestination);
248 theResults.push_back(aDestinationDir.ToCString());
251 std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
254 } else { // simply save opened document
255 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
262 void Model_Document::close(const bool theForever)
264 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
265 if (!isRoot() && this == aPM->activeDocument().get()) {
266 aPM->setActiveDocument(aPM->moduleDocument());
267 } else if (isRoot()) {
268 // erase the active document if root is closed
269 aPM->setActiveDocument(DocumentPtr());
272 const std::set<std::string> aSubs = subDocuments(true);
273 std::set<std::string>::iterator aSubIter = aSubs.begin();
274 for (; aSubIter != aSubs.end(); aSubIter++) {
275 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
276 if (aSub->myObjs) // if it was not closed before
277 aSub->close(theForever);
280 // close for thid document needs no transaction in this document
281 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
283 // close all only if it is really asked, otherwise it can be undoed/redoed
285 // flush everything to avoid messages with bad objects
288 if (myDoc->CanClose() == CDM_CCS_OK)
290 mySelectionFeature.reset();
292 setCurrentFeature(FeaturePtr(), false); // disables all features
295 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
298 void Model_Document::startOperation()
300 if (myDoc->HasOpenCommand()) { // start of nested command
301 if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
302 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
304 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
305 myDoc->OpenCommand();
306 } else { // start the simple command
309 // starts a new operation
310 incrementTransactionID();
311 myTransactions.push_back(Transaction());
312 if (!myNestedNum.empty())
313 (*myNestedNum.rbegin())++;
315 // new command for all subs
316 const std::set<std::string> aSubs = subDocuments(true);
317 std::set<std::string>::iterator aSubIter = aSubs.begin();
318 for (; aSubIter != aSubs.end(); aSubIter++)
319 subDoc(*aSubIter)->startOperation();
322 void Model_Document::compactNested()
324 if (!myNestedNum.empty()) {
325 int aNumToCompact = *(myNestedNum.rbegin());
326 int aSumOfTransaction = 0;
327 for(int a = 0; a < aNumToCompact; a++) {
328 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
329 myTransactions.pop_back();
331 // the latest transaction is the start of lower-level operation which startes the nested
332 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
333 myNestedNum.pop_back();
337 bool Model_Document::finishOperation()
339 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
340 static std::shared_ptr<Model_Session> aSession =
341 std::static_pointer_cast<Model_Session>(Model_Session::get());
342 myObjs->synchronizeBackRefs();
343 Events_Loop* aLoop = Events_Loop::loop();
344 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
345 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
346 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
347 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
348 // this must be here just after everything is finished but before real transaction stop
349 // to avoid messages about modifications outside of the transaction
350 // and to rebuild everything after all updates and creates
351 if (isRoot()) { // once for root document
352 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
353 static std::shared_ptr<Events_Message> aFinishMsg
354 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
355 Events_Loop::loop()->send(aFinishMsg);
356 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
358 // to avoid "updated" message appearance by updater
359 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
361 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
362 bool aResult = false;
363 const std::set<std::string> aSubs = subDocuments(true);
364 std::set<std::string>::iterator aSubIter = aSubs.begin();
365 for (; aSubIter != aSubs.end(); aSubIter++)
366 if (subDoc(*aSubIter)->finishOperation())
369 // transaction may be empty if this document was created during this transaction (create part)
370 if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
371 myTransactions.rbegin()->myOCAFNum++;
375 if (isNestedClosed) {
378 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
379 aResult = myTransactions.rbegin()->myOCAFNum != 0;
381 if (!aResult && isRoot()) {
382 // nothing inside in all documents, so remove this transaction from the transactions list
383 undoInternal(true, false);
385 // on finish clear redos in any case (issue 446) and for all subs (issue 408)
388 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
389 subDoc(*aSubIter)->myDoc->ClearRedos();
390 subDoc(*aSubIter)->myRedos.clear();
396 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
397 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
398 const bool isRedo = false) {
399 Handle(TDF_Delta) aDelta;
401 aDelta = theDoc->GetRedos().First();
403 aDelta = theDoc->GetUndos().Last();
404 TDF_LabelList aDeltaList;
405 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
406 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
407 theDelta.Append(aListIter.Value());
409 // add also label of the modified attributes
410 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
411 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
412 theDelta.Append(anAttr.Value()->Label());
416 void Model_Document::abortOperation()
418 TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
419 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
421 // store undo-delta here as undo actually does in the method later
422 int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
423 for(a = 0; a < aNumTransactions; a++) {
424 modifiedLabels(myDoc, aDeltaLabels);
427 for(a = 0; a < aNumTransactions; a++) {
431 undoInternal(false, false);
434 } else { // abort the current
435 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
436 myTransactions.pop_back();
437 if (!myNestedNum.empty())
438 (*myNestedNum.rbegin())--;
439 // roll back the needed number of transactions
440 // make commit/undo to get the modification delta
441 //myDoc->AbortCommand();
442 if (myDoc->CommitCommand()) {
443 modifiedLabels(myDoc, aDeltaLabels);
446 for(int a = 0; a < aNumTransactions; a++) {
447 modifiedLabels(myDoc, aDeltaLabels);
452 // abort for all subs, flushes will be later, in the end of root abort
453 const std::set<std::string> aSubs = subDocuments(true);
454 std::set<std::string>::iterator aSubIter = aSubs.begin();
455 for (; aSubIter != aSubs.end(); aSubIter++)
456 subDoc(*aSubIter)->abortOperation();
457 // references may be changed because they are set in attributes on the fly
458 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
461 bool Model_Document::isOperation() const
463 // operation is opened for all documents: no need to check subs
464 return myDoc->HasOpenCommand() == Standard_True ;
467 bool Model_Document::isModified()
469 // is modified if at least one operation was commited and not undoed
470 return myTransactions.size() != myTransactionSave || isOperation();
473 bool Model_Document::canUndo()
475 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
476 int aCurrentNum = isOperation() ? 1 : 0;
477 if (myDoc->GetAvailableUndos() > 0 &&
478 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
479 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
481 // check other subs contains operation that can be undoed
482 const std::set<std::string> aSubs = subDocuments(true);
483 std::set<std::string>::iterator aSubIter = aSubs.begin();
484 for (; aSubIter != aSubs.end(); aSubIter++) {
485 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
486 if (aSub->myObjs) {// if it was not closed before
495 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
497 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
498 myRedos.push_back(*myTransactions.rbegin());
499 myTransactions.pop_back();
500 if (!myNestedNum.empty())
501 (*myNestedNum.rbegin())--;
502 // roll back the needed number of transactions
503 TDF_LabelList aDeltaLabels;
504 for(int a = 0; a < aNumTransactions; a++) {
506 modifiedLabels(myDoc, aDeltaLabels);
512 const std::set<std::string> aSubs = subDocuments(true);
513 std::set<std::string>::iterator aSubIter = aSubs.begin();
514 for (; aSubIter != aSubs.end(); aSubIter++) {
515 if (!subDoc(*aSubIter)->myObjs)
517 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
520 // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
521 if (theSynchronize) {
522 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
523 // update the current features status
524 setCurrentFeature(currentFeature(false), false);
528 void Model_Document::undo()
530 undoInternal(true, true);
533 bool Model_Document::canRedo()
535 if (!myRedos.empty())
537 // check other subs contains operation that can be redoed
538 const std::set<std::string> aSubs = subDocuments(true);
539 std::set<std::string>::iterator aSubIter = aSubs.begin();
540 for (; aSubIter != aSubs.end(); aSubIter++) {
541 if (!subDoc(*aSubIter)->myObjs)
543 if (subDoc(*aSubIter)->canRedo())
549 void Model_Document::redo()
551 if (!myNestedNum.empty())
552 (*myNestedNum.rbegin())++;
553 int aNumRedos = myRedos.rbegin()->myOCAFNum;
554 myTransactions.push_back(*myRedos.rbegin());
556 TDF_LabelList aDeltaLabels;
557 for(int a = 0; a < aNumRedos; a++) {
558 modifiedLabels(myDoc, aDeltaLabels, true);
563 const std::set<std::string> aSubs = subDocuments(true);
564 std::set<std::string>::iterator aSubIter = aSubs.begin();
565 for (; aSubIter != aSubs.end(); aSubIter++)
566 subDoc(*aSubIter)->redo();
568 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
569 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
570 // update the current features status
571 setCurrentFeature(currentFeature(false), false);
574 std::list<std::string> Model_Document::undoList() const
576 std::list<std::string> aResult;
577 // the number of skipped current operations (on undo they will be aborted)
578 int aSkipCurrent = isOperation() ? 1 : 0;
579 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
580 int aNumUndo = myTransactions.size();
581 if (!myNestedNum.empty())
582 aNumUndo = *myNestedNum.rbegin();
583 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
584 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
590 std::list<std::string> Model_Document::redoList() const
592 std::list<std::string> aResult;
593 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
594 for( ; aTrIter != myRedos.crend(); aTrIter++) {
595 aResult.push_back(aTrIter->myId);
600 void Model_Document::operationId(const std::string& theId)
602 myTransactions.rbegin()->myId = theId;
605 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
607 std::shared_ptr<Model_Session> aSession =
608 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
609 FeaturePtr aFeature = aSession->createFeature(theID, this);
613 Model_Document* aDocToAdd;
614 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
615 if (aFeature->documentToAdd() != kind()) { // the root document by default
616 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
620 } else { // if customized is not presented, add to "this" document
624 // searching for feature after which must be added the next feature: this is the current feature
625 // but also all sub-features of this feature
626 FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
627 bool isModified = true;
628 for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
629 aComp.get() && isModified;
630 aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
632 int aSubs = aComp->numberOfSubs(false);
633 for(int a = 0; a < aSubs; a++) {
634 FeaturePtr aSub = aComp->subFeature(a, false);
635 if (myObjs->isLater(aSub, aCurrent)) {
641 aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
642 if (!aFeature->isAction()) { // do not add action to the data model
643 if (theMakeCurrent) // after all this feature stays in the document, so make it current
644 aDocToAdd->setCurrentFeature(aFeature, false);
645 } else { // feature must be executed
646 // no creation event => updater not working, problem with remove part
654 void Model_Document::refsToFeature(FeaturePtr theFeature,
655 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
657 myObjs->refsToFeature(theFeature, theRefs, isSendError);
660 void Model_Document::removeFeature(FeaturePtr theFeature)
662 myObjs->removeFeature(theFeature);
665 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
667 myObjs->moveFeature(theMoved, theAfterThis);
668 if (theAfterThis == currentFeature(true))
669 setCurrentFeature(theMoved, true);
672 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
674 myObjs->updateHistory(theObject);
677 void Model_Document::updateHistory(const std::string theGroup)
679 myObjs->updateHistory(theGroup);
682 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
684 return Model_Application::getApplication()->getDocument(theDocID);
687 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
689 std::set<std::string> aResult;
690 std::list<ResultPtr> aPartResults;
691 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
692 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
693 for(; aPartRes != aPartResults.end(); aPartRes++) {
694 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
695 if (aPart && (!theActivatedOnly || aPart->isActivated())) {
696 aResult.insert(aPart->original()->data()->name());
702 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
704 // just store sub-document identifier here to manage it later
705 return std::dynamic_pointer_cast<Model_Document>(
706 Model_Application::getApplication()->getDocument(theDocID));
709 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
711 return myObjs->object(theGroupID, theIndex);
714 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
715 const std::string& theGroupID, const std::string& theName)
717 return myObjs->objectByName(theGroupID, theName);
720 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
722 return myObjs->index(theObject);
725 int Model_Document::size(const std::string& theGroupID)
727 return myObjs->size(theGroupID);
730 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
732 if (!myObjs) // on close document feature destruction it may call this method
733 return std::shared_ptr<ModelAPI_Feature>();
734 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
735 Handle(TDF_Reference) aRef;
736 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
737 TDF_Label aLab = aRef->Get();
738 FeaturePtr aResult = myObjs->feature(aLab);
739 if (theVisible) { // get nearest visible (in history) going up
740 while(aResult.get() && // sub-composites are never in history
741 (!aResult->isInHistory() || ModelAPI_Tools::compositeOwner(aResult).get())) {
742 aResult = myObjs->nextFeature(aResult, true);
747 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
750 void Model_Document::setCurrentFeature(std::shared_ptr<ModelAPI_Feature> theCurrent,
751 const bool theVisible, const bool theFlushUpdates)
753 // blocks the flush signals to avoid each objects visualization in the viewer
754 // they should not be shown once after all modifications are performed
755 Events_Loop* aLoop = Events_Loop::loop();
756 bool isActive = aLoop->activateFlushes(false);
758 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
759 CompositeFeaturePtr aMain; // main feature that may nest the new current
760 if (theCurrent.get()) {
761 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
763 // if feature nests into compisite feature, make the composite feature as current
764 const std::set<AttributePtr>& aRefsToMe = theCurrent->data()->refsToMe();
765 std::set<AttributePtr>::const_iterator aRefToMe = aRefsToMe.begin();
766 for(; aRefToMe != aRefsToMe.end(); aRefToMe++) {
767 CompositeFeaturePtr aComposite =
768 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>((*aRefToMe)->owner());
769 if (aComposite.get() && aComposite->isSub(theCurrent)) {
777 if (theVisible) { // make features below which are not in history also enabled: sketch subs
779 theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
780 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
781 if (aNext->isInHistory()) {
782 break; // next in history is not needed
783 } else { // next not in history is good for making current
788 if (theCurrent.get()) {
789 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
790 if (!aData.get() || !aData->isValid()) {
791 aLoop->activateFlushes(isActive);
794 TDF_Label aFeatureLabel = aData->label().Father();
796 Handle(TDF_Reference) aRef;
797 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
798 aRef->Set(aFeatureLabel);
800 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
802 } else { // remove reference for the null feature
803 aRefLab.ForgetAttribute(TDF_Reference::GetID());
805 // make all features after this feature disabled in reversed order (to remove results without deps)
806 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
807 static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
808 static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
810 bool aPassed = false; // flag that the current object is already passed in cycle
811 FeaturePtr anIter = myObjs->lastFeature();
812 bool aWasChanged = false;
813 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
814 // check this before passed become enabled: the current feature is enabled!
815 if (anIter == theCurrent) aPassed = true;
817 bool aDisabledFlag = !aPassed;
818 if (aMain.get() && aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
819 aDisabledFlag = false;
820 if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
821 if (theCurrent.get() && theCurrent->getKind() != "Parameter")
822 aDisabledFlag = false;
824 if (anIter->setDisabled(aDisabledFlag)) {
825 // state of feature is changed => so feature become updated
826 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
827 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
828 // flush is in the end of this method
829 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
832 // update for everyone the concealment flag immideately: on edit feature in the midle of history
834 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = anIter->results();
835 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
836 for(; aRes != aResList.end(); aRes++) {
837 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
838 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
843 // unblock the flush signals and up them after this
844 aLoop->activateFlushes(isActive);
846 if (theFlushUpdates) {
847 aLoop->flush(aCreateEvent);
848 aLoop->flush(aRedispEvent);
849 aLoop->flush(aDeleteEvent);
853 void Model_Document::setCurrentFeatureUp()
855 // on remove just go up for minimum step: highlight external objects in sketch causes
856 // problems if it is true: here and in "setCurrentFeature"
857 FeaturePtr aCurrent = currentFeature(false);
858 if (aCurrent.get()) { // if not, do nothing because null is the upper
859 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
860 // do not flush: it is called only on remove, it will be flushed in the end of transaction
861 setCurrentFeature(aPrev, false, false);
865 TDF_Label Model_Document::generalLabel() const
867 return myDoc->Main().FindChild(TAG_GENERAL);
870 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
871 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
873 return myObjs->createConstruction(theFeatureData, theIndex);
876 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
877 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
879 return myObjs->createBody(theFeatureData, theIndex);
882 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
883 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
885 return myObjs->createPart(theFeatureData, theIndex);
888 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
889 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
890 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
892 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
895 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
896 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
898 return myObjs->createGroup(theFeatureData, theIndex);
901 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
902 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
904 return myObjs->createParameter(theFeatureData, theIndex);
907 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
908 const std::shared_ptr<ModelAPI_Result>& theResult)
910 return myObjs->feature(theResult);
913 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
915 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
918 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
920 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
923 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
925 myNamingNames[theName] = theLabel;
928 TDF_Label Model_Document::findNamingName(std::string theName)
930 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
931 if (aFind == myNamingNames.end())
932 return TDF_Label(); // not found
933 return aFind->second;
936 ResultPtr Model_Document::findByName(const std::string theName)
938 return myObjs->findByName(theName);
941 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
943 return myObjs->allFeatures();
946 void Model_Document::setActive(const bool theFlag)
948 if (theFlag != myIsActive) {
949 myIsActive = theFlag;
950 // redisplay all the objects of this part
951 static Events_Loop* aLoop = Events_Loop::loop();
952 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
954 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
955 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
956 object(ModelAPI_Feature::group(), a));
957 if (aFeature.get() && aFeature->data()->isValid()) {
958 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
959 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
960 for(; aRes != aResList.end(); aRes++) {
961 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
968 bool Model_Document::isActive() const
973 int Model_Document::transactionID()
975 Handle(TDataStd_Integer) anIndex;
976 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
977 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
978 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
980 return anIndex->Get();
983 void Model_Document::incrementTransactionID()
985 int aNewVal = transactionID() + 1;
986 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
988 void Model_Document::decrementTransactionID()
990 int aNewVal = transactionID() - 1;
991 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
994 bool Model_Document::isOpened()
996 return myObjs && !myDoc.IsNull();
999 int Model_Document::numInternalFeatures()
1001 return myObjs->numInternalFeatures();
1004 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
1006 return myObjs->internalFeature(theIndex);
1009 void Model_Document::synchronizeTransactions()
1011 Model_Document* aRoot =
1012 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
1014 return; // don't need to synchronise root with root
1016 std::shared_ptr<Model_Session> aSession =
1017 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
1018 while(myRedos.size() > aRoot->myRedos.size()) { // remove redos in this
1019 aSession->setCheckTransactions(false);
1021 aSession->setCheckTransactions(true);
1023 /* this case can not be reproduced in any known case for the current moment, so, just comment
1024 while(myRedos.size() < aRoot->myRedos.size()) { // add more redos in this
1025 undoInternal(false, true);
1029 /// Feature that is used for selection in the Part document by the external request
1030 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1032 /// Nothing to do in constructor
1033 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1035 /// Returns the unique kind of a feature
1036 virtual const std::string& getKind() {
1037 static std::string MY_KIND("InternalSelectionInPartFeature");
1040 /// Request for initialization of data model of the object: adding all attributes
1041 virtual void initAttributes() {
1042 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1044 /// Nothing to do in the execution function
1045 virtual void execute() {}
1049 //! Returns the feature that is used for calculation of selection externally from the document
1050 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1052 // return already created, otherwise create
1053 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1055 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1057 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1058 std::shared_ptr<Model_Data> aData(new Model_Data);
1059 aData->setLabel(aFeatureLab.FindChild(1));
1060 aData->setObject(mySelectionFeature);
1061 mySelectionFeature->setDoc(myObjs->owner());
1062 mySelectionFeature->setData(aData);
1063 std::string aName = id() + "_Part";
1064 mySelectionFeature->data()->setName(aName);
1065 mySelectionFeature->setDoc(myObjs->owner());
1066 mySelectionFeature->initAttributes();
1068 return mySelectionFeature->selectionList("selection");
1071 FeaturePtr Model_Document::lastFeature()
1074 return myObjs->lastFeature();
1075 return FeaturePtr();