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->data()->name());
626 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
628 // just store sub-document identifier here to manage it later
629 return std::dynamic_pointer_cast<Model_Document>(
630 Model_Application::getApplication()->getDocument(theDocID));
633 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
635 return myObjs->object(theGroupID, theIndex);
638 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
639 const std::string& theGroupID, const std::string& theName)
641 return myObjs->objectByName(theGroupID, theName);
644 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
646 return myObjs->index(theObject);
649 int Model_Document::size(const std::string& theGroupID)
651 return myObjs->size(theGroupID);
654 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
656 if (!myObjs) // on close document feature destruction it may call this method
657 return std::shared_ptr<ModelAPI_Feature>();
658 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
659 Handle(TDF_Reference) aRef;
660 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
661 TDF_Label aLab = aRef->Get();
662 FeaturePtr aResult = myObjs->feature(aLab);
663 if (theVisible) { // get nearest visible (in history) going up
664 while(aResult.get() && // sub-composites are never in history
665 (!aResult->isInHistory() || ModelAPI_Tools::compositeOwner(aResult).get())) {
666 aResult = myObjs->nextFeature(aResult, true);
671 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
674 void Model_Document::setCurrentFeature(std::shared_ptr<ModelAPI_Feature> theCurrent,
675 const bool theVisible)
677 // blocks the flush signals to avoid each objects visualization in the viewer
678 // they should not be shown once after all modifications are performed
679 Events_Loop* aLoop = Events_Loop::loop();
680 bool isActive = aLoop->activateFlushes(false);
682 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
683 CompositeFeaturePtr aMain; // main feature that may nest the new current
684 if (theCurrent.get()) {
685 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
687 // if feature nests into compisite feature, make the composite feature as current
688 const std::set<AttributePtr>& aRefsToMe = theCurrent->data()->refsToMe();
689 std::set<AttributePtr>::const_iterator aRefToMe = aRefsToMe.begin();
690 for(; aRefToMe != aRefsToMe.end(); aRefToMe++) {
691 CompositeFeaturePtr aComposite =
692 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>((*aRefToMe)->owner());
693 if (aComposite.get() && aComposite->isSub(theCurrent)) {
701 if (theVisible) { // make features below which are not in history also enabled: sketch subs
703 theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
704 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
705 if (aNext->isInHistory()) {
706 break; // next in history is not needed
707 } else { // next not in history is good for making current
712 if (theCurrent.get()) {
713 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
714 if (!aData.get() || !aData->isValid()) {
715 aLoop->activateFlushes(isActive);
718 TDF_Label aFeatureLabel = aData->label().Father();
720 Handle(TDF_Reference) aRef;
721 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
722 aRef->Set(aFeatureLabel);
724 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
726 } else { // remove reference for the null feature
727 aRefLab.ForgetAttribute(TDF_Reference::GetID());
729 // make all features after this feature disabled in reversed order (to remove results without deps)
730 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
731 static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
732 static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
734 bool aPassed = false; // flag that the current object is already passed in cycle
735 FeaturePtr anIter = myObjs->lastFeature();
736 bool aWasChanged = false;
737 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
738 // check this before passed become enabled: the current feature is enabled!
739 if (anIter == theCurrent) aPassed = true;
741 bool aDisabledFlag = !aPassed;
742 if (aMain.get() && aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
743 aDisabledFlag = false;
744 if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
745 if (theCurrent.get() && theCurrent->getKind() != "Parameter")
746 aDisabledFlag = false;
748 if (anIter->setDisabled(aDisabledFlag)) {
749 // state of feature is changed => so feature become updated
750 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
751 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
752 // flush is in the end of this method
753 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
756 // update for everyone the concealment flag immideately: on edit feature in the midle of history
758 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = anIter->results();
759 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
760 for(; aRes != aResList.end(); aRes++) {
761 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
762 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
767 // unblock the flush signals and up them after this
768 aLoop->activateFlushes(isActive);
770 aLoop->flush(aCreateEvent);
771 aLoop->flush(aRedispEvent);
772 aLoop->flush(aDeleteEvent);
775 void Model_Document::setCurrentFeatureUp()
777 // on remove just go up for minimum step: highlight external objects in sketch causes
778 // problems if it is true: here and in "setCurrentFeature"
779 FeaturePtr aCurrent = currentFeature(false);
780 if (aCurrent.get()) { // if not, do nothing because null is the upper
781 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
782 setCurrentFeature(aPrev, false);
786 TDF_Label Model_Document::generalLabel() const
788 return myDoc->Main().FindChild(TAG_GENERAL);
791 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
792 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
794 return myObjs->createConstruction(theFeatureData, theIndex);
797 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
798 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
800 return myObjs->createBody(theFeatureData, theIndex);
803 std::shared_ptr<ModelAPI_ResultCompSolid> Model_Document::createCompSolid(
804 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
806 return myObjs->createCompSolid(theFeatureData, theIndex);
809 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
810 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
812 return myObjs->createPart(theFeatureData, theIndex);
815 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
816 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
817 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
819 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
822 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
823 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
825 return myObjs->createGroup(theFeatureData, theIndex);
828 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
829 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
831 return myObjs->createParameter(theFeatureData, theIndex);
834 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
835 const std::shared_ptr<ModelAPI_Result>& theResult)
837 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
839 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
840 return myObjs->feature(aFeatureLab);
845 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
847 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
850 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
852 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
855 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
857 myNamingNames[theName] = theLabel;
860 TDF_Label Model_Document::findNamingName(std::string theName)
862 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
863 if (aFind == myNamingNames.end())
864 return TDF_Label(); // not found
865 return aFind->second;
868 ResultPtr Model_Document::findByName(const std::string theName)
870 return myObjs->findByName(theName);
873 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
875 return myObjs->allFeatures();
878 void Model_Document::setActive(const bool theFlag)
880 if (theFlag != myIsActive) {
881 myIsActive = theFlag;
882 // redisplay all the objects of this part
883 static Events_Loop* aLoop = Events_Loop::loop();
884 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
886 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
887 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
888 object(ModelAPI_Feature::group(), a));
889 if (aFeature.get() && aFeature->data()->isValid()) {
890 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
891 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
892 for(; aRes != aResList.end(); aRes++) {
893 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
900 bool Model_Document::isActive() const
905 int Model_Document::transactionID()
907 Handle(TDataStd_Integer) anIndex;
908 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
909 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
910 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
912 return anIndex->Get();
915 void Model_Document::incrementTransactionID()
917 int aNewVal = transactionID() + 1;
918 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
920 void Model_Document::decrementTransactionID()
922 int aNewVal = transactionID() - 1;
923 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
926 bool Model_Document::isOpened()
928 return myObjs && !myDoc.IsNull();
931 int Model_Document::numInternalFeatures()
933 return myObjs->numInternalFeatures();
936 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
938 return myObjs->internalFeature(theIndex);
941 // Feature that is used for selection in the Part document by the external request
942 class Model_SelectionInPartFeature : public ModelAPI_Feature {
944 /// Nothing to do in constructor
945 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
947 /// Returns the unique kind of a feature
948 virtual const std::string& getKind() {
949 static std::string MY_KIND("InternalSelectionInPartFeature");
952 /// Request for initialization of data model of the object: adding all attributes
953 virtual void initAttributes() {
954 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
956 /// Nothing to do in the execution function
957 virtual void execute() {}
961 //! Returns the feature that is used for calculation of selection externally from the document
962 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
964 // return already created, otherwise create
965 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
967 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
969 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
970 std::shared_ptr<Model_Data> aData(new Model_Data);
971 aData->setLabel(aFeatureLab.FindChild(1));
972 aData->setObject(mySelectionFeature);
973 mySelectionFeature->setDoc(myObjs->owner());
974 mySelectionFeature->setData(aData);
975 std::string aName = id() + "_Part";
976 mySelectionFeature->data()->setName(aName);
977 mySelectionFeature->setDoc(myObjs->owner());
978 mySelectionFeature->initAttributes();
980 return mySelectionFeature->selectionList("selection");
983 FeaturePtr Model_Document::lastFeature()
986 return myObjs->lastFeature();