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