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 <OSD_File.hxx>
32 #include <OSD_Path.hxx>
40 # define _separator_ '\\'
42 # define _separator_ '/'
45 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
47 static const int TAG_GENERAL = 1; // general properties tag
50 static const int TAG_CURRENT_FEATURE = 1; ///< where the reference to the current feature label is located (or no attribute if null feature)
51 static const int TAG_CURRENT_TRANSACTION = 2; ///< integer, index of the cransaction
52 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
54 Model_Document::Model_Document(const std::string theID, const std::string theKind)
55 : myID(theID), myKind(theKind), myIsActive(false),
56 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
58 myObjs = new Model_Objects(myDoc->Main());
59 myDoc->SetUndoLimit(UNDO_LIMIT);
60 myTransactionSave = 0;
61 myExecuteFeatures = true;
62 // to have something in the document and avoid empty doc open/save problem
63 // in transaction for nesting correct working
65 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
66 myDoc->CommitCommand();
69 void Model_Document::setThis(DocumentPtr theDoc)
71 myObjs->setOwner(theDoc);
74 /// Returns the file name of this document by the nameof directory and identifuer of a document
75 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
77 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
78 // remove end-separators
79 while(aPath.Length() &&
80 (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
81 aPath.Remove(aPath.Length());
83 aPath += theID.c_str();
84 aPath += ".cbf"; // standard binary file extension
88 bool Model_Document::isRoot() const
90 return this == Model_Session::get()->moduleDocument().get();
93 bool Model_Document::load(const char* theFileName, DocumentPtr theThis)
95 Handle(Model_Application) anApp = Model_Application::getApplication();
97 anApp->setLoadPath(theFileName);
99 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
100 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
102 aStatus = anApp->Open(aPath, myDoc);
103 } catch (Standard_Failure) {
104 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
106 std::string("Exception in opening of document: ") + aFail->GetMessageString());
109 bool isError = aStatus != PCDM_RS_OK;
112 case PCDM_RS_UnknownDocument:
113 Events_Error::send(std::string("Can not open document"));
115 case PCDM_RS_AlreadyRetrieved:
116 Events_Error::send(std::string("Can not open document: already opened"));
118 case PCDM_RS_AlreadyRetrievedAndModified:
120 std::string("Can not open document: already opened and modified"));
122 case PCDM_RS_NoDriver:
123 Events_Error::send(std::string("Can not open document: driver library is not found"));
125 case PCDM_RS_UnknownFileDriver:
126 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
128 case PCDM_RS_OpenError:
129 Events_Error::send(std::string("Can not open document: file open error"));
131 case PCDM_RS_NoVersion:
132 Events_Error::send(std::string("Can not open document: invalid version"));
134 case PCDM_RS_NoModel:
135 Events_Error::send(std::string("Can not open document: no data model"));
137 case PCDM_RS_NoDocument:
138 Events_Error::send(std::string("Can not open document: no document inside"));
140 case PCDM_RS_FormatFailure:
141 Events_Error::send(std::string("Can not open document: format failure"));
143 case PCDM_RS_TypeNotFoundInSchema:
144 Events_Error::send(std::string("Can not open document: invalid object"));
146 case PCDM_RS_UnrecognizedFileFormat:
147 Events_Error::send(std::string("Can not open document: unrecognized file format"));
149 case PCDM_RS_MakeFailure:
150 Events_Error::send(std::string("Can not open document: make failure"));
152 case PCDM_RS_PermissionDenied:
153 Events_Error::send(std::string("Can not open document: permission denied"));
155 case PCDM_RS_DriverFailure:
156 Events_Error::send(std::string("Can not open document: driver failure"));
159 Events_Error::send(std::string("Can not open document: unknown error"));
164 myDoc->SetUndoLimit(UNDO_LIMIT);
165 // to avoid the problem that feature is created in the current, not this, document
166 std::shared_ptr<Model_Session> aSession =
167 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
168 aSession->setActiveDocument(anApp->getDocument(myID), false);
169 aSession->setCheckTransactions(false);
172 myObjs = new Model_Objects(myDoc->Main()); // synchronisation is inside
173 myObjs->setOwner(theThis);
174 // update the current features status
175 setCurrentFeature(currentFeature(false), false);
176 aSession->setCheckTransactions(true);
177 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
178 // this is done in Part result "activate", so no needed here. Causes not-blue active part.
179 // aSession->setActiveDocument(anApp->getDocument(myID), true);
184 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
186 // create a directory in the root document if it is not yet exist
187 Handle(Model_Application) anApp = Model_Application::getApplication();
190 CreateDirectory(theFileName, NULL);
192 mkdir(theFileName, 0x1ff);
195 // filename in the dir is id of document inside of the given directory
196 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
197 PCDM_StoreStatus aStatus;
199 aStatus = anApp->SaveAs(myDoc, aPath);
200 } catch (Standard_Failure) {
201 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
203 std::string("Exception in saving of document: ") + aFail->GetMessageString());
206 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
209 case PCDM_SS_DriverFailure:
210 Events_Error::send(std::string("Can not save document: save driver-library failure"));
212 case PCDM_SS_WriteFailure:
213 Events_Error::send(std::string("Can not save document: file writing failure"));
215 case PCDM_SS_Failure:
217 Events_Error::send(std::string("Can not save document"));
221 myTransactionSave = myTransactions.size();
222 if (isDone) { // save also sub-documents if any
223 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
224 const std::set<std::string> aSubs = subDocuments(false);
225 std::set<std::string>::iterator aSubIter = aSubs.begin();
226 for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
227 if (anApp->isLoadByDemand(*aSubIter)) {
228 // copy not-activated document that is not in the memory
229 std::string aDocName = *aSubIter;
230 if (!aDocName.empty()) {
232 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
233 OSD_Path aPath(aSubPath);
234 OSD_File aFile(aPath);
235 if (aFile.Exists()) {
236 TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
237 OSD_Path aDestination(aDestinationDir);
238 aFile.Copy(aDestination);
239 theResults.push_back(aDestinationDir.ToCString());
242 std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
245 } else { // simply save opened document
246 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
253 void Model_Document::close(const bool theForever)
255 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
256 if (!isRoot() && this == aPM->activeDocument().get()) {
257 aPM->setActiveDocument(aPM->moduleDocument());
258 } else if (isRoot()) {
259 // erase the active document if root is closed
260 aPM->setActiveDocument(DocumentPtr());
263 const std::set<std::string> aSubs = subDocuments(true);
264 std::set<std::string>::iterator aSubIter = aSubs.begin();
265 for (; aSubIter != aSubs.end(); aSubIter++) {
266 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
267 if (aSub->myObjs) // if it was not closed before
268 aSub->close(theForever);
271 // close for thid document needs no transaction in this document
272 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
274 // close all only if it is really asked, otherwise it can be undoed/redoed
278 if (myDoc->CanClose() == CDM_CCS_OK)
280 mySelectionFeature.reset();
282 setCurrentFeature(FeaturePtr(), false); // disables all features
285 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
288 void Model_Document::startOperation()
290 if (myDoc->HasOpenCommand()) { // start of nested command
291 if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
292 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
294 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
295 myDoc->OpenCommand();
296 } else { // start the simple command
299 // starts a new operation
300 incrementTransactionID();
301 myTransactions.push_back(Transaction());
302 if (!myNestedNum.empty())
303 (*myNestedNum.rbegin())++;
305 // new command for all subs
306 const std::set<std::string> aSubs = subDocuments(true);
307 std::set<std::string>::iterator aSubIter = aSubs.begin();
308 for (; aSubIter != aSubs.end(); aSubIter++)
309 subDoc(*aSubIter)->startOperation();
312 void Model_Document::compactNested()
314 if (!myNestedNum.empty()) {
315 int aNumToCompact = *(myNestedNum.rbegin());
316 int aSumOfTransaction = 0;
317 for(int a = 0; a < aNumToCompact; a++) {
318 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
319 myTransactions.pop_back();
321 // the latest transaction is the start of lower-level operation which startes the nested
322 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
323 myNestedNum.pop_back();
327 bool Model_Document::finishOperation()
329 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
330 static std::shared_ptr<Model_Session> aSession =
331 std::static_pointer_cast<Model_Session>(Model_Session::get());
332 myObjs->synchronizeBackRefs();
333 Events_Loop* aLoop = Events_Loop::loop();
334 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
335 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
336 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
337 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
338 // this must be here just after everything is finished but before real transaction stop
339 // to avoid messages about modifications outside of the transaction
340 // and to rebuild everything after all updates and creates
341 if (isRoot()) { // once for root document
342 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
343 static std::shared_ptr<Events_Message> aFinishMsg
344 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
345 Events_Loop::loop()->send(aFinishMsg);
346 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
348 // to avoid "updated" message appearance by updater
349 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
351 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
352 bool aResult = false;
353 const std::set<std::string> aSubs = subDocuments(true);
354 std::set<std::string>::iterator aSubIter = aSubs.begin();
355 for (; aSubIter != aSubs.end(); aSubIter++)
356 if (subDoc(*aSubIter)->finishOperation())
359 // transaction may be empty if this document was created during this transaction (create part)
360 if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
361 myTransactions.rbegin()->myOCAFNum++;
365 if (isNestedClosed) {
368 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
369 aResult = myTransactions.rbegin()->myOCAFNum != 0;
371 if (!aResult && isRoot()) {
372 // nothing inside in all documents, so remove this transaction from the transactions list
373 undoInternal(true, false);
375 // on finish clear redos in any case (issue 446) and for all subs (issue 408)
378 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
379 subDoc(*aSubIter)->myDoc->ClearRedos();
380 subDoc(*aSubIter)->myRedos.clear();
386 void Model_Document::abortOperation()
388 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
390 undoInternal(false, false);
393 } else { // abort the current
394 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
395 myTransactions.pop_back();
396 if (!myNestedNum.empty())
397 (*myNestedNum.rbegin())--;
398 // roll back the needed number of transactions
399 myDoc->AbortCommand();
400 for(int a = 0; a < aNumTransactions; a++)
404 // abort for all subs, flushes will be later, in the end of root abort
405 const std::set<std::string> aSubs = subDocuments(true);
406 std::set<std::string>::iterator aSubIter = aSubs.begin();
407 for (; aSubIter != aSubs.end(); aSubIter++)
408 subDoc(*aSubIter)->abortOperation();
409 // references may be changed because they are set in attributes on the fly
410 myObjs->synchronizeFeatures(true, true, isRoot());
413 bool Model_Document::isOperation() const
415 // operation is opened for all documents: no need to check subs
416 return myDoc->HasOpenCommand() == Standard_True ;
419 bool Model_Document::isModified()
421 // is modified if at least one operation was commited and not undoed
422 return myTransactions.size() != myTransactionSave || isOperation();
425 bool Model_Document::canUndo()
427 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
428 int aCurrentNum = isOperation() ? 1 : 0;
429 if (myDoc->GetAvailableUndos() > 0 &&
430 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
431 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
433 // check other subs contains operation that can be undoed
434 const std::set<std::string> aSubs = subDocuments(true);
435 std::set<std::string>::iterator aSubIter = aSubs.begin();
436 for (; aSubIter != aSubs.end(); aSubIter++) {
437 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
438 if (aSub->myObjs) {// if it was not closed before
447 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
449 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
450 myRedos.push_back(*myTransactions.rbegin());
451 myTransactions.pop_back();
452 if (!myNestedNum.empty())
453 (*myNestedNum.rbegin())--;
454 // roll back the needed number of transactions
455 for(int a = 0; a < aNumTransactions; a++)
460 const std::set<std::string> aSubs = subDocuments(true);
461 std::set<std::string>::iterator aSubIter = aSubs.begin();
462 for (; aSubIter != aSubs.end(); aSubIter++) {
463 if (!subDoc(*aSubIter)->myObjs)
465 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
468 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
469 if (theSynchronize) {
470 myObjs->synchronizeFeatures(true, true, isRoot());
471 // update the current features status
472 setCurrentFeature(currentFeature(false), false);
476 void Model_Document::undo()
478 undoInternal(true, true);
481 bool Model_Document::canRedo()
483 if (!myRedos.empty())
485 // check other subs contains operation that can be redoed
486 const std::set<std::string> aSubs = subDocuments(true);
487 std::set<std::string>::iterator aSubIter = aSubs.begin();
488 for (; aSubIter != aSubs.end(); aSubIter++) {
489 if (!subDoc(*aSubIter)->myObjs)
491 if (subDoc(*aSubIter)->canRedo())
497 void Model_Document::redo()
499 if (!myNestedNum.empty())
500 (*myNestedNum.rbegin())++;
501 int aNumRedos = myRedos.rbegin()->myOCAFNum;
502 myTransactions.push_back(*myRedos.rbegin());
504 for(int a = 0; a < aNumRedos; a++)
508 const std::set<std::string> aSubs = subDocuments(true);
509 std::set<std::string>::iterator aSubIter = aSubs.begin();
510 for (; aSubIter != aSubs.end(); aSubIter++)
511 subDoc(*aSubIter)->redo();
513 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
514 myObjs->synchronizeFeatures(true, true, isRoot());
515 // update the current features status
516 setCurrentFeature(currentFeature(false), false);
519 std::list<std::string> Model_Document::undoList() const
521 std::list<std::string> aResult;
522 // the number of skipped current operations (on undo they will be aborted)
523 int aSkipCurrent = isOperation() ? 1 : 0;
524 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
525 int aNumUndo = myTransactions.size();
526 if (!myNestedNum.empty())
527 aNumUndo = *myNestedNum.rbegin();
528 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
529 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
535 std::list<std::string> Model_Document::redoList() const
537 std::list<std::string> aResult;
538 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
539 for( ; aTrIter != myRedos.crend(); aTrIter++) {
540 aResult.push_back(aTrIter->myId);
545 void Model_Document::operationId(const std::string& theId)
547 myTransactions.rbegin()->myId = theId;
550 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
552 std::shared_ptr<Model_Session> aSession =
553 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
554 FeaturePtr aFeature = aSession->createFeature(theID, this);
557 Model_Document* aDocToAdd;
558 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
559 if (aFeature->documentToAdd() != kind()) { // the root document by default
560 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
564 } else { // if customized is not presented, add to "this" document
568 aDocToAdd->myObjs->addFeature(aFeature, aDocToAdd->currentFeature(false));
569 if (!aFeature->isAction()) { // do not add action to the data model
570 if (theMakeCurrent) // after all this feature stays in the document, so make it current
571 aDocToAdd->setCurrentFeature(aFeature, false);
572 } else { // feature must be executed
573 // no creation event => updater not working, problem with remove part
581 void Model_Document::refsToFeature(FeaturePtr theFeature,
582 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
584 myObjs->refsToFeature(theFeature, theRefs, isSendError);
587 void Model_Document::removeFeature(FeaturePtr theFeature)
589 myObjs->removeFeature(theFeature);
592 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
594 myObjs->moveFeature(theMoved, theAfterThis);
597 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
599 myObjs->updateHistory(theObject);
602 void Model_Document::updateHistory(const std::string theGroup)
604 myObjs->updateHistory(theGroup);
607 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
609 return Model_Application::getApplication()->getDocument(theDocID);
612 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
614 std::set<std::string> aResult;
615 std::list<ResultPtr> aPartResults;
616 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
617 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
618 for(; aPartRes != aPartResults.end(); aPartRes++) {
619 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
620 if (aPart && (!theActivatedOnly || aPart->isActivated())) {
621 aResult.insert(aPart->original()->data()->name());
627 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
629 // just store sub-document identifier here to manage it later
630 return std::dynamic_pointer_cast<Model_Document>(
631 Model_Application::getApplication()->getDocument(theDocID));
634 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
636 return myObjs->object(theGroupID, theIndex);
639 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
640 const std::string& theGroupID, const std::string& theName)
642 return myObjs->objectByName(theGroupID, theName);
645 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
647 return myObjs->index(theObject);
650 int Model_Document::size(const std::string& theGroupID)
652 return myObjs->size(theGroupID);
655 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
657 if (!myObjs) // on close document feature destruction it may call this method
658 return std::shared_ptr<ModelAPI_Feature>();
659 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
660 Handle(TDF_Reference) aRef;
661 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
662 TDF_Label aLab = aRef->Get();
663 FeaturePtr aResult = myObjs->feature(aLab);
664 if (theVisible) { // get nearest visible (in history) going up
665 while(aResult.get() && // sub-composites are never in history
666 (!aResult->isInHistory() || ModelAPI_Tools::compositeOwner(aResult).get())) {
667 aResult = myObjs->nextFeature(aResult, true);
672 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
675 void Model_Document::setCurrentFeature(std::shared_ptr<ModelAPI_Feature> theCurrent,
676 const bool theVisible)
678 // blocks the flush signals to avoid each objects visualization in the viewer
679 // they should not be shown once after all modifications are performed
680 Events_Loop* aLoop = Events_Loop::loop();
681 bool isActive = aLoop->activateFlushes(false);
683 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
684 CompositeFeaturePtr aMain; // main feature that may nest the new current
685 if (theCurrent.get()) {
686 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
688 // if feature nests into compisite feature, make the composite feature as current
689 const std::set<AttributePtr>& aRefsToMe = theCurrent->data()->refsToMe();
690 std::set<AttributePtr>::const_iterator aRefToMe = aRefsToMe.begin();
691 for(; aRefToMe != aRefsToMe.end(); aRefToMe++) {
692 CompositeFeaturePtr aComposite =
693 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>((*aRefToMe)->owner());
694 if (aComposite.get() && aComposite->isSub(theCurrent)) {
702 if (theVisible) { // make features below which are not in history also enabled: sketch subs
704 theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
705 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
706 if (aNext->isInHistory()) {
707 break; // next in history is not needed
708 } else { // next not in history is good for making current
713 if (theCurrent.get()) {
714 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
715 if (!aData.get() || !aData->isValid()) {
716 aLoop->activateFlushes(isActive);
719 TDF_Label aFeatureLabel = aData->label().Father();
721 Handle(TDF_Reference) aRef;
722 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
723 aRef->Set(aFeatureLabel);
725 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
727 } else { // remove reference for the null feature
728 aRefLab.ForgetAttribute(TDF_Reference::GetID());
730 // make all features after this feature disabled in reversed order (to remove results without deps)
731 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
732 static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
733 static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
735 bool aPassed = false; // flag that the current object is already passed in cycle
736 FeaturePtr anIter = myObjs->lastFeature();
737 bool aWasChanged = false;
738 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
739 // check this before passed become enabled: the current feature is enabled!
740 if (anIter == theCurrent) aPassed = true;
742 bool aDisabledFlag = !aPassed;
743 if (aMain.get() && aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
744 aDisabledFlag = false;
745 if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
746 if (theCurrent.get() && theCurrent->getKind() != "Parameter")
747 aDisabledFlag = false;
749 if (anIter->setDisabled(aDisabledFlag)) {
750 // state of feature is changed => so feature become updated
751 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
752 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
753 // flush is in the end of this method
754 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
757 // update for everyone the concealment flag immideately: on edit feature in the midle of history
759 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = anIter->results();
760 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
761 for(; aRes != aResList.end(); aRes++) {
762 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
763 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
768 // unblock the flush signals and up them after this
769 aLoop->activateFlushes(isActive);
771 aLoop->flush(aCreateEvent);
772 aLoop->flush(aRedispEvent);
773 aLoop->flush(aDeleteEvent);
776 void Model_Document::setCurrentFeatureUp()
778 // on remove just go up for minimum step: highlight external objects in sketch causes
779 // problems if it is true: here and in "setCurrentFeature"
780 FeaturePtr aCurrent = currentFeature(false);
781 if (aCurrent.get()) { // if not, do nothing because null is the upper
782 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
783 setCurrentFeature(aPrev, false);
787 TDF_Label Model_Document::generalLabel() const
789 return myDoc->Main().FindChild(TAG_GENERAL);
792 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
793 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
795 return myObjs->createConstruction(theFeatureData, theIndex);
798 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
799 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
801 return myObjs->createBody(theFeatureData, theIndex);
804 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
805 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
807 return myObjs->createPart(theFeatureData, theIndex);
810 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
811 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
812 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
814 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
817 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
818 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
820 return myObjs->createGroup(theFeatureData, theIndex);
823 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
824 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
826 return myObjs->createParameter(theFeatureData, theIndex);
829 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
830 const std::shared_ptr<ModelAPI_Result>& theResult)
832 return myObjs->feature(theResult);
835 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
837 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
840 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
842 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
845 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
847 myNamingNames[theName] = theLabel;
850 TDF_Label Model_Document::findNamingName(std::string theName)
852 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
853 if (aFind == myNamingNames.end())
854 return TDF_Label(); // not found
855 return aFind->second;
858 ResultPtr Model_Document::findByName(const std::string theName)
860 return myObjs->findByName(theName);
863 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
865 return myObjs->allFeatures();
868 void Model_Document::setActive(const bool theFlag)
870 if (theFlag != myIsActive) {
871 myIsActive = theFlag;
872 // redisplay all the objects of this part
873 static Events_Loop* aLoop = Events_Loop::loop();
874 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
876 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
877 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
878 object(ModelAPI_Feature::group(), a));
879 if (aFeature.get() && aFeature->data()->isValid()) {
880 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
881 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
882 for(; aRes != aResList.end(); aRes++) {
883 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
890 bool Model_Document::isActive() const
895 int Model_Document::transactionID()
897 Handle(TDataStd_Integer) anIndex;
898 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
899 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
900 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
902 return anIndex->Get();
905 void Model_Document::incrementTransactionID()
907 int aNewVal = transactionID() + 1;
908 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
910 void Model_Document::decrementTransactionID()
912 int aNewVal = transactionID() - 1;
913 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
916 bool Model_Document::isOpened()
918 return myObjs && !myDoc.IsNull();
921 int Model_Document::numInternalFeatures()
923 return myObjs->numInternalFeatures();
926 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
928 return myObjs->internalFeature(theIndex);
931 // Feature that is used for selection in the Part document by the external request
932 class Model_SelectionInPartFeature : public ModelAPI_Feature {
934 /// Nothing to do in constructor
935 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
937 /// Returns the unique kind of a feature
938 virtual const std::string& getKind() {
939 static std::string MY_KIND("InternalSelectionInPartFeature");
942 /// Request for initialization of data model of the object: adding all attributes
943 virtual void initAttributes() {
944 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
946 /// Nothing to do in the execution function
947 virtual void execute() {}
951 //! Returns the feature that is used for calculation of selection externally from the document
952 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
954 // return already created, otherwise create
955 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
957 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
959 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
960 std::shared_ptr<Model_Data> aData(new Model_Data);
961 aData->setLabel(aFeatureLab.FindChild(1));
962 aData->setObject(mySelectionFeature);
963 mySelectionFeature->setDoc(myObjs->owner());
964 mySelectionFeature->setData(aData);
965 std::string aName = id() + "_Part";
966 mySelectionFeature->data()->setName(aName);
967 mySelectionFeature->setDoc(myObjs->owner());
968 mySelectionFeature->initAttributes();
970 return mySelectionFeature->selectionList("selection");
973 FeaturePtr Model_Document::lastFeature()
976 return myObjs->lastFeature();