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>
44 # define _separator_ '\\'
46 # define _separator_ '/'
49 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
51 static const int TAG_GENERAL = 1; // general properties tag
54 static const int TAG_CURRENT_FEATURE = 1; ///< where the reference to the current feature label is located (or no attribute if null feature)
55 static const int TAG_CURRENT_TRANSACTION = 2; ///< integer, index of the cransaction
56 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
58 Model_Document::Model_Document(const std::string theID, const std::string theKind)
59 : myID(theID), myKind(theKind), myIsActive(false),
60 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
62 myObjs = new Model_Objects(myDoc->Main());
63 myDoc->SetUndoLimit(UNDO_LIMIT);
64 myTransactionSave = 0;
65 myExecuteFeatures = true;
66 // to have something in the document and avoid empty doc open/save problem
67 // in transaction for nesting correct working
69 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
70 myDoc->CommitCommand();
73 void Model_Document::setThis(DocumentPtr theDoc)
75 myObjs->setOwner(theDoc);
78 /// Returns the file name of this document by the nameof directory and identifuer of a document
79 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
81 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
82 // remove end-separators
83 while(aPath.Length() &&
84 (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
85 aPath.Remove(aPath.Length());
87 aPath += theID.c_str();
88 aPath += ".cbf"; // standard binary file extension
92 bool Model_Document::isRoot() const
94 return this == Model_Session::get()->moduleDocument().get();
97 bool Model_Document::load(const char* theFileName, DocumentPtr theThis)
99 Handle(Model_Application) anApp = Model_Application::getApplication();
101 anApp->setLoadPath(theFileName);
103 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
104 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
106 aStatus = anApp->Open(aPath, myDoc);
107 } catch (Standard_Failure) {
108 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
110 std::string("Exception in opening of document: ") + aFail->GetMessageString());
113 bool isError = aStatus != PCDM_RS_OK;
116 case PCDM_RS_UnknownDocument:
117 Events_Error::send(std::string("Can not open document"));
119 case PCDM_RS_AlreadyRetrieved:
120 Events_Error::send(std::string("Can not open document: already opened"));
122 case PCDM_RS_AlreadyRetrievedAndModified:
124 std::string("Can not open document: already opened and modified"));
126 case PCDM_RS_NoDriver:
127 Events_Error::send(std::string("Can not open document: driver library is not found"));
129 case PCDM_RS_UnknownFileDriver:
130 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
132 case PCDM_RS_OpenError:
133 Events_Error::send(std::string("Can not open document: file open error"));
135 case PCDM_RS_NoVersion:
136 Events_Error::send(std::string("Can not open document: invalid version"));
138 case PCDM_RS_NoModel:
139 Events_Error::send(std::string("Can not open document: no data model"));
141 case PCDM_RS_NoDocument:
142 Events_Error::send(std::string("Can not open document: no document inside"));
144 case PCDM_RS_FormatFailure:
145 Events_Error::send(std::string("Can not open document: format failure"));
147 case PCDM_RS_TypeNotFoundInSchema:
148 Events_Error::send(std::string("Can not open document: invalid object"));
150 case PCDM_RS_UnrecognizedFileFormat:
151 Events_Error::send(std::string("Can not open document: unrecognized file format"));
153 case PCDM_RS_MakeFailure:
154 Events_Error::send(std::string("Can not open document: make failure"));
156 case PCDM_RS_PermissionDenied:
157 Events_Error::send(std::string("Can not open document: permission denied"));
159 case PCDM_RS_DriverFailure:
160 Events_Error::send(std::string("Can not open document: driver failure"));
163 Events_Error::send(std::string("Can not open document: unknown error"));
168 myDoc->SetUndoLimit(UNDO_LIMIT);
169 // to avoid the problem that feature is created in the current, not this, document
170 std::shared_ptr<Model_Session> aSession =
171 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
172 aSession->setActiveDocument(anApp->getDocument(myID), false);
173 aSession->setCheckTransactions(false);
176 myObjs = new Model_Objects(myDoc->Main()); // synchronisation is inside
177 myObjs->setOwner(theThis);
178 // update the current features status
179 setCurrentFeature(currentFeature(false), false);
180 aSession->setCheckTransactions(true);
181 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
182 // this is done in Part result "activate", so no needed here. Causes not-blue active part.
183 // aSession->setActiveDocument(anApp->getDocument(myID), true);
188 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
190 // create a directory in the root document if it is not yet exist
191 Handle(Model_Application) anApp = Model_Application::getApplication();
194 CreateDirectory(theFileName, NULL);
196 mkdir(theFileName, 0x1ff);
199 // filename in the dir is id of document inside of the given directory
200 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
201 PCDM_StoreStatus aStatus;
203 aStatus = anApp->SaveAs(myDoc, aPath);
204 } catch (Standard_Failure) {
205 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
207 std::string("Exception in saving of document: ") + aFail->GetMessageString());
210 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
213 case PCDM_SS_DriverFailure:
214 Events_Error::send(std::string("Can not save document: save driver-library failure"));
216 case PCDM_SS_WriteFailure:
217 Events_Error::send(std::string("Can not save document: file writing failure"));
219 case PCDM_SS_Failure:
221 Events_Error::send(std::string("Can not save document"));
225 myTransactionSave = myTransactions.size();
226 if (isDone) { // save also sub-documents if any
227 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
228 const std::set<std::string> aSubs = subDocuments(false);
229 std::set<std::string>::iterator aSubIter = aSubs.begin();
230 for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
231 if (anApp->isLoadByDemand(*aSubIter)) {
232 // copy not-activated document that is not in the memory
233 std::string aDocName = *aSubIter;
234 if (!aDocName.empty()) {
236 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
237 OSD_Path aPath(aSubPath);
238 OSD_File aFile(aPath);
239 if (aFile.Exists()) {
240 TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
241 OSD_Path aDestination(aDestinationDir);
242 aFile.Copy(aDestination);
243 theResults.push_back(aDestinationDir.ToCString());
246 std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
249 } else { // simply save opened document
250 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
257 void Model_Document::close(const bool theForever)
259 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
260 if (!isRoot() && this == aPM->activeDocument().get()) {
261 aPM->setActiveDocument(aPM->moduleDocument());
262 } else if (isRoot()) {
263 // erase the active document if root is closed
264 aPM->setActiveDocument(DocumentPtr());
267 const std::set<std::string> aSubs = subDocuments(true);
268 std::set<std::string>::iterator aSubIter = aSubs.begin();
269 for (; aSubIter != aSubs.end(); aSubIter++) {
270 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
271 if (aSub->myObjs) // if it was not closed before
272 aSub->close(theForever);
275 // close for thid document needs no transaction in this document
276 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
278 // close all only if it is really asked, otherwise it can be undoed/redoed
282 if (myDoc->CanClose() == CDM_CCS_OK)
284 mySelectionFeature.reset();
286 setCurrentFeature(FeaturePtr(), false); // disables all features
289 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
292 void Model_Document::startOperation()
294 if (myDoc->HasOpenCommand()) { // start of nested command
295 if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
296 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
298 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
299 myDoc->OpenCommand();
300 } else { // start the simple command
303 // starts a new operation
304 incrementTransactionID();
305 myTransactions.push_back(Transaction());
306 if (!myNestedNum.empty())
307 (*myNestedNum.rbegin())++;
309 // new command for all subs
310 const std::set<std::string> aSubs = subDocuments(true);
311 std::set<std::string>::iterator aSubIter = aSubs.begin();
312 for (; aSubIter != aSubs.end(); aSubIter++)
313 subDoc(*aSubIter)->startOperation();
316 void Model_Document::compactNested()
318 if (!myNestedNum.empty()) {
319 int aNumToCompact = *(myNestedNum.rbegin());
320 int aSumOfTransaction = 0;
321 for(int a = 0; a < aNumToCompact; a++) {
322 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
323 myTransactions.pop_back();
325 // the latest transaction is the start of lower-level operation which startes the nested
326 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
327 myNestedNum.pop_back();
331 bool Model_Document::finishOperation()
333 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
334 static std::shared_ptr<Model_Session> aSession =
335 std::static_pointer_cast<Model_Session>(Model_Session::get());
336 myObjs->synchronizeBackRefs();
337 Events_Loop* aLoop = Events_Loop::loop();
338 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
339 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
340 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
341 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
342 // this must be here just after everything is finished but before real transaction stop
343 // to avoid messages about modifications outside of the transaction
344 // and to rebuild everything after all updates and creates
345 if (isRoot()) { // once for root document
346 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
347 static std::shared_ptr<Events_Message> aFinishMsg
348 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
349 Events_Loop::loop()->send(aFinishMsg);
350 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
352 // to avoid "updated" message appearance by updater
353 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
355 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
356 bool aResult = false;
357 const std::set<std::string> aSubs = subDocuments(true);
358 std::set<std::string>::iterator aSubIter = aSubs.begin();
359 for (; aSubIter != aSubs.end(); aSubIter++)
360 if (subDoc(*aSubIter)->finishOperation())
363 // transaction may be empty if this document was created during this transaction (create part)
364 if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
365 myTransactions.rbegin()->myOCAFNum++;
369 if (isNestedClosed) {
372 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
373 aResult = myTransactions.rbegin()->myOCAFNum != 0;
375 if (!aResult && isRoot()) {
376 // nothing inside in all documents, so remove this transaction from the transactions list
377 undoInternal(true, false);
379 // on finish clear redos in any case (issue 446) and for all subs (issue 408)
382 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
383 subDoc(*aSubIter)->myDoc->ClearRedos();
384 subDoc(*aSubIter)->myRedos.clear();
390 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
391 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
392 const bool isRedo = false) {
393 Handle(TDF_Delta) aDelta;
395 aDelta = theDoc->GetRedos().First();
397 aDelta = theDoc->GetUndos().Last();
398 aDelta->Labels(theDelta);
399 // add also label of the modified attributes
400 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
401 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
402 theDelta.Append(anAttr.Value()->Label());
406 void Model_Document::abortOperation()
408 TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
409 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
411 // store undo-delta here as undo actually does in the method later
412 int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
413 for(a = 0; a < aNumTransactions; a++) {
414 modifiedLabels(myDoc, aDeltaLabels);
417 for(a = 0; a < aNumTransactions; a++) {
421 undoInternal(false, false);
424 } else { // abort the current
425 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
426 myTransactions.pop_back();
427 if (!myNestedNum.empty())
428 (*myNestedNum.rbegin())--;
429 // roll back the needed number of transactions
430 myDoc->AbortCommand();
431 for(int a = 0; a < aNumTransactions; a++) {
432 modifiedLabels(myDoc, aDeltaLabels);
437 // abort for all subs, flushes will be later, in the end of root abort
438 const std::set<std::string> aSubs = subDocuments(true);
439 std::set<std::string>::iterator aSubIter = aSubs.begin();
440 for (; aSubIter != aSubs.end(); aSubIter++)
441 subDoc(*aSubIter)->abortOperation();
442 // references may be changed because they are set in attributes on the fly
443 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
446 bool Model_Document::isOperation() const
448 // operation is opened for all documents: no need to check subs
449 return myDoc->HasOpenCommand() == Standard_True ;
452 bool Model_Document::isModified()
454 // is modified if at least one operation was commited and not undoed
455 return myTransactions.size() != myTransactionSave || isOperation();
458 bool Model_Document::canUndo()
460 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
461 int aCurrentNum = isOperation() ? 1 : 0;
462 if (myDoc->GetAvailableUndos() > 0 &&
463 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
464 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
466 // check other subs contains operation that can be undoed
467 const std::set<std::string> aSubs = subDocuments(true);
468 std::set<std::string>::iterator aSubIter = aSubs.begin();
469 for (; aSubIter != aSubs.end(); aSubIter++) {
470 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
471 if (aSub->myObjs) {// if it was not closed before
480 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
482 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
483 myRedos.push_back(*myTransactions.rbegin());
484 myTransactions.pop_back();
485 if (!myNestedNum.empty())
486 (*myNestedNum.rbegin())--;
487 // roll back the needed number of transactions
488 TDF_LabelList aDeltaLabels;
489 for(int a = 0; a < aNumTransactions; a++) {
491 modifiedLabels(myDoc, aDeltaLabels);
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 if (!subDoc(*aSubIter)->myObjs)
502 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
505 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
506 if (theSynchronize) {
507 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
508 // update the current features status
509 setCurrentFeature(currentFeature(false), false);
513 void Model_Document::undo()
515 undoInternal(true, true);
518 bool Model_Document::canRedo()
520 if (!myRedos.empty())
522 // check other subs contains operation that can be redoed
523 const std::set<std::string> aSubs = subDocuments(true);
524 std::set<std::string>::iterator aSubIter = aSubs.begin();
525 for (; aSubIter != aSubs.end(); aSubIter++) {
526 if (!subDoc(*aSubIter)->myObjs)
528 if (subDoc(*aSubIter)->canRedo())
534 void Model_Document::redo()
536 if (!myNestedNum.empty())
537 (*myNestedNum.rbegin())++;
538 int aNumRedos = myRedos.rbegin()->myOCAFNum;
539 myTransactions.push_back(*myRedos.rbegin());
541 TDF_LabelList aDeltaLabels;
542 for(int a = 0; a < aNumRedos; a++) {
543 modifiedLabels(myDoc, aDeltaLabels, true);
548 const std::set<std::string> aSubs = subDocuments(true);
549 std::set<std::string>::iterator aSubIter = aSubs.begin();
550 for (; aSubIter != aSubs.end(); aSubIter++)
551 subDoc(*aSubIter)->redo();
553 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
554 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
555 // update the current features status
556 setCurrentFeature(currentFeature(false), false);
559 std::list<std::string> Model_Document::undoList() const
561 std::list<std::string> aResult;
562 // the number of skipped current operations (on undo they will be aborted)
563 int aSkipCurrent = isOperation() ? 1 : 0;
564 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
565 int aNumUndo = myTransactions.size();
566 if (!myNestedNum.empty())
567 aNumUndo = *myNestedNum.rbegin();
568 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
569 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
575 std::list<std::string> Model_Document::redoList() const
577 std::list<std::string> aResult;
578 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
579 for( ; aTrIter != myRedos.crend(); aTrIter++) {
580 aResult.push_back(aTrIter->myId);
585 void Model_Document::operationId(const std::string& theId)
587 myTransactions.rbegin()->myId = theId;
590 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
592 std::shared_ptr<Model_Session> aSession =
593 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
594 FeaturePtr aFeature = aSession->createFeature(theID, this);
597 Model_Document* aDocToAdd;
598 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
599 if (aFeature->documentToAdd() != kind()) { // the root document by default
600 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
604 } else { // if customized is not presented, add to "this" document
608 aDocToAdd->myObjs->addFeature(aFeature, aDocToAdd->currentFeature(false));
609 if (!aFeature->isAction()) { // do not add action to the data model
610 if (theMakeCurrent) // after all this feature stays in the document, so make it current
611 aDocToAdd->setCurrentFeature(aFeature, false);
612 } else { // feature must be executed
613 // no creation event => updater not working, problem with remove part
621 void Model_Document::refsToFeature(FeaturePtr theFeature,
622 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
624 myObjs->refsToFeature(theFeature, theRefs, isSendError);
627 void Model_Document::removeFeature(FeaturePtr theFeature)
629 myObjs->removeFeature(theFeature);
632 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
634 myObjs->moveFeature(theMoved, theAfterThis);
637 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
639 myObjs->updateHistory(theObject);
642 void Model_Document::updateHistory(const std::string theGroup)
644 myObjs->updateHistory(theGroup);
647 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
649 return Model_Application::getApplication()->getDocument(theDocID);
652 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
654 std::set<std::string> aResult;
655 std::list<ResultPtr> aPartResults;
656 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
657 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
658 for(; aPartRes != aPartResults.end(); aPartRes++) {
659 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
660 if (aPart && (!theActivatedOnly || aPart->isActivated())) {
661 aResult.insert(aPart->original()->data()->name());
667 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
669 // just store sub-document identifier here to manage it later
670 return std::dynamic_pointer_cast<Model_Document>(
671 Model_Application::getApplication()->getDocument(theDocID));
674 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
676 return myObjs->object(theGroupID, theIndex);
679 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
680 const std::string& theGroupID, const std::string& theName)
682 return myObjs->objectByName(theGroupID, theName);
685 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
687 return myObjs->index(theObject);
690 int Model_Document::size(const std::string& theGroupID)
692 return myObjs->size(theGroupID);
695 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
697 if (!myObjs) // on close document feature destruction it may call this method
698 return std::shared_ptr<ModelAPI_Feature>();
699 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
700 Handle(TDF_Reference) aRef;
701 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
702 TDF_Label aLab = aRef->Get();
703 FeaturePtr aResult = myObjs->feature(aLab);
704 if (theVisible) { // get nearest visible (in history) going up
705 while(aResult.get() && // sub-composites are never in history
706 (!aResult->isInHistory() || ModelAPI_Tools::compositeOwner(aResult).get())) {
707 aResult = myObjs->nextFeature(aResult, true);
712 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
715 void Model_Document::setCurrentFeature(std::shared_ptr<ModelAPI_Feature> theCurrent,
716 const bool theVisible)
718 // blocks the flush signals to avoid each objects visualization in the viewer
719 // they should not be shown once after all modifications are performed
720 Events_Loop* aLoop = Events_Loop::loop();
721 bool isActive = aLoop->activateFlushes(false);
723 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
724 CompositeFeaturePtr aMain; // main feature that may nest the new current
725 if (theCurrent.get()) {
726 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
728 // if feature nests into compisite feature, make the composite feature as current
729 const std::set<AttributePtr>& aRefsToMe = theCurrent->data()->refsToMe();
730 std::set<AttributePtr>::const_iterator aRefToMe = aRefsToMe.begin();
731 for(; aRefToMe != aRefsToMe.end(); aRefToMe++) {
732 CompositeFeaturePtr aComposite =
733 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>((*aRefToMe)->owner());
734 if (aComposite.get() && aComposite->isSub(theCurrent)) {
742 if (theVisible) { // make features below which are not in history also enabled: sketch subs
744 theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
745 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
746 if (aNext->isInHistory()) {
747 break; // next in history is not needed
748 } else { // next not in history is good for making current
753 if (theCurrent.get()) {
754 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
755 if (!aData.get() || !aData->isValid()) {
756 aLoop->activateFlushes(isActive);
759 TDF_Label aFeatureLabel = aData->label().Father();
761 Handle(TDF_Reference) aRef;
762 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
763 aRef->Set(aFeatureLabel);
765 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
767 } else { // remove reference for the null feature
768 aRefLab.ForgetAttribute(TDF_Reference::GetID());
770 // make all features after this feature disabled in reversed order (to remove results without deps)
771 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
772 static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
773 static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
775 bool aPassed = false; // flag that the current object is already passed in cycle
776 FeaturePtr anIter = myObjs->lastFeature();
777 bool aWasChanged = false;
778 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
779 // check this before passed become enabled: the current feature is enabled!
780 if (anIter == theCurrent) aPassed = true;
782 bool aDisabledFlag = !aPassed;
783 if (aMain.get() && aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
784 aDisabledFlag = false;
785 if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
786 if (theCurrent.get() && theCurrent->getKind() != "Parameter")
787 aDisabledFlag = false;
789 if (anIter->setDisabled(aDisabledFlag)) {
790 // state of feature is changed => so feature become updated
791 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
792 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
793 // flush is in the end of this method
794 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
797 // update for everyone the concealment flag immideately: on edit feature in the midle of history
799 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = anIter->results();
800 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
801 for(; aRes != aResList.end(); aRes++) {
802 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
803 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
808 // unblock the flush signals and up them after this
809 aLoop->activateFlushes(isActive);
811 aLoop->flush(aCreateEvent);
812 aLoop->flush(aRedispEvent);
813 aLoop->flush(aDeleteEvent);
816 void Model_Document::setCurrentFeatureUp()
818 // on remove just go up for minimum step: highlight external objects in sketch causes
819 // problems if it is true: here and in "setCurrentFeature"
820 FeaturePtr aCurrent = currentFeature(false);
821 if (aCurrent.get()) { // if not, do nothing because null is the upper
822 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
823 setCurrentFeature(aPrev, false);
827 TDF_Label Model_Document::generalLabel() const
829 return myDoc->Main().FindChild(TAG_GENERAL);
832 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
833 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
835 return myObjs->createConstruction(theFeatureData, theIndex);
838 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
839 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
841 return myObjs->createBody(theFeatureData, theIndex);
844 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
845 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
847 return myObjs->createPart(theFeatureData, theIndex);
850 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
851 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
852 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
854 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
857 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
858 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
860 return myObjs->createGroup(theFeatureData, theIndex);
863 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
864 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
866 return myObjs->createParameter(theFeatureData, theIndex);
869 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
870 const std::shared_ptr<ModelAPI_Result>& theResult)
872 return myObjs->feature(theResult);
875 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
877 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
880 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
882 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
885 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
887 myNamingNames[theName] = theLabel;
890 TDF_Label Model_Document::findNamingName(std::string theName)
892 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
893 if (aFind == myNamingNames.end())
894 return TDF_Label(); // not found
895 return aFind->second;
898 ResultPtr Model_Document::findByName(const std::string theName)
900 return myObjs->findByName(theName);
903 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
905 return myObjs->allFeatures();
908 void Model_Document::setActive(const bool theFlag)
910 if (theFlag != myIsActive) {
911 myIsActive = theFlag;
912 // redisplay all the objects of this part
913 static Events_Loop* aLoop = Events_Loop::loop();
914 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
916 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
917 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
918 object(ModelAPI_Feature::group(), a));
919 if (aFeature.get() && aFeature->data()->isValid()) {
920 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
921 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
922 for(; aRes != aResList.end(); aRes++) {
923 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
930 bool Model_Document::isActive() const
935 int Model_Document::transactionID()
937 Handle(TDataStd_Integer) anIndex;
938 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
939 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
940 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
942 return anIndex->Get();
945 void Model_Document::incrementTransactionID()
947 int aNewVal = transactionID() + 1;
948 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
950 void Model_Document::decrementTransactionID()
952 int aNewVal = transactionID() - 1;
953 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
956 bool Model_Document::isOpened()
958 return myObjs && !myDoc.IsNull();
961 int Model_Document::numInternalFeatures()
963 return myObjs->numInternalFeatures();
966 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
968 return myObjs->internalFeature(theIndex);
971 // Feature that is used for selection in the Part document by the external request
972 class Model_SelectionInPartFeature : public ModelAPI_Feature {
974 /// Nothing to do in constructor
975 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
977 /// Returns the unique kind of a feature
978 virtual const std::string& getKind() {
979 static std::string MY_KIND("InternalSelectionInPartFeature");
982 /// Request for initialization of data model of the object: adding all attributes
983 virtual void initAttributes() {
984 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
986 /// Nothing to do in the execution function
987 virtual void execute() {}
991 //! Returns the feature that is used for calculation of selection externally from the document
992 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
994 // return already created, otherwise create
995 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
997 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
999 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1000 std::shared_ptr<Model_Data> aData(new Model_Data);
1001 aData->setLabel(aFeatureLab.FindChild(1));
1002 aData->setObject(mySelectionFeature);
1003 mySelectionFeature->setDoc(myObjs->owner());
1004 mySelectionFeature->setData(aData);
1005 std::string aName = id() + "_Part";
1006 mySelectionFeature->data()->setName(aName);
1007 mySelectionFeature->setDoc(myObjs->owner());
1008 mySelectionFeature->initAttributes();
1010 return mySelectionFeature->selectionList("selection");
1013 FeaturePtr Model_Document::lastFeature()
1016 return myObjs->lastFeature();
1017 return FeaturePtr();