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 // do it before flashes to enable and recompute nesting features correctly
345 if (myNestedNum.empty() || (isNestedClosed && myNestedNum.size() == 1)) {
346 // if all nested operations are closed, make current the higher level objects (to perform
347 // it in the python scripts correctly): sketch become current after creation ofsub-elements
348 FeaturePtr aCurrent = currentFeature(false);
349 CompositeFeaturePtr aMain, aNext = ModelAPI_Tools::compositeOwner(aCurrent);
352 aNext = ModelAPI_Tools::compositeOwner(aMain);
354 if (aMain.get() && aMain != aCurrent)
355 setCurrentFeature(aMain, false);
357 myObjs->synchronizeBackRefs();
358 Events_Loop* aLoop = Events_Loop::loop();
359 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
360 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
361 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
362 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
363 // this must be here just after everything is finished but before real transaction stop
364 // to avoid messages about modifications outside of the transaction
365 // and to rebuild everything after all updates and creates
366 if (isRoot()) { // once for root document
367 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
368 static std::shared_ptr<Events_Message> aFinishMsg
369 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
370 Events_Loop::loop()->send(aFinishMsg);
371 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
373 // to avoid "updated" message appearance by updater
374 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
376 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
377 bool aResult = false;
378 const std::set<std::string> aSubs = subDocuments(true);
379 std::set<std::string>::iterator aSubIter = aSubs.begin();
380 for (; aSubIter != aSubs.end(); aSubIter++)
381 if (subDoc(*aSubIter)->finishOperation())
384 // transaction may be empty if this document was created during this transaction (create part)
385 if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
386 myTransactions.rbegin()->myOCAFNum++;
390 if (isNestedClosed) {
393 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
394 aResult = myTransactions.rbegin()->myOCAFNum != 0;
396 if (!aResult && isRoot()) {
397 // nothing inside in all documents, so remove this transaction from the transactions list
398 undoInternal(true, false);
400 // on finish clear redos in any case (issue 446) and for all subs (issue 408)
403 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
404 subDoc(*aSubIter)->myDoc->ClearRedos();
405 subDoc(*aSubIter)->myRedos.clear();
411 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
412 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
413 const bool isRedo = false) {
414 Handle(TDF_Delta) aDelta;
416 aDelta = theDoc->GetRedos().First();
418 aDelta = theDoc->GetUndos().Last();
419 TDF_LabelList aDeltaList;
420 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
421 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
422 theDelta.Append(aListIter.Value());
424 // add also label of the modified attributes
425 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
426 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
427 theDelta.Append(anAttr.Value()->Label());
431 void Model_Document::abortOperation()
433 TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
434 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
436 // store undo-delta here as undo actually does in the method later
437 int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
438 for(a = 0; a < aNumTransactions; a++) {
439 modifiedLabels(myDoc, aDeltaLabels);
442 for(a = 0; a < aNumTransactions; a++) {
446 undoInternal(false, false);
449 } else { // abort the current
450 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
451 myTransactions.pop_back();
452 if (!myNestedNum.empty())
453 (*myNestedNum.rbegin())--;
454 // roll back the needed number of transactions
455 // make commit/undo to get the modification delta
456 //myDoc->AbortCommand();
457 if (myDoc->CommitCommand()) {
458 modifiedLabels(myDoc, aDeltaLabels);
461 for(int a = 0; a < aNumTransactions; a++) {
462 modifiedLabels(myDoc, aDeltaLabels);
467 // abort for all subs, flushes will be later, in the end of root abort
468 const std::set<std::string> aSubs = subDocuments(true);
469 std::set<std::string>::iterator aSubIter = aSubs.begin();
470 for (; aSubIter != aSubs.end(); aSubIter++)
471 subDoc(*aSubIter)->abortOperation();
472 // references may be changed because they are set in attributes on the fly
473 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
476 bool Model_Document::isOperation() const
478 // operation is opened for all documents: no need to check subs
479 return myDoc->HasOpenCommand() == Standard_True ;
482 bool Model_Document::isModified()
484 // is modified if at least one operation was commited and not undoed
485 return myTransactions.size() != myTransactionSave || isOperation();
488 bool Model_Document::canUndo()
490 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
491 int aCurrentNum = isOperation() ? 1 : 0;
492 if (myDoc->GetAvailableUndos() > 0 &&
493 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
494 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
496 // check other subs contains operation that can be undoed
497 const std::set<std::string> aSubs = subDocuments(true);
498 std::set<std::string>::iterator aSubIter = aSubs.begin();
499 for (; aSubIter != aSubs.end(); aSubIter++) {
500 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
501 if (aSub->myObjs) {// if it was not closed before
510 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
512 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
513 myRedos.push_back(*myTransactions.rbegin());
514 myTransactions.pop_back();
515 if (!myNestedNum.empty())
516 (*myNestedNum.rbegin())--;
517 // roll back the needed number of transactions
518 TDF_LabelList aDeltaLabels;
519 for(int a = 0; a < aNumTransactions; a++) {
521 modifiedLabels(myDoc, aDeltaLabels);
527 const std::set<std::string> aSubs = subDocuments(true);
528 std::set<std::string>::iterator aSubIter = aSubs.begin();
529 for (; aSubIter != aSubs.end(); aSubIter++) {
530 if (!subDoc(*aSubIter)->myObjs)
532 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
535 // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
536 if (theSynchronize) {
537 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
538 // update the current features status
539 setCurrentFeature(currentFeature(false), false);
543 void Model_Document::undo()
545 undoInternal(true, true);
548 bool Model_Document::canRedo()
550 if (!myRedos.empty())
552 // check other subs contains operation that can be redoed
553 const std::set<std::string> aSubs = subDocuments(true);
554 std::set<std::string>::iterator aSubIter = aSubs.begin();
555 for (; aSubIter != aSubs.end(); aSubIter++) {
556 if (!subDoc(*aSubIter)->myObjs)
558 if (subDoc(*aSubIter)->canRedo())
564 void Model_Document::redo()
566 if (!myNestedNum.empty())
567 (*myNestedNum.rbegin())++;
568 int aNumRedos = myRedos.rbegin()->myOCAFNum;
569 myTransactions.push_back(*myRedos.rbegin());
571 TDF_LabelList aDeltaLabels;
572 for(int a = 0; a < aNumRedos; a++) {
573 modifiedLabels(myDoc, aDeltaLabels, true);
578 const std::set<std::string> aSubs = subDocuments(true);
579 std::set<std::string>::iterator aSubIter = aSubs.begin();
580 for (; aSubIter != aSubs.end(); aSubIter++)
581 subDoc(*aSubIter)->redo();
583 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
584 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
585 // update the current features status
586 setCurrentFeature(currentFeature(false), false);
589 std::list<std::string> Model_Document::undoList() const
591 std::list<std::string> aResult;
592 // the number of skipped current operations (on undo they will be aborted)
593 int aSkipCurrent = isOperation() ? 1 : 0;
594 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
595 int aNumUndo = myTransactions.size();
596 if (!myNestedNum.empty())
597 aNumUndo = *myNestedNum.rbegin();
598 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
599 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
605 std::list<std::string> Model_Document::redoList() const
607 std::list<std::string> aResult;
608 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
609 for( ; aTrIter != myRedos.crend(); aTrIter++) {
610 aResult.push_back(aTrIter->myId);
615 void Model_Document::operationId(const std::string& theId)
617 myTransactions.rbegin()->myId = theId;
620 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
622 std::shared_ptr<Model_Session> aSession =
623 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
624 FeaturePtr aFeature = aSession->createFeature(theID, this);
628 Model_Document* aDocToAdd;
629 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
630 if (aFeature->documentToAdd() != kind()) { // the root document by default
631 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
635 } else { // if customized is not presented, add to "this" document
639 // searching for feature after which must be added the next feature: this is the current feature
640 // but also all sub-features of this feature
641 FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
642 bool isModified = true;
643 for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
644 aComp.get() && isModified;
645 aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
647 int aSubs = aComp->numberOfSubs(false);
648 for(int a = 0; a < aSubs; a++) {
649 FeaturePtr aSub = aComp->subFeature(a, false);
650 if (myObjs->isLater(aSub, aCurrent)) {
656 aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
657 if (!aFeature->isAction()) { // do not add action to the data model
658 if (theMakeCurrent) // after all this feature stays in the document, so make it current
659 aDocToAdd->setCurrentFeature(aFeature, false);
660 } else { // feature must be executed
661 // no creation event => updater not working, problem with remove part
669 void Model_Document::refsToFeature(FeaturePtr theFeature,
670 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
672 myObjs->refsToFeature(theFeature, theRefs, isSendError);
675 void Model_Document::removeFeature(FeaturePtr theFeature)
677 myObjs->removeFeature(theFeature);
680 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
682 myObjs->moveFeature(theMoved, theAfterThis);
683 if (theAfterThis == currentFeature(true))
684 setCurrentFeature(theMoved, true);
687 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
689 myObjs->updateHistory(theObject);
692 void Model_Document::updateHistory(const std::string theGroup)
694 myObjs->updateHistory(theGroup);
697 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
699 return Model_Application::getApplication()->getDocument(theDocID);
702 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
704 std::set<std::string> aResult;
705 std::list<ResultPtr> aPartResults;
706 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
707 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
708 for(; aPartRes != aPartResults.end(); aPartRes++) {
709 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
710 if (aPart && (!theActivatedOnly || aPart->isActivated())) {
711 aResult.insert(aPart->original()->data()->name());
717 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
719 // just store sub-document identifier here to manage it later
720 return std::dynamic_pointer_cast<Model_Document>(
721 Model_Application::getApplication()->getDocument(theDocID));
724 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
726 return myObjs->object(theGroupID, theIndex);
729 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
730 const std::string& theGroupID, const std::string& theName)
732 return myObjs->objectByName(theGroupID, theName);
735 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
737 return myObjs->index(theObject);
740 int Model_Document::size(const std::string& theGroupID)
742 return myObjs->size(theGroupID);
745 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
747 if (!myObjs) // on close document feature destruction it may call this method
748 return std::shared_ptr<ModelAPI_Feature>();
749 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
750 Handle(TDF_Reference) aRef;
751 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
752 TDF_Label aLab = aRef->Get();
753 FeaturePtr aResult = myObjs->feature(aLab);
754 if (theVisible) { // get nearest visible (in history) going up
755 while(aResult.get() && !aResult->isInHistory()) {
756 aResult = myObjs->nextFeature(aResult, true);
761 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
764 void Model_Document::setCurrentFeature(
765 std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theVisible)
767 // blocks the flush signals to avoid each objects visualization in the viewer
768 // they should not be shown once after all modifications are performed
769 Events_Loop* aLoop = Events_Loop::loop();
770 bool isActive = aLoop->activateFlushes(false);
772 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
773 CompositeFeaturePtr aMain; // main feature that may nest the new current
774 std::set<FeaturePtr> anOwners; // composites that contain theCurrent (with any level of nesting)
775 if (theCurrent.get()) {
776 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
777 CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theCurrent);
778 while(anOwner.get()) {
782 anOwners.insert(anOwner);
783 anOwner = ModelAPI_Tools::compositeOwner(anOwner);
787 if (theVisible) { // make features below which are not in history also enabled: sketch subs
789 theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
790 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
791 if (aNext->isInHistory()) {
792 break; // next in history is not needed
793 } else { // next not in history is good for making current
798 if (theCurrent.get()) {
799 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
800 if (!aData.get() || !aData->isValid()) {
801 aLoop->activateFlushes(isActive);
804 TDF_Label aFeatureLabel = aData->label().Father();
806 Handle(TDF_Reference) aRef;
807 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
808 aRef->Set(aFeatureLabel);
810 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
812 } else { // remove reference for the null feature
813 aRefLab.ForgetAttribute(TDF_Reference::GetID());
815 // make all features after this feature disabled in reversed order (to remove results without deps)
816 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
817 static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
818 static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
820 bool aPassed = false; // flag that the current object is already passed in cycle
821 FeaturePtr anIter = myObjs->lastFeature();
822 bool aWasChanged = false;
823 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
824 // check this before passed become enabled: the current feature is enabled!
825 if (anIter == theCurrent) aPassed = true;
827 bool aDisabledFlag = !aPassed;
829 if (aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
830 aDisabledFlag = false;
831 else if (anOwners.find(anIter) != anOwners.end()) // disable the higher-level feature is the nested is the current
832 aDisabledFlag = true;
835 if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
836 if (theCurrent.get() && theCurrent->getKind() != "Parameter")
837 aDisabledFlag = false;
839 if (anIter->setDisabled(aDisabledFlag)) {
840 // state of feature is changed => so feature become updated
841 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
842 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
843 // flush is in the end of this method
844 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
847 // update for everyone the concealment flag immideately: on edit feature in the midle of history
849 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = anIter->results();
850 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
851 for(; aRes != aResList.end(); aRes++) {
852 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
853 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
858 // unblock the flush signals and up them after this
859 aLoop->activateFlushes(isActive);
862 void Model_Document::setCurrentFeatureUp()
864 // on remove just go up for minimum step: highlight external objects in sketch causes
865 // problems if it is true: here and in "setCurrentFeature"
866 FeaturePtr aCurrent = currentFeature(false);
867 if (aCurrent.get()) { // if not, do nothing because null is the upper
868 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
869 // do not flush: it is called only on remove, it will be flushed in the end of transaction
870 setCurrentFeature(aPrev, false);
874 TDF_Label Model_Document::generalLabel() const
876 return myDoc->Main().FindChild(TAG_GENERAL);
879 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
880 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
882 return myObjs->createConstruction(theFeatureData, theIndex);
885 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
886 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
888 return myObjs->createBody(theFeatureData, theIndex);
891 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
892 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
894 return myObjs->createPart(theFeatureData, theIndex);
897 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
898 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
899 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
901 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
904 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
905 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
907 return myObjs->createGroup(theFeatureData, theIndex);
910 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
911 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
913 return myObjs->createParameter(theFeatureData, theIndex);
916 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
917 const std::shared_ptr<ModelAPI_Result>& theResult)
919 return myObjs->feature(theResult);
922 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
924 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
927 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
929 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
932 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
934 myNamingNames[theName] = theLabel;
937 TDF_Label Model_Document::findNamingName(std::string theName)
939 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
940 if (aFind == myNamingNames.end())
941 return TDF_Label(); // not found
942 return aFind->second;
945 ResultPtr Model_Document::findByName(const std::string theName)
947 return myObjs->findByName(theName);
950 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
952 return myObjs->allFeatures();
955 void Model_Document::setActive(const bool theFlag)
957 if (theFlag != myIsActive) {
958 myIsActive = theFlag;
959 // redisplay all the objects of this part
960 static Events_Loop* aLoop = Events_Loop::loop();
961 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
963 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
964 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
965 object(ModelAPI_Feature::group(), a));
966 if (aFeature.get() && aFeature->data()->isValid()) {
967 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
968 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
969 for(; aRes != aResList.end(); aRes++) {
970 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
977 bool Model_Document::isActive() const
982 int Model_Document::transactionID()
984 Handle(TDataStd_Integer) anIndex;
985 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
986 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
987 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
989 return anIndex->Get();
992 void Model_Document::incrementTransactionID()
994 int aNewVal = transactionID() + 1;
995 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
997 void Model_Document::decrementTransactionID()
999 int aNewVal = transactionID() - 1;
1000 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1003 bool Model_Document::isOpened()
1005 return myObjs && !myDoc.IsNull();
1008 int Model_Document::numInternalFeatures()
1010 return myObjs->numInternalFeatures();
1013 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
1015 return myObjs->internalFeature(theIndex);
1018 void Model_Document::synchronizeTransactions()
1020 Model_Document* aRoot =
1021 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
1023 return; // don't need to synchronise root with root
1025 std::shared_ptr<Model_Session> aSession =
1026 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
1027 while(myRedos.size() > aRoot->myRedos.size()) { // remove redos in this
1028 aSession->setCheckTransactions(false);
1030 aSession->setCheckTransactions(true);
1032 /* this case can not be reproduced in any known case for the current moment, so, just comment
1033 while(myRedos.size() < aRoot->myRedos.size()) { // add more redos in this
1034 undoInternal(false, true);
1038 /// Feature that is used for selection in the Part document by the external request
1039 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1041 /// Nothing to do in constructor
1042 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1044 /// Returns the unique kind of a feature
1045 virtual const std::string& getKind() {
1046 static std::string MY_KIND("InternalSelectionInPartFeature");
1049 /// Request for initialization of data model of the object: adding all attributes
1050 virtual void initAttributes() {
1051 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1053 /// Nothing to do in the execution function
1054 virtual void execute() {}
1058 //! Returns the feature that is used for calculation of selection externally from the document
1059 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1061 // return already created, otherwise create
1062 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1064 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1066 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1067 std::shared_ptr<Model_Data> aData(new Model_Data);
1068 aData->setLabel(aFeatureLab.FindChild(1));
1069 aData->setObject(mySelectionFeature);
1070 mySelectionFeature->setDoc(myObjs->owner());
1071 mySelectionFeature->setData(aData);
1072 std::string aName = id() + "_Part";
1073 mySelectionFeature->data()->setName(aName);
1074 mySelectionFeature->setDoc(myObjs->owner());
1075 mySelectionFeature->initAttributes();
1077 return mySelectionFeature->selectionList("selection");
1080 FeaturePtr Model_Document::lastFeature()
1083 return myObjs->lastFeature();
1084 return FeaturePtr();