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"));
171 std::shared_ptr<Model_Session> aSession =
172 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
175 myDoc->SetUndoLimit(UNDO_LIMIT);
176 // to avoid the problem that feature is created in the current, not this, document
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);
189 } else { // open failed, but new documnet was created to work with it: inform the model
190 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
195 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
197 // create a directory in the root document if it is not yet exist
198 Handle(Model_Application) anApp = Model_Application::getApplication();
201 CreateDirectory(theFileName, NULL);
203 mkdir(theFileName, 0x1ff);
206 // filename in the dir is id of document inside of the given directory
207 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
208 PCDM_StoreStatus aStatus;
210 aStatus = anApp->SaveAs(myDoc, aPath);
211 } catch (Standard_Failure) {
212 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
214 std::string("Exception in saving of document: ") + aFail->GetMessageString());
217 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
220 case PCDM_SS_DriverFailure:
221 Events_Error::send(std::string("Can not save document: save driver-library failure"));
223 case PCDM_SS_WriteFailure:
224 Events_Error::send(std::string("Can not save document: file writing failure"));
226 case PCDM_SS_Failure:
228 Events_Error::send(std::string("Can not save document"));
232 myTransactionSave = myTransactions.size();
233 if (isDone) { // save also sub-documents if any
234 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
235 const std::set<std::string> aSubs = subDocuments(false);
236 std::set<std::string>::iterator aSubIter = aSubs.begin();
237 for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
238 if (anApp->isLoadByDemand(*aSubIter)) {
239 // copy not-activated document that is not in the memory
240 std::string aDocName = *aSubIter;
241 if (!aDocName.empty()) {
243 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
244 OSD_Path aPath(aSubPath);
245 OSD_File aFile(aPath);
246 if (aFile.Exists()) {
247 TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
248 OSD_Path aDestination(aDestinationDir);
249 aFile.Copy(aDestination);
250 theResults.push_back(aDestinationDir.ToCString());
253 std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
256 } else { // simply save opened document
257 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
264 void Model_Document::close(const bool theForever)
266 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
267 if (!isRoot() && this == aPM->activeDocument().get()) {
268 aPM->setActiveDocument(aPM->moduleDocument());
269 } else if (isRoot()) {
270 // erase the active document if root is closed
271 aPM->setActiveDocument(DocumentPtr());
274 const std::set<std::string> aSubs = subDocuments(true);
275 std::set<std::string>::iterator aSubIter = aSubs.begin();
276 for (; aSubIter != aSubs.end(); aSubIter++) {
277 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
278 if (aSub->myObjs) // if it was not closed before
279 aSub->close(theForever);
282 // close for thid document needs no transaction in this document
283 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
285 // close all only if it is really asked, otherwise it can be undoed/redoed
287 // flush everything to avoid messages with bad objects
290 if (myDoc->CanClose() == CDM_CCS_OK)
292 mySelectionFeature.reset();
294 setCurrentFeature(FeaturePtr(), false); // disables all features
297 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
300 void Model_Document::startOperation()
302 if (myDoc->HasOpenCommand()) { // start of nested command
303 if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
304 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
306 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
307 myDoc->OpenCommand();
308 } else { // start the simple command
311 // starts a new operation
312 incrementTransactionID();
313 myTransactions.push_back(Transaction());
314 if (!myNestedNum.empty())
315 (*myNestedNum.rbegin())++;
317 // new command for all subs
318 const std::set<std::string> aSubs = subDocuments(true);
319 std::set<std::string>::iterator aSubIter = aSubs.begin();
320 for (; aSubIter != aSubs.end(); aSubIter++)
321 subDoc(*aSubIter)->startOperation();
324 void Model_Document::compactNested()
326 if (!myNestedNum.empty()) {
327 int aNumToCompact = *(myNestedNum.rbegin());
328 int aSumOfTransaction = 0;
329 for(int a = 0; a < aNumToCompact; a++) {
330 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
331 myTransactions.pop_back();
333 // the latest transaction is the start of lower-level operation which startes the nested
334 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
335 myNestedNum.pop_back();
339 bool Model_Document::finishOperation()
341 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
342 static std::shared_ptr<Model_Session> aSession =
343 std::static_pointer_cast<Model_Session>(Model_Session::get());
344 myObjs->synchronizeBackRefs();
345 Events_Loop* aLoop = Events_Loop::loop();
346 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
347 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
348 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
349 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
350 // this must be here just after everything is finished but before real transaction stop
351 // to avoid messages about modifications outside of the transaction
352 // and to rebuild everything after all updates and creates
353 if (isRoot()) { // once for root document
354 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
355 static std::shared_ptr<Events_Message> aFinishMsg
356 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
357 Events_Loop::loop()->send(aFinishMsg);
358 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
360 // to avoid "updated" message appearance by updater
361 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
363 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
364 bool aResult = false;
365 const std::set<std::string> aSubs = subDocuments(true);
366 std::set<std::string>::iterator aSubIter = aSubs.begin();
367 for (; aSubIter != aSubs.end(); aSubIter++)
368 if (subDoc(*aSubIter)->finishOperation())
371 // transaction may be empty if this document was created during this transaction (create part)
372 if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
373 myTransactions.rbegin()->myOCAFNum++;
377 if (isNestedClosed) {
380 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
381 aResult = myTransactions.rbegin()->myOCAFNum != 0;
383 if (!aResult && isRoot()) {
384 // nothing inside in all documents, so remove this transaction from the transactions list
385 undoInternal(true, false);
387 // on finish clear redos in any case (issue 446) and for all subs (issue 408)
390 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
391 subDoc(*aSubIter)->myDoc->ClearRedos();
392 subDoc(*aSubIter)->myRedos.clear();
398 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
399 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
400 const bool isRedo = false) {
401 Handle(TDF_Delta) aDelta;
403 aDelta = theDoc->GetRedos().First();
405 aDelta = theDoc->GetUndos().Last();
406 TDF_LabelList aDeltaList;
407 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
408 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
409 theDelta.Append(aListIter.Value());
411 // add also label of the modified attributes
412 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
413 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
414 theDelta.Append(anAttr.Value()->Label());
418 void Model_Document::abortOperation()
420 TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
421 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
423 // store undo-delta here as undo actually does in the method later
424 int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
425 for(a = 0; a < aNumTransactions; a++) {
426 modifiedLabels(myDoc, aDeltaLabels);
429 for(a = 0; a < aNumTransactions; a++) {
433 undoInternal(false, false);
436 } else { // abort the current
437 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
438 myTransactions.pop_back();
439 if (!myNestedNum.empty())
440 (*myNestedNum.rbegin())--;
441 // roll back the needed number of transactions
442 // make commit/undo to get the modification delta
443 //myDoc->AbortCommand();
444 if (myDoc->CommitCommand()) {
445 modifiedLabels(myDoc, aDeltaLabels);
448 for(int a = 0; a < aNumTransactions; a++) {
449 modifiedLabels(myDoc, aDeltaLabels);
454 // abort for all subs, flushes will be later, in the end of root abort
455 const std::set<std::string> aSubs = subDocuments(true);
456 std::set<std::string>::iterator aSubIter = aSubs.begin();
457 for (; aSubIter != aSubs.end(); aSubIter++)
458 subDoc(*aSubIter)->abortOperation();
459 // references may be changed because they are set in attributes on the fly
460 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
463 bool Model_Document::isOperation() const
465 // operation is opened for all documents: no need to check subs
466 return myDoc->HasOpenCommand() == Standard_True ;
469 bool Model_Document::isModified()
471 // is modified if at least one operation was commited and not undoed
472 return myTransactions.size() != myTransactionSave || isOperation();
475 bool Model_Document::canUndo()
477 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
478 int aCurrentNum = isOperation() ? 1 : 0;
479 if (myDoc->GetAvailableUndos() > 0 &&
480 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
481 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
483 // check other subs contains operation that can be undoed
484 const std::set<std::string> aSubs = subDocuments(true);
485 std::set<std::string>::iterator aSubIter = aSubs.begin();
486 for (; aSubIter != aSubs.end(); aSubIter++) {
487 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
488 if (aSub->myObjs) {// if it was not closed before
497 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
499 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
500 myRedos.push_back(*myTransactions.rbegin());
501 myTransactions.pop_back();
502 if (!myNestedNum.empty())
503 (*myNestedNum.rbegin())--;
504 // roll back the needed number of transactions
505 TDF_LabelList aDeltaLabels;
506 for(int a = 0; a < aNumTransactions; a++) {
508 modifiedLabels(myDoc, aDeltaLabels);
514 const std::set<std::string> aSubs = subDocuments(true);
515 std::set<std::string>::iterator aSubIter = aSubs.begin();
516 for (; aSubIter != aSubs.end(); aSubIter++) {
517 if (!subDoc(*aSubIter)->myObjs)
519 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
522 // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
523 if (theSynchronize) {
524 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
525 // update the current features status
526 setCurrentFeature(currentFeature(false), false);
530 void Model_Document::undo()
532 undoInternal(true, true);
535 bool Model_Document::canRedo()
537 if (!myRedos.empty())
539 // check other subs contains operation that can be redoed
540 const std::set<std::string> aSubs = subDocuments(true);
541 std::set<std::string>::iterator aSubIter = aSubs.begin();
542 for (; aSubIter != aSubs.end(); aSubIter++) {
543 if (!subDoc(*aSubIter)->myObjs)
545 if (subDoc(*aSubIter)->canRedo())
551 void Model_Document::redo()
553 if (!myNestedNum.empty())
554 (*myNestedNum.rbegin())++;
555 int aNumRedos = myRedos.rbegin()->myOCAFNum;
556 myTransactions.push_back(*myRedos.rbegin());
558 TDF_LabelList aDeltaLabels;
559 for(int a = 0; a < aNumRedos; a++) {
560 modifiedLabels(myDoc, aDeltaLabels, true);
565 const std::set<std::string> aSubs = subDocuments(true);
566 std::set<std::string>::iterator aSubIter = aSubs.begin();
567 for (; aSubIter != aSubs.end(); aSubIter++)
568 subDoc(*aSubIter)->redo();
570 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
571 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
572 // update the current features status
573 setCurrentFeature(currentFeature(false), false);
576 std::list<std::string> Model_Document::undoList() const
578 std::list<std::string> aResult;
579 // the number of skipped current operations (on undo they will be aborted)
580 int aSkipCurrent = isOperation() ? 1 : 0;
581 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
582 int aNumUndo = myTransactions.size();
583 if (!myNestedNum.empty())
584 aNumUndo = *myNestedNum.rbegin();
585 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
586 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
592 std::list<std::string> Model_Document::redoList() const
594 std::list<std::string> aResult;
595 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
596 for( ; aTrIter != myRedos.crend(); aTrIter++) {
597 aResult.push_back(aTrIter->myId);
602 void Model_Document::operationId(const std::string& theId)
604 myTransactions.rbegin()->myId = theId;
607 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
609 std::shared_ptr<Model_Session> aSession =
610 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
611 FeaturePtr aFeature = aSession->createFeature(theID, this);
615 Model_Document* aDocToAdd;
616 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
617 if (aFeature->documentToAdd() != kind()) { // the root document by default
618 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
622 } else { // if customized is not presented, add to "this" document
626 // searching for feature after which must be added the next feature: this is the current feature
627 // but also all sub-features of this feature
628 FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
629 bool isModified = true;
630 for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
631 aComp.get() && isModified;
632 aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
634 int aSubs = aComp->numberOfSubs(false);
635 for(int a = 0; a < aSubs; a++) {
636 FeaturePtr aSub = aComp->subFeature(a, false);
637 if (myObjs->isLater(aSub, aCurrent)) {
643 aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
644 if (!aFeature->isAction()) { // do not add action to the data model
645 if (theMakeCurrent) // after all this feature stays in the document, so make it current
646 aDocToAdd->setCurrentFeature(aFeature, false);
647 } else { // feature must be executed
648 // no creation event => updater not working, problem with remove part
656 void Model_Document::refsToFeature(FeaturePtr theFeature,
657 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
659 myObjs->refsToFeature(theFeature, theRefs, isSendError);
662 void Model_Document::removeFeature(FeaturePtr theFeature)
664 myObjs->removeFeature(theFeature);
667 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
669 myObjs->moveFeature(theMoved, theAfterThis);
670 if (theAfterThis == currentFeature(true))
671 setCurrentFeature(theMoved, true);
674 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
676 myObjs->updateHistory(theObject);
679 void Model_Document::updateHistory(const std::string theGroup)
681 myObjs->updateHistory(theGroup);
684 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
686 return Model_Application::getApplication()->getDocument(theDocID);
689 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
691 std::set<std::string> aResult;
692 std::list<ResultPtr> aPartResults;
693 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
694 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
695 for(; aPartRes != aPartResults.end(); aPartRes++) {
696 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
697 if (aPart && (!theActivatedOnly || aPart->isActivated())) {
698 aResult.insert(aPart->original()->data()->name());
704 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
706 // just store sub-document identifier here to manage it later
707 return std::dynamic_pointer_cast<Model_Document>(
708 Model_Application::getApplication()->getDocument(theDocID));
711 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
713 return myObjs->object(theGroupID, theIndex);
716 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
717 const std::string& theGroupID, const std::string& theName)
719 return myObjs->objectByName(theGroupID, theName);
722 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
724 return myObjs->index(theObject);
727 int Model_Document::size(const std::string& theGroupID)
729 return myObjs->size(theGroupID);
732 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
734 if (!myObjs) // on close document feature destruction it may call this method
735 return std::shared_ptr<ModelAPI_Feature>();
736 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
737 Handle(TDF_Reference) aRef;
738 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
739 TDF_Label aLab = aRef->Get();
740 FeaturePtr aResult = myObjs->feature(aLab);
741 if (theVisible) { // get nearest visible (in history) going up
742 while(aResult.get() && // sub-composites are never in history
743 (!aResult->isInHistory() || ModelAPI_Tools::compositeOwner(aResult).get())) {
744 aResult = myObjs->nextFeature(aResult, true);
749 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
752 void Model_Document::setCurrentFeature(
753 std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theVisible)
755 // blocks the flush signals to avoid each objects visualization in the viewer
756 // they should not be shown once after all modifications are performed
757 Events_Loop* aLoop = Events_Loop::loop();
758 bool isActive = aLoop->activateFlushes(false);
760 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
761 CompositeFeaturePtr aMain; // main feature that may nest the new current
762 if (theCurrent.get()) {
763 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
765 // if feature nests into compisite feature, make the composite feature as current
766 const std::set<AttributePtr>& aRefsToMe = theCurrent->data()->refsToMe();
767 std::set<AttributePtr>::const_iterator aRefToMe = aRefsToMe.begin();
768 for(; aRefToMe != aRefsToMe.end(); aRefToMe++) {
769 CompositeFeaturePtr aComposite =
770 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>((*aRefToMe)->owner());
771 if (aComposite.get() && aComposite->isSub(theCurrent)) {
779 if (theVisible) { // make features below which are not in history also enabled: sketch subs
781 theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
782 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
783 if (aNext->isInHistory()) {
784 break; // next in history is not needed
785 } else { // next not in history is good for making current
790 if (theCurrent.get()) {
791 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
792 if (!aData.get() || !aData->isValid()) {
793 aLoop->activateFlushes(isActive);
796 TDF_Label aFeatureLabel = aData->label().Father();
798 Handle(TDF_Reference) aRef;
799 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
800 aRef->Set(aFeatureLabel);
802 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
804 } else { // remove reference for the null feature
805 aRefLab.ForgetAttribute(TDF_Reference::GetID());
807 // make all features after this feature disabled in reversed order (to remove results without deps)
808 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
809 static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
810 static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
812 bool aPassed = false; // flag that the current object is already passed in cycle
813 FeaturePtr anIter = myObjs->lastFeature();
814 bool aWasChanged = false;
815 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
816 // check this before passed become enabled: the current feature is enabled!
817 if (anIter == theCurrent) aPassed = true;
819 bool aDisabledFlag = !aPassed;
820 if (aMain.get() && aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
821 aDisabledFlag = false;
822 if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
823 if (theCurrent.get() && theCurrent->getKind() != "Parameter")
824 aDisabledFlag = false;
826 if (anIter->setDisabled(aDisabledFlag)) {
827 // state of feature is changed => so feature become updated
828 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
829 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
830 // flush is in the end of this method
831 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
834 // update for everyone the concealment flag immideately: on edit feature in the midle of history
836 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = anIter->results();
837 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
838 for(; aRes != aResList.end(); aRes++) {
839 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
840 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
845 // unblock the flush signals and up them after this
846 aLoop->activateFlushes(isActive);
849 void Model_Document::setCurrentFeatureUp()
851 // on remove just go up for minimum step: highlight external objects in sketch causes
852 // problems if it is true: here and in "setCurrentFeature"
853 FeaturePtr aCurrent = currentFeature(false);
854 if (aCurrent.get()) { // if not, do nothing because null is the upper
855 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
856 // do not flush: it is called only on remove, it will be flushed in the end of transaction
857 setCurrentFeature(aPrev, false);
861 TDF_Label Model_Document::generalLabel() const
863 return myDoc->Main().FindChild(TAG_GENERAL);
866 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
867 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
869 return myObjs->createConstruction(theFeatureData, theIndex);
872 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
873 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
875 return myObjs->createBody(theFeatureData, theIndex);
878 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
879 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
881 return myObjs->createPart(theFeatureData, theIndex);
884 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
885 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
886 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
888 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
891 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
892 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
894 return myObjs->createGroup(theFeatureData, theIndex);
897 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
898 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
900 return myObjs->createParameter(theFeatureData, theIndex);
903 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
904 const std::shared_ptr<ModelAPI_Result>& theResult)
906 return myObjs->feature(theResult);
909 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
911 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
914 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
916 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
919 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
921 myNamingNames[theName] = theLabel;
924 TDF_Label Model_Document::findNamingName(std::string theName)
926 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
927 if (aFind == myNamingNames.end())
928 return TDF_Label(); // not found
929 return aFind->second;
932 ResultPtr Model_Document::findByName(const std::string theName)
934 return myObjs->findByName(theName);
937 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
939 return myObjs->allFeatures();
942 void Model_Document::setActive(const bool theFlag)
944 if (theFlag != myIsActive) {
945 myIsActive = theFlag;
946 // redisplay all the objects of this part
947 static Events_Loop* aLoop = Events_Loop::loop();
948 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
950 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
951 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
952 object(ModelAPI_Feature::group(), a));
953 if (aFeature.get() && aFeature->data()->isValid()) {
954 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
955 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
956 for(; aRes != aResList.end(); aRes++) {
957 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
964 bool Model_Document::isActive() const
969 int Model_Document::transactionID()
971 Handle(TDataStd_Integer) anIndex;
972 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
973 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
974 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
976 return anIndex->Get();
979 void Model_Document::incrementTransactionID()
981 int aNewVal = transactionID() + 1;
982 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
984 void Model_Document::decrementTransactionID()
986 int aNewVal = transactionID() - 1;
987 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
990 bool Model_Document::isOpened()
992 return myObjs && !myDoc.IsNull();
995 int Model_Document::numInternalFeatures()
997 return myObjs->numInternalFeatures();
1000 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
1002 return myObjs->internalFeature(theIndex);
1005 void Model_Document::synchronizeTransactions()
1007 Model_Document* aRoot =
1008 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
1010 return; // don't need to synchronise root with root
1012 std::shared_ptr<Model_Session> aSession =
1013 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
1014 while(myRedos.size() > aRoot->myRedos.size()) { // remove redos in this
1015 aSession->setCheckTransactions(false);
1017 aSession->setCheckTransactions(true);
1019 /* this case can not be reproduced in any known case for the current moment, so, just comment
1020 while(myRedos.size() < aRoot->myRedos.size()) { // add more redos in this
1021 undoInternal(false, true);
1025 /// Feature that is used for selection in the Part document by the external request
1026 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1028 /// Nothing to do in constructor
1029 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1031 /// Returns the unique kind of a feature
1032 virtual const std::string& getKind() {
1033 static std::string MY_KIND("InternalSelectionInPartFeature");
1036 /// Request for initialization of data model of the object: adding all attributes
1037 virtual void initAttributes() {
1038 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1040 /// Nothing to do in the execution function
1041 virtual void execute() {}
1045 //! Returns the feature that is used for calculation of selection externally from the document
1046 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1048 // return already created, otherwise create
1049 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1051 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1053 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1054 std::shared_ptr<Model_Data> aData(new Model_Data);
1055 aData->setLabel(aFeatureLab.FindChild(1));
1056 aData->setObject(mySelectionFeature);
1057 mySelectionFeature->setDoc(myObjs->owner());
1058 mySelectionFeature->setData(aData);
1059 std::string aName = id() + "_Part";
1060 mySelectionFeature->data()->setName(aName);
1061 mySelectionFeature->setDoc(myObjs->owner());
1062 mySelectionFeature->initAttributes();
1064 return mySelectionFeature->selectionList("selection");
1067 FeaturePtr Model_Document::lastFeature()
1070 return myObjs->lastFeature();
1071 return FeaturePtr();