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>
18 #include <Events_Loop.h>
19 #include <Events_Error.h>
21 #include <TDataStd_Integer.hxx>
22 #include <TDataStd_Comment.hxx>
23 #include <TDF_ChildIDIterator.hxx>
24 #include <TDataStd_ReferenceArray.hxx>
25 #include <TDataStd_HLabelArray1.hxx>
26 #include <TDataStd_Name.hxx>
27 #include <TDF_Reference.hxx>
28 #include <TDF_ChildIDIterator.hxx>
29 #include <TDF_LabelMapHasher.hxx>
30 #include <OSD_File.hxx>
31 #include <OSD_Path.hxx>
39 # define _separator_ '\\'
41 # define _separator_ '/'
44 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
46 static const int TAG_GENERAL = 1; // general properties tag
49 static const int TAG_CURRENT_FEATURE = 1; ///< where the reference to the current feature label is located (or no attribute if null feature)
50 static const int TAG_CURRENT_TRANSACTION = 2; ///< integer, index of the cransaction
51 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
53 Model_Document::Model_Document(const std::string theID, const std::string theKind)
54 : myID(theID), myKind(theKind), myIsActive(false),
55 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
57 myObjs = new Model_Objects(myDoc->Main());
58 myDoc->SetUndoLimit(UNDO_LIMIT);
59 myTransactionSave = 0;
60 myExecuteFeatures = true;
61 // to have something in the document and avoid empty doc open/save problem
62 // in transaction for nesting correct working
64 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
65 myDoc->CommitCommand();
68 void Model_Document::setThis(DocumentPtr theDoc)
70 myObjs->setOwner(theDoc);
73 /// Returns the file name of this document by the nameof directory and identifuer of a document
74 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
76 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
77 // remove end-separators
78 while(aPath.Length() &&
79 (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
80 aPath.Remove(aPath.Length());
82 aPath += theID.c_str();
83 aPath += ".cbf"; // standard binary file extension
87 bool Model_Document::isRoot() const
89 return this == Model_Session::get()->moduleDocument().get();
92 bool Model_Document::load(const char* theFileName, DocumentPtr theThis)
94 Handle(Model_Application) anApp = Model_Application::getApplication();
96 anApp->setLoadPath(theFileName);
98 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
99 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
101 aStatus = anApp->Open(aPath, myDoc);
102 } catch (Standard_Failure) {
103 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
105 std::string("Exception in opening of document: ") + aFail->GetMessageString());
108 bool isError = aStatus != PCDM_RS_OK;
111 case PCDM_RS_UnknownDocument:
112 Events_Error::send(std::string("Can not open document"));
114 case PCDM_RS_AlreadyRetrieved:
115 Events_Error::send(std::string("Can not open document: already opened"));
117 case PCDM_RS_AlreadyRetrievedAndModified:
119 std::string("Can not open document: already opened and modified"));
121 case PCDM_RS_NoDriver:
122 Events_Error::send(std::string("Can not open document: driver library is not found"));
124 case PCDM_RS_UnknownFileDriver:
125 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
127 case PCDM_RS_OpenError:
128 Events_Error::send(std::string("Can not open document: file open error"));
130 case PCDM_RS_NoVersion:
131 Events_Error::send(std::string("Can not open document: invalid version"));
133 case PCDM_RS_NoModel:
134 Events_Error::send(std::string("Can not open document: no data model"));
136 case PCDM_RS_NoDocument:
137 Events_Error::send(std::string("Can not open document: no document inside"));
139 case PCDM_RS_FormatFailure:
140 Events_Error::send(std::string("Can not open document: format failure"));
142 case PCDM_RS_TypeNotFoundInSchema:
143 Events_Error::send(std::string("Can not open document: invalid object"));
145 case PCDM_RS_UnrecognizedFileFormat:
146 Events_Error::send(std::string("Can not open document: unrecognized file format"));
148 case PCDM_RS_MakeFailure:
149 Events_Error::send(std::string("Can not open document: make failure"));
151 case PCDM_RS_PermissionDenied:
152 Events_Error::send(std::string("Can not open document: permission denied"));
154 case PCDM_RS_DriverFailure:
155 Events_Error::send(std::string("Can not open document: driver failure"));
158 Events_Error::send(std::string("Can not open document: unknown error"));
163 myDoc->SetUndoLimit(UNDO_LIMIT);
164 // to avoid the problem that feature is created in the current, not this, document
165 std::shared_ptr<Model_Session> aSession =
166 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
167 aSession->setActiveDocument(anApp->getDocument(myID), false);
168 aSession->setCheckTransactions(false);
171 myObjs = new Model_Objects(myDoc->Main()); // synchronisation is inside
172 myObjs->setOwner(theThis);
173 // update the current features status
174 setCurrentFeature(currentFeature(false), false);
175 aSession->setCheckTransactions(true);
176 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
177 // this is done in Part result "activate", so no needed here. Causes not-blue active part.
178 // aSession->setActiveDocument(anApp->getDocument(myID), true);
183 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
185 // create a directory in the root document if it is not yet exist
186 Handle(Model_Application) anApp = Model_Application::getApplication();
189 CreateDirectory(theFileName, NULL);
191 mkdir(theFileName, 0x1ff);
194 // filename in the dir is id of document inside of the given directory
195 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
196 PCDM_StoreStatus aStatus;
198 aStatus = anApp->SaveAs(myDoc, aPath);
199 } catch (Standard_Failure) {
200 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
202 std::string("Exception in saving of document: ") + aFail->GetMessageString());
205 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
208 case PCDM_SS_DriverFailure:
209 Events_Error::send(std::string("Can not save document: save driver-library failure"));
211 case PCDM_SS_WriteFailure:
212 Events_Error::send(std::string("Can not save document: file writing failure"));
214 case PCDM_SS_Failure:
216 Events_Error::send(std::string("Can not save document"));
220 myTransactionSave = myTransactions.size();
221 if (isDone) { // save also sub-documents if any
222 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
223 const std::set<std::string> aSubs = subDocuments(false);
224 std::set<std::string>::iterator aSubIter = aSubs.begin();
225 for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
226 if (anApp->isLoadByDemand(*aSubIter)) {
227 // copy not-activated document that is not in the memory
228 std::string aDocName = *aSubIter;
229 if (!aDocName.empty()) {
231 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
232 OSD_Path aPath(aSubPath);
233 OSD_File aFile(aPath);
234 if (aFile.Exists()) {
235 TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
236 OSD_Path aDestination(aDestinationDir);
237 aFile.Copy(aDestination);
238 theResults.push_back(aDestinationDir.ToCString());
241 std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
244 } else { // simply save opened document
245 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
252 void Model_Document::close(const bool theForever)
254 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
255 if (!isRoot() && this == aPM->activeDocument().get()) {
256 aPM->setActiveDocument(aPM->moduleDocument());
257 } else if (isRoot()) {
258 // erase the active document if root is closed
259 aPM->setActiveDocument(DocumentPtr());
262 const std::set<std::string> aSubs = subDocuments(true);
263 std::set<std::string>::iterator aSubIter = aSubs.begin();
264 for (; aSubIter != aSubs.end(); aSubIter++) {
265 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
266 if (aSub->myObjs) // if it was not closed before
267 aSub->close(theForever);
270 // close for thid document needs no transaction in this document
271 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
273 // close all only if it is really asked, otherwise it can be undoed/redoed
277 if (myDoc->CanClose() == CDM_CCS_OK)
279 mySelectionFeature.reset();
281 setCurrentFeature(FeaturePtr(), false); // disables all features
284 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
287 void Model_Document::startOperation()
289 if (myDoc->HasOpenCommand()) { // start of nested command
290 if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
291 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
293 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
294 myDoc->OpenCommand();
295 } else { // start the simple command
298 // starts a new operation
299 incrementTransactionID();
300 myTransactions.push_back(Transaction());
301 if (!myNestedNum.empty())
302 (*myNestedNum.rbegin())++;
304 // new command for all subs
305 const std::set<std::string> aSubs = subDocuments(true);
306 std::set<std::string>::iterator aSubIter = aSubs.begin();
307 for (; aSubIter != aSubs.end(); aSubIter++)
308 subDoc(*aSubIter)->startOperation();
311 void Model_Document::compactNested()
313 if (!myNestedNum.empty()) {
314 int aNumToCompact = *(myNestedNum.rbegin());
315 int aSumOfTransaction = 0;
316 for(int a = 0; a < aNumToCompact; a++) {
317 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
318 myTransactions.pop_back();
320 // the latest transaction is the start of lower-level operation which startes the nested
321 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
322 myNestedNum.pop_back();
326 bool Model_Document::finishOperation()
328 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
329 static std::shared_ptr<Model_Session> aSession =
330 std::static_pointer_cast<Model_Session>(Model_Session::get());
331 myObjs->synchronizeBackRefs();
332 Events_Loop* aLoop = Events_Loop::loop();
333 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
334 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
335 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
336 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
337 // this must be here just after everything is finished but before real transaction stop
338 // to avoid messages about modifications outside of the transaction
339 // and to rebuild everything after all updates and creates
340 if (isRoot()) { // once for root document
341 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
342 static std::shared_ptr<Events_Message> aFinishMsg
343 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
344 Events_Loop::loop()->send(aFinishMsg);
345 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
347 // to avoid "updated" message appearance by updater
348 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
350 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
351 bool aResult = false;
352 const std::set<std::string> aSubs = subDocuments(true);
353 std::set<std::string>::iterator aSubIter = aSubs.begin();
354 for (; aSubIter != aSubs.end(); aSubIter++)
355 if (subDoc(*aSubIter)->finishOperation())
358 // transaction may be empty if this document was created during this transaction (create part)
359 if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
360 myTransactions.rbegin()->myOCAFNum++;
364 if (isNestedClosed) {
367 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
368 aResult = myTransactions.rbegin()->myOCAFNum != 0;
370 if (!aResult && isRoot()) {
371 // nothing inside in all documents, so remove this transaction from the transactions list
372 undoInternal(true, false);
374 // on finish clear redos in any case (issue 446) and for all subs (issue 408)
377 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
378 subDoc(*aSubIter)->myDoc->ClearRedos();
379 subDoc(*aSubIter)->myRedos.clear();
385 void Model_Document::abortOperation()
387 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
389 undoInternal(false, false);
392 } else { // abort the current
393 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
394 myTransactions.pop_back();
395 if (!myNestedNum.empty())
396 (*myNestedNum.rbegin())--;
397 // roll back the needed number of transactions
398 myDoc->AbortCommand();
399 for(int a = 0; a < aNumTransactions; a++)
403 // abort for all subs, flushes will be later, in the end of root abort
404 const std::set<std::string> aSubs = subDocuments(true);
405 std::set<std::string>::iterator aSubIter = aSubs.begin();
406 for (; aSubIter != aSubs.end(); aSubIter++)
407 subDoc(*aSubIter)->abortOperation();
408 // references may be changed because they are set in attributes on the fly
409 myObjs->synchronizeFeatures(true, true, isRoot());
412 bool Model_Document::isOperation() const
414 // operation is opened for all documents: no need to check subs
415 return myDoc->HasOpenCommand() == Standard_True ;
418 bool Model_Document::isModified()
420 // is modified if at least one operation was commited and not undoed
421 return myTransactions.size() != myTransactionSave || isOperation();
424 bool Model_Document::canUndo()
426 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
427 int aCurrentNum = isOperation() ? 1 : 0;
428 if (myDoc->GetAvailableUndos() > 0 &&
429 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
430 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
432 // check other subs contains operation that can be undoed
433 const std::set<std::string> aSubs = subDocuments(true);
434 std::set<std::string>::iterator aSubIter = aSubs.begin();
435 for (; aSubIter != aSubs.end(); aSubIter++) {
436 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
437 if (aSub->myObjs) {// if it was not closed before
446 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
448 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
449 myRedos.push_back(*myTransactions.rbegin());
450 myTransactions.pop_back();
451 if (!myNestedNum.empty())
452 (*myNestedNum.rbegin())--;
453 // roll back the needed number of transactions
454 for(int a = 0; a < aNumTransactions; a++)
459 const std::set<std::string> aSubs = subDocuments(true);
460 std::set<std::string>::iterator aSubIter = aSubs.begin();
461 for (; aSubIter != aSubs.end(); aSubIter++) {
462 if (!subDoc(*aSubIter)->myObjs)
464 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
467 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
468 if (theSynchronize) {
469 myObjs->synchronizeFeatures(true, true, isRoot());
470 // update the current features status
471 setCurrentFeature(currentFeature(false), false);
475 void Model_Document::undo()
477 undoInternal(true, true);
480 bool Model_Document::canRedo()
482 if (!myRedos.empty())
484 // check other subs contains operation that can be redoed
485 const std::set<std::string> aSubs = subDocuments(true);
486 std::set<std::string>::iterator aSubIter = aSubs.begin();
487 for (; aSubIter != aSubs.end(); aSubIter++) {
488 if (!subDoc(*aSubIter)->myObjs)
490 if (subDoc(*aSubIter)->canRedo())
496 void Model_Document::redo()
498 if (!myNestedNum.empty())
499 (*myNestedNum.rbegin())++;
500 int aNumRedos = myRedos.rbegin()->myOCAFNum;
501 myTransactions.push_back(*myRedos.rbegin());
503 for(int a = 0; a < aNumRedos; a++)
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 subDoc(*aSubIter)->redo();
512 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
513 myObjs->synchronizeFeatures(true, true, isRoot());
514 // update the current features status
515 setCurrentFeature(currentFeature(false), false);
518 std::list<std::string> Model_Document::undoList() const
520 std::list<std::string> aResult;
521 // the number of skipped current operations (on undo they will be aborted)
522 int aSkipCurrent = isOperation() ? 1 : 0;
523 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
524 int aNumUndo = myTransactions.size();
525 if (!myNestedNum.empty())
526 aNumUndo = *myNestedNum.rbegin();
527 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
528 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
534 std::list<std::string> Model_Document::redoList() const
536 std::list<std::string> aResult;
537 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
538 for( ; aTrIter != myRedos.crend(); aTrIter++) {
539 aResult.push_back(aTrIter->myId);
544 void Model_Document::operationId(const std::string& theId)
546 myTransactions.rbegin()->myId = theId;
549 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
551 std::shared_ptr<Model_Session> aSession =
552 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
553 FeaturePtr aFeature = aSession->createFeature(theID, this);
556 Model_Document* aDocToAdd;
557 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
558 if (aFeature->documentToAdd() != kind()) { // the root document by default
559 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
563 } else { // if customized is not presented, add to "this" document
567 aDocToAdd->myObjs->addFeature(aFeature, aDocToAdd->currentFeature(false));
568 if (!aFeature->isAction()) { // do not add action to the data model
569 if (theMakeCurrent) // after all this feature stays in the document, so make it current
570 aDocToAdd->setCurrentFeature(aFeature, false);
571 } else { // feature must be executed
572 // no creation event => updater not working, problem with remove part
580 void Model_Document::refsToFeature(FeaturePtr theFeature,
581 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
583 myObjs->refsToFeature(theFeature, theRefs, isSendError);
586 void Model_Document::removeFeature(FeaturePtr theFeature)
588 myObjs->removeFeature(theFeature);
591 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
593 myObjs->moveFeature(theMoved, theAfterThis);
596 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
598 myObjs->updateHistory(theObject);
601 void Model_Document::updateHistory(const std::string theGroup)
603 myObjs->updateHistory(theGroup);
606 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
608 return Model_Application::getApplication()->getDocument(theDocID);
611 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
613 std::set<std::string> aResult;
614 std::list<ResultPtr> aPartResults;
615 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
616 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
617 for(; aPartRes != aPartResults.end(); aPartRes++) {
618 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
619 if (aPart && (!theActivatedOnly || aPart->isActivated()))
620 aResult.insert(aPart->data()->name());
625 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
627 // just store sub-document identifier here to manage it later
628 return std::dynamic_pointer_cast<Model_Document>(
629 Model_Application::getApplication()->getDocument(theDocID));
632 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
634 return myObjs->object(theGroupID, theIndex);
637 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
638 const std::string& theGroupID, const std::string& theName)
640 return myObjs->objectByName(theGroupID, theName);
643 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
645 return myObjs->index(theObject);
648 int Model_Document::size(const std::string& theGroupID)
650 return myObjs->size(theGroupID);
653 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
655 if (!myObjs) // on close document feature destruction it may call this method
656 return std::shared_ptr<ModelAPI_Feature>();
657 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
658 Handle(TDF_Reference) aRef;
659 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
660 TDF_Label aLab = aRef->Get();
661 FeaturePtr aResult = myObjs->feature(aLab);
662 if (theVisible) { // get nearest visible (in history) going up
663 while(aResult.get() && !aResult->isInHistory()) {
664 aResult = myObjs->nextFeature(aResult, true);
669 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
672 void Model_Document::setCurrentFeature(std::shared_ptr<ModelAPI_Feature> theCurrent,
673 const bool theVisible)
675 // blocks the flush signals to avoid each objects visualization in the viewer
676 // they should not be shown once after all modifications are performed
677 Events_Loop* aLoop = Events_Loop::loop();
678 bool isActive = aLoop->activateFlushes(false);
680 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
681 CompositeFeaturePtr aMain; // main feature that may nest the new current
682 if (theCurrent.get()) {
683 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
685 // if feature nests into compisite feature, make the composite feature as current
686 const std::set<AttributePtr>& aRefsToMe = theCurrent->data()->refsToMe();
687 std::set<AttributePtr>::const_iterator aRefToMe = aRefsToMe.begin();
688 for(; aRefToMe != aRefsToMe.end(); aRefToMe++) {
689 CompositeFeaturePtr aComposite =
690 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>((*aRefToMe)->owner());
691 if (aComposite.get() && aComposite->isSub(theCurrent)) {
699 if (theVisible) { // make features below which are not in history also enabled: sketch subs
701 theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
702 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
703 if (aNext->isInHistory()) {
704 break; // next in history is not needed
705 } else { // next not in history is good for making current
710 if (theCurrent.get()) {
711 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
712 if (!aData.get() || !aData->isValid()) {
713 aLoop->activateFlushes(isActive);
716 TDF_Label aFeatureLabel = aData->label().Father();
718 Handle(TDF_Reference) aRef;
719 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
720 aRef->Set(aFeatureLabel);
722 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
724 } else { // remove reference for the null feature
725 aRefLab.ForgetAttribute(TDF_Reference::GetID());
727 // make all features after this feature disabled in reversed order (to remove results without deps)
728 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
729 static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
730 static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
732 bool aPassed = false; // flag that the current object is already passed in cycle
733 FeaturePtr anIter = myObjs->lastFeature();
734 bool aWasChanged = false;
735 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
736 // check this before passed become enabled: the current feature is enabled!
737 if (anIter == theCurrent) aPassed = true;
739 bool aDisabledFlag = !aPassed;
740 if (aMain.get() && aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
741 aDisabledFlag = false;
742 if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
743 if (theCurrent.get() && theCurrent->getKind() != "Parameter")
744 aDisabledFlag = false;
746 if (anIter->setDisabled(aDisabledFlag)) {
747 // state of feature is changed => so feature become updated
748 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
749 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
750 // flush is in the end of this method
751 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
754 // update for everyone the concealment flag immideately: on edit feature in the midle of history
756 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = anIter->results();
757 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
758 for(; aRes != aResList.end(); aRes++) {
759 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
760 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
765 // unblock the flush signals and up them after this
766 aLoop->activateFlushes(isActive);
768 aLoop->flush(aCreateEvent);
769 aLoop->flush(aRedispEvent);
770 aLoop->flush(aDeleteEvent);
773 void Model_Document::setCurrentFeatureUp()
775 // on remove just go up for minimum step: highlight external objects in sketch causes
776 // problems if it is true: here and in "setCurrentFeature"
777 FeaturePtr aCurrent = currentFeature(false);
778 if (aCurrent.get()) { // if not, do nothing because null is the upper
779 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
780 setCurrentFeature(aPrev, false);
784 TDF_Label Model_Document::generalLabel() const
786 return myDoc->Main().FindChild(TAG_GENERAL);
789 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
790 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
792 return myObjs->createConstruction(theFeatureData, theIndex);
795 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
796 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
798 return myObjs->createBody(theFeatureData, theIndex);
801 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
802 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
804 return myObjs->createPart(theFeatureData, theIndex);
807 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
808 const std::shared_ptr<ModelAPI_Result>& theOldPart,
809 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
812 return myObjs->copyPart(theOldPart, theOrigin, theIndex);
815 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
816 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
818 return myObjs->createGroup(theFeatureData, theIndex);
821 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
822 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
824 return myObjs->createParameter(theFeatureData, theIndex);
827 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
828 const std::shared_ptr<ModelAPI_Result>& theResult)
830 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
832 TDF_Label aFeatureLab = aData->label().Father().Father().Father();
833 return myObjs->feature(aFeatureLab);
838 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
840 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
843 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
845 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
848 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
850 myNamingNames[theName] = theLabel;
853 TDF_Label Model_Document::findNamingName(std::string theName)
855 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
856 if (aFind == myNamingNames.end())
857 return TDF_Label(); // not found
858 return aFind->second;
861 ResultPtr Model_Document::findByName(const std::string theName)
863 return myObjs->findByName(theName);
866 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
868 return myObjs->allFeatures();
871 void Model_Document::setActive(const bool theFlag)
873 if (theFlag != myIsActive) {
874 myIsActive = theFlag;
875 // redisplay all the objects of this part
876 static Events_Loop* aLoop = Events_Loop::loop();
877 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
879 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
880 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
881 object(ModelAPI_Feature::group(), a));
882 if (aFeature.get() && aFeature->data()->isValid()) {
883 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
884 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
885 for(; aRes != aResList.end(); aRes++) {
886 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
893 bool Model_Document::isActive() const
898 int Model_Document::transactionID()
900 Handle(TDataStd_Integer) anIndex;
901 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
902 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
903 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
905 return anIndex->Get();
908 void Model_Document::incrementTransactionID()
910 int aNewVal = transactionID() + 1;
911 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
913 void Model_Document::decrementTransactionID()
915 int aNewVal = transactionID() - 1;
916 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
919 bool Model_Document::isOpened()
921 return myObjs && !myDoc.IsNull();
924 int Model_Document::numInternalFeatures()
926 return myObjs->numInternalFeatures();
929 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
931 return myObjs->internalFeature(theIndex);
934 // Feature that is used for selection in the Part document by the external request
935 class Model_SelectionInPartFeature : public ModelAPI_Feature {
937 /// Nothing to do in constructor
938 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
940 /// Returns the unique kind of a feature
941 virtual const std::string& getKind() {
942 static std::string MY_KIND("InternalSelectionInPartFeature");
945 /// Request for initialization of data model of the object: adding all attributes
946 virtual void initAttributes() {
947 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
949 /// Nothing to do in the execution function
950 virtual void execute() {}
954 //! Returns the feature that is used for calculation of selection externally from the document
955 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
957 // return already created, otherwise create
958 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
960 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
962 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
963 std::shared_ptr<Model_Data> aData(new Model_Data);
964 aData->setLabel(aFeatureLab.FindChild(1));
965 aData->setObject(mySelectionFeature);
966 mySelectionFeature->setDoc(myObjs->owner());
967 mySelectionFeature->setData(aData);
968 std::string aName = id() + "_Part";
969 mySelectionFeature->data()->setName(aName);
970 mySelectionFeature->setDoc(myObjs->owner());
971 mySelectionFeature->initAttributes();
973 return mySelectionFeature->selectionList("selection");