1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
3 // File: Model_Document.cxx
4 // Created: 28 Feb 2014
5 // Author: Mikhail PONIKAROV
7 #include <Model_Document.h>
8 #include <Model_Data.h>
9 #include <Model_Objects.h>
10 #include <Model_Application.h>
11 #include <Model_Session.h>
12 #include <Model_Events.h>
13 #include <ModelAPI_ResultPart.h>
14 #include <ModelAPI_Validator.h>
15 #include <ModelAPI_CompositeFeature.h>
16 #include <ModelAPI_AttributeSelectionList.h>
17 #include <ModelAPI_Tools.h>
19 #include <Events_Loop.h>
20 #include <Events_Error.h>
22 #include <TDataStd_Integer.hxx>
23 #include <TDataStd_Comment.hxx>
24 #include <TDF_ChildIDIterator.hxx>
25 #include <TDataStd_ReferenceArray.hxx>
26 #include <TDataStd_HLabelArray1.hxx>
27 #include <TDataStd_Name.hxx>
28 #include <TDF_Reference.hxx>
29 #include <TDF_ChildIDIterator.hxx>
30 #include <TDF_LabelMapHasher.hxx>
31 #include <TDF_Delta.hxx>
32 #include <OSD_File.hxx>
33 #include <OSD_Path.hxx>
34 #include <TDF_AttributeDelta.hxx>
35 #include <TDF_AttributeDeltaList.hxx>
36 #include <TDF_ListIteratorOfAttributeDeltaList.hxx>
37 #include <TDF_ListIteratorOfLabelList.hxx>
45 # define _separator_ '\\'
47 # define _separator_ '/'
50 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
52 static const int TAG_GENERAL = 1; // general properties tag
55 static const int TAG_CURRENT_FEATURE = 1; ///< where the reference to the current feature label is located (or no attribute if null feature)
56 static const int TAG_CURRENT_TRANSACTION = 2; ///< integer, index of the cransaction
57 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
59 Model_Document::Model_Document(const std::string theID, const std::string theKind)
60 : myID(theID), myKind(theKind), myIsActive(false),
61 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
63 myObjs = new Model_Objects(myDoc->Main());
64 myDoc->SetUndoLimit(UNDO_LIMIT);
65 myTransactionSave = 0;
66 myExecuteFeatures = true;
67 // to have something in the document and avoid empty doc open/save problem
68 // in transaction for nesting correct working
70 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
71 // this to avoid creation of integer attribute outside the transaction after undo
73 myDoc->CommitCommand();
76 void Model_Document::setThis(DocumentPtr theDoc)
78 myObjs->setOwner(theDoc);
81 /// Returns the file name of this document by the nameof directory and identifuer of a document
82 static TCollection_ExtendedString DocFileName(const char* theFileName, const std::string& theID)
84 TCollection_ExtendedString aPath((const Standard_CString) theFileName);
85 // remove end-separators
86 while(aPath.Length() &&
87 (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
88 aPath.Remove(aPath.Length());
90 aPath += theID.c_str();
91 aPath += ".cbf"; // standard binary file extension
95 bool Model_Document::isRoot() const
97 return this == Model_Session::get()->moduleDocument().get();
100 bool Model_Document::load(const char* theFileName, DocumentPtr theThis)
102 Handle(Model_Application) anApp = Model_Application::getApplication();
104 anApp->setLoadPath(theFileName);
106 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
107 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
109 aStatus = anApp->Open(aPath, myDoc);
110 } catch (Standard_Failure) {
111 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
113 std::string("Exception in opening of document: ") + aFail->GetMessageString());
116 bool isError = aStatus != PCDM_RS_OK;
119 case PCDM_RS_UnknownDocument:
120 Events_Error::send(std::string("Can not open document"));
122 case PCDM_RS_AlreadyRetrieved:
123 Events_Error::send(std::string("Can not open document: already opened"));
125 case PCDM_RS_AlreadyRetrievedAndModified:
127 std::string("Can not open document: already opened and modified"));
129 case PCDM_RS_NoDriver:
130 Events_Error::send(std::string("Can not open document: driver library is not found"));
132 case PCDM_RS_UnknownFileDriver:
133 Events_Error::send(std::string("Can not open document: unknown driver for opening"));
135 case PCDM_RS_OpenError:
136 Events_Error::send(std::string("Can not open document: file open error"));
138 case PCDM_RS_NoVersion:
139 Events_Error::send(std::string("Can not open document: invalid version"));
141 case PCDM_RS_NoModel:
142 Events_Error::send(std::string("Can not open document: no data model"));
144 case PCDM_RS_NoDocument:
145 Events_Error::send(std::string("Can not open document: no document inside"));
147 case PCDM_RS_FormatFailure:
148 Events_Error::send(std::string("Can not open document: format failure"));
150 case PCDM_RS_TypeNotFoundInSchema:
151 Events_Error::send(std::string("Can not open document: invalid object"));
153 case PCDM_RS_UnrecognizedFileFormat:
154 Events_Error::send(std::string("Can not open document: unrecognized file format"));
156 case PCDM_RS_MakeFailure:
157 Events_Error::send(std::string("Can not open document: make failure"));
159 case PCDM_RS_PermissionDenied:
160 Events_Error::send(std::string("Can not open document: permission denied"));
162 case PCDM_RS_DriverFailure:
163 Events_Error::send(std::string("Can not open document: driver failure"));
166 Events_Error::send(std::string("Can not open document: unknown error"));
171 myDoc->SetUndoLimit(UNDO_LIMIT);
172 // to avoid the problem that feature is created in the current, not this, document
173 std::shared_ptr<Model_Session> aSession =
174 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
175 aSession->setActiveDocument(anApp->getDocument(myID), false);
176 aSession->setCheckTransactions(false);
179 myObjs = new Model_Objects(myDoc->Main()); // synchronisation is inside
180 myObjs->setOwner(theThis);
181 // update the current features status
182 setCurrentFeature(currentFeature(false), false);
183 aSession->setCheckTransactions(true);
184 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
185 // this is done in Part result "activate", so no needed here. Causes not-blue active part.
186 // aSession->setActiveDocument(anApp->getDocument(myID), true);
191 bool Model_Document::save(const char* theFileName, std::list<std::string>& theResults)
193 // create a directory in the root document if it is not yet exist
194 Handle(Model_Application) anApp = Model_Application::getApplication();
197 CreateDirectory(theFileName, NULL);
199 mkdir(theFileName, 0x1ff);
202 // filename in the dir is id of document inside of the given directory
203 TCollection_ExtendedString aPath(DocFileName(theFileName, myID));
204 PCDM_StoreStatus aStatus;
206 aStatus = anApp->SaveAs(myDoc, aPath);
207 } catch (Standard_Failure) {
208 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
210 std::string("Exception in saving of document: ") + aFail->GetMessageString());
213 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
216 case PCDM_SS_DriverFailure:
217 Events_Error::send(std::string("Can not save document: save driver-library failure"));
219 case PCDM_SS_WriteFailure:
220 Events_Error::send(std::string("Can not save document: file writing failure"));
222 case PCDM_SS_Failure:
224 Events_Error::send(std::string("Can not save document"));
228 myTransactionSave = myTransactions.size();
229 if (isDone) { // save also sub-documents if any
230 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
231 const std::set<std::string> aSubs = subDocuments(false);
232 std::set<std::string>::iterator aSubIter = aSubs.begin();
233 for (; aSubIter != aSubs.end() && isDone; aSubIter++) {
234 if (anApp->isLoadByDemand(*aSubIter)) {
235 // copy not-activated document that is not in the memory
236 std::string aDocName = *aSubIter;
237 if (!aDocName.empty()) {
239 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
240 OSD_Path aPath(aSubPath);
241 OSD_File aFile(aPath);
242 if (aFile.Exists()) {
243 TCollection_AsciiString aDestinationDir(DocFileName(theFileName, aDocName));
244 OSD_Path aDestination(aDestinationDir);
245 aFile.Copy(aDestination);
246 theResults.push_back(aDestinationDir.ToCString());
249 std::string("Can not open file ") + aSubPath.ToCString() + " for saving");
252 } else { // simply save opened document
253 isDone = subDoc(*aSubIter)->save(theFileName, theResults);
260 void Model_Document::close(const bool theForever)
262 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
263 if (!isRoot() && this == aPM->activeDocument().get()) {
264 aPM->setActiveDocument(aPM->moduleDocument());
265 } else if (isRoot()) {
266 // erase the active document if root is closed
267 aPM->setActiveDocument(DocumentPtr());
270 const std::set<std::string> aSubs = subDocuments(true);
271 std::set<std::string>::iterator aSubIter = aSubs.begin();
272 for (; aSubIter != aSubs.end(); aSubIter++) {
273 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
274 if (aSub->myObjs) // if it was not closed before
275 aSub->close(theForever);
278 // close for thid document needs no transaction in this document
279 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
281 // close all only if it is really asked, otherwise it can be undoed/redoed
283 // flush everything to avoid messages with bad objects
286 if (myDoc->CanClose() == CDM_CCS_OK)
288 mySelectionFeature.reset();
290 setCurrentFeature(FeaturePtr(), false); // disables all features
293 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
296 void Model_Document::startOperation()
298 if (myDoc->HasOpenCommand()) { // start of nested command
299 if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
300 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
302 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
303 myDoc->OpenCommand();
304 } else { // start the simple command
307 // starts a new operation
308 incrementTransactionID();
309 myTransactions.push_back(Transaction());
310 if (!myNestedNum.empty())
311 (*myNestedNum.rbegin())++;
313 // new command for all subs
314 const std::set<std::string> aSubs = subDocuments(true);
315 std::set<std::string>::iterator aSubIter = aSubs.begin();
316 for (; aSubIter != aSubs.end(); aSubIter++)
317 subDoc(*aSubIter)->startOperation();
320 void Model_Document::compactNested()
322 if (!myNestedNum.empty()) {
323 int aNumToCompact = *(myNestedNum.rbegin());
324 int aSumOfTransaction = 0;
325 for(int a = 0; a < aNumToCompact; a++) {
326 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
327 myTransactions.pop_back();
329 // the latest transaction is the start of lower-level operation which startes the nested
330 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
331 myNestedNum.pop_back();
335 bool Model_Document::finishOperation()
337 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
338 static std::shared_ptr<Model_Session> aSession =
339 std::static_pointer_cast<Model_Session>(Model_Session::get());
340 myObjs->synchronizeBackRefs();
341 Events_Loop* aLoop = Events_Loop::loop();
342 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
343 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
344 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
345 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
346 // this must be here just after everything is finished but before real transaction stop
347 // to avoid messages about modifications outside of the transaction
348 // and to rebuild everything after all updates and creates
349 if (isRoot()) { // once for root document
350 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
351 static std::shared_ptr<Events_Message> aFinishMsg
352 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
353 Events_Loop::loop()->send(aFinishMsg);
354 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
356 // to avoid "updated" message appearance by updater
357 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
359 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
360 bool aResult = false;
361 const std::set<std::string> aSubs = subDocuments(true);
362 std::set<std::string>::iterator aSubIter = aSubs.begin();
363 for (; aSubIter != aSubs.end(); aSubIter++)
364 if (subDoc(*aSubIter)->finishOperation())
367 // transaction may be empty if this document was created during this transaction (create part)
368 if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
369 myTransactions.rbegin()->myOCAFNum++;
373 if (isNestedClosed) {
376 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
377 aResult = myTransactions.rbegin()->myOCAFNum != 0;
379 if (!aResult && isRoot()) {
380 // nothing inside in all documents, so remove this transaction from the transactions list
381 undoInternal(true, false);
383 // on finish clear redos in any case (issue 446) and for all subs (issue 408)
386 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
387 subDoc(*aSubIter)->myDoc->ClearRedos();
388 subDoc(*aSubIter)->myRedos.clear();
394 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
395 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
396 const bool isRedo = false) {
397 Handle(TDF_Delta) aDelta;
399 aDelta = theDoc->GetRedos().First();
401 aDelta = theDoc->GetUndos().Last();
402 TDF_LabelList aDeltaList;
403 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
404 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
405 theDelta.Append(aListIter.Value());
407 // add also label of the modified attributes
408 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
409 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
410 theDelta.Append(anAttr.Value()->Label());
414 void Model_Document::abortOperation()
416 TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
417 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
419 // store undo-delta here as undo actually does in the method later
420 int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
421 for(a = 0; a < aNumTransactions; a++) {
422 modifiedLabels(myDoc, aDeltaLabels);
425 for(a = 0; a < aNumTransactions; a++) {
429 undoInternal(false, false);
432 } else { // abort the current
433 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
434 myTransactions.pop_back();
435 if (!myNestedNum.empty())
436 (*myNestedNum.rbegin())--;
437 // roll back the needed number of transactions
438 // make commit/undo to get the modification delta
439 //myDoc->AbortCommand();
440 if (myDoc->CommitCommand()) {
441 modifiedLabels(myDoc, aDeltaLabels);
444 for(int a = 0; a < aNumTransactions; a++) {
445 modifiedLabels(myDoc, aDeltaLabels);
450 // abort for all subs, flushes will be later, in the end of root abort
451 const std::set<std::string> aSubs = subDocuments(true);
452 std::set<std::string>::iterator aSubIter = aSubs.begin();
453 for (; aSubIter != aSubs.end(); aSubIter++)
454 subDoc(*aSubIter)->abortOperation();
455 // references may be changed because they are set in attributes on the fly
456 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
459 bool Model_Document::isOperation() const
461 // operation is opened for all documents: no need to check subs
462 return myDoc->HasOpenCommand() == Standard_True ;
465 bool Model_Document::isModified()
467 // is modified if at least one operation was commited and not undoed
468 return myTransactions.size() != myTransactionSave || isOperation();
471 bool Model_Document::canUndo()
473 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
474 int aCurrentNum = isOperation() ? 1 : 0;
475 if (myDoc->GetAvailableUndos() > 0 &&
476 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
477 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
479 // check other subs contains operation that can be undoed
480 const std::set<std::string> aSubs = subDocuments(true);
481 std::set<std::string>::iterator aSubIter = aSubs.begin();
482 for (; aSubIter != aSubs.end(); aSubIter++) {
483 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
484 if (aSub->myObjs) {// if it was not closed before
493 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
495 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
496 myRedos.push_back(*myTransactions.rbegin());
497 myTransactions.pop_back();
498 if (!myNestedNum.empty())
499 (*myNestedNum.rbegin())--;
500 // roll back the needed number of transactions
501 TDF_LabelList aDeltaLabels;
502 for(int a = 0; a < aNumTransactions; a++) {
504 modifiedLabels(myDoc, aDeltaLabels);
510 const std::set<std::string> aSubs = subDocuments(true);
511 std::set<std::string>::iterator aSubIter = aSubs.begin();
512 for (; aSubIter != aSubs.end(); aSubIter++) {
513 if (!subDoc(*aSubIter)->myObjs)
515 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
518 // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
519 if (theSynchronize) {
520 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
521 // update the current features status
522 setCurrentFeature(currentFeature(false), false);
526 void Model_Document::undo()
528 undoInternal(true, true);
531 bool Model_Document::canRedo()
533 if (!myRedos.empty())
535 // check other subs contains operation that can be redoed
536 const std::set<std::string> aSubs = subDocuments(true);
537 std::set<std::string>::iterator aSubIter = aSubs.begin();
538 for (; aSubIter != aSubs.end(); aSubIter++) {
539 if (!subDoc(*aSubIter)->myObjs)
541 if (subDoc(*aSubIter)->canRedo())
547 void Model_Document::redo()
549 if (!myNestedNum.empty())
550 (*myNestedNum.rbegin())++;
551 int aNumRedos = myRedos.rbegin()->myOCAFNum;
552 myTransactions.push_back(*myRedos.rbegin());
554 TDF_LabelList aDeltaLabels;
555 for(int a = 0; a < aNumRedos; a++) {
556 modifiedLabels(myDoc, aDeltaLabels, true);
561 const std::set<std::string> aSubs = subDocuments(true);
562 std::set<std::string>::iterator aSubIter = aSubs.begin();
563 for (; aSubIter != aSubs.end(); aSubIter++)
564 subDoc(*aSubIter)->redo();
566 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
567 myObjs->synchronizeFeatures(aDeltaLabels, true, isRoot());
568 // update the current features status
569 setCurrentFeature(currentFeature(false), false);
572 std::list<std::string> Model_Document::undoList() const
574 std::list<std::string> aResult;
575 // the number of skipped current operations (on undo they will be aborted)
576 int aSkipCurrent = isOperation() ? 1 : 0;
577 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
578 int aNumUndo = myTransactions.size();
579 if (!myNestedNum.empty())
580 aNumUndo = *myNestedNum.rbegin();
581 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
582 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
588 std::list<std::string> Model_Document::redoList() const
590 std::list<std::string> aResult;
591 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
592 for( ; aTrIter != myRedos.crend(); aTrIter++) {
593 aResult.push_back(aTrIter->myId);
598 void Model_Document::operationId(const std::string& theId)
600 myTransactions.rbegin()->myId = theId;
603 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
605 std::shared_ptr<Model_Session> aSession =
606 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
607 FeaturePtr aFeature = aSession->createFeature(theID, this);
611 Model_Document* aDocToAdd;
612 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
613 if (aFeature->documentToAdd() != kind()) { // the root document by default
614 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
618 } else { // if customized is not presented, add to "this" document
622 // searching for feature after which must be added the next feature: this is the current feature
623 // but also all sub-features of this feature
624 FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
625 bool isModified = true;
626 for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
627 aComp.get() && isModified;
628 aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
630 int aSubs = aComp->numberOfSubs(false);
631 for(int a = 0; a < aSubs; a++) {
632 FeaturePtr aSub = aComp->subFeature(a, false);
633 if (myObjs->isLater(aSub, aCurrent)) {
639 aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
640 if (!aFeature->isAction()) { // do not add action to the data model
641 if (theMakeCurrent) // after all this feature stays in the document, so make it current
642 aDocToAdd->setCurrentFeature(aFeature, false);
643 } else { // feature must be executed
644 // no creation event => updater not working, problem with remove part
652 void Model_Document::refsToFeature(FeaturePtr theFeature,
653 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
655 myObjs->refsToFeature(theFeature, theRefs, isSendError);
658 void Model_Document::removeFeature(FeaturePtr theFeature)
660 myObjs->removeFeature(theFeature);
663 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
665 myObjs->moveFeature(theMoved, theAfterThis);
666 if (theAfterThis == currentFeature(true))
667 setCurrentFeature(theMoved, true);
670 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
672 myObjs->updateHistory(theObject);
675 void Model_Document::updateHistory(const std::string theGroup)
677 myObjs->updateHistory(theGroup);
680 std::shared_ptr<ModelAPI_Document> Model_Document::subDocument(std::string theDocID)
682 return Model_Application::getApplication()->getDocument(theDocID);
685 const std::set<std::string> Model_Document::subDocuments(const bool theActivatedOnly) const
687 std::set<std::string> aResult;
688 std::list<ResultPtr> aPartResults;
689 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
690 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
691 for(; aPartRes != aPartResults.end(); aPartRes++) {
692 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
693 if (aPart && (!theActivatedOnly || aPart->isActivated())) {
694 aResult.insert(aPart->original()->data()->name());
700 std::shared_ptr<Model_Document> Model_Document::subDoc(std::string theDocID)
702 // just store sub-document identifier here to manage it later
703 return std::dynamic_pointer_cast<Model_Document>(
704 Model_Application::getApplication()->getDocument(theDocID));
707 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
709 return myObjs->object(theGroupID, theIndex);
712 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
713 const std::string& theGroupID, const std::string& theName)
715 return myObjs->objectByName(theGroupID, theName);
718 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
720 return myObjs->index(theObject);
723 int Model_Document::size(const std::string& theGroupID)
725 return myObjs->size(theGroupID);
728 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
730 if (!myObjs) // on close document feature destruction it may call this method
731 return std::shared_ptr<ModelAPI_Feature>();
732 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
733 Handle(TDF_Reference) aRef;
734 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
735 TDF_Label aLab = aRef->Get();
736 FeaturePtr aResult = myObjs->feature(aLab);
737 if (theVisible) { // get nearest visible (in history) going up
738 while(aResult.get() && // sub-composites are never in history
739 (!aResult->isInHistory() || ModelAPI_Tools::compositeOwner(aResult).get())) {
740 aResult = myObjs->nextFeature(aResult, true);
745 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
748 void Model_Document::setCurrentFeature(std::shared_ptr<ModelAPI_Feature> theCurrent,
749 const bool theVisible, const bool theFlushUpdates)
751 // blocks the flush signals to avoid each objects visualization in the viewer
752 // they should not be shown once after all modifications are performed
753 Events_Loop* aLoop = Events_Loop::loop();
754 bool isActive = aLoop->activateFlushes(false);
756 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
757 CompositeFeaturePtr aMain; // main feature that may nest the new current
758 if (theCurrent.get()) {
759 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
761 // if feature nests into compisite feature, make the composite feature as current
762 const std::set<AttributePtr>& aRefsToMe = theCurrent->data()->refsToMe();
763 std::set<AttributePtr>::const_iterator aRefToMe = aRefsToMe.begin();
764 for(; aRefToMe != aRefsToMe.end(); aRefToMe++) {
765 CompositeFeaturePtr aComposite =
766 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>((*aRefToMe)->owner());
767 if (aComposite.get() && aComposite->isSub(theCurrent)) {
775 if (theVisible) { // make features below which are not in history also enabled: sketch subs
777 theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
778 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
779 if (aNext->isInHistory()) {
780 break; // next in history is not needed
781 } else { // next not in history is good for making current
786 if (theCurrent.get()) {
787 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
788 if (!aData.get() || !aData->isValid()) {
789 aLoop->activateFlushes(isActive);
792 TDF_Label aFeatureLabel = aData->label().Father();
794 Handle(TDF_Reference) aRef;
795 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
796 aRef->Set(aFeatureLabel);
798 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
800 } else { // remove reference for the null feature
801 aRefLab.ForgetAttribute(TDF_Reference::GetID());
803 // make all features after this feature disabled in reversed order (to remove results without deps)
804 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
805 static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
806 static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
808 bool aPassed = false; // flag that the current object is already passed in cycle
809 FeaturePtr anIter = myObjs->lastFeature();
810 bool aWasChanged = false;
811 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
812 // check this before passed become enabled: the current feature is enabled!
813 if (anIter == theCurrent) aPassed = true;
815 bool aDisabledFlag = !aPassed;
816 if (aMain.get() && aMain->isSub(anIter)) // sub-elements of not-disabled feature are not disabled
817 aDisabledFlag = false;
818 if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
819 if (theCurrent.get() && theCurrent->getKind() != "Parameter")
820 aDisabledFlag = false;
822 if (anIter->setDisabled(aDisabledFlag)) {
823 // state of feature is changed => so feature become updated
824 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
825 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
826 // flush is in the end of this method
827 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
830 // update for everyone the concealment flag immideately: on edit feature in the midle of history
832 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = anIter->results();
833 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
834 for(; aRes != aResList.end(); aRes++) {
835 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
836 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
841 // unblock the flush signals and up them after this
842 aLoop->activateFlushes(isActive);
844 if (theFlushUpdates) {
845 aLoop->flush(aCreateEvent);
846 aLoop->flush(aRedispEvent);
847 aLoop->flush(aDeleteEvent);
851 void Model_Document::setCurrentFeatureUp()
853 // on remove just go up for minimum step: highlight external objects in sketch causes
854 // problems if it is true: here and in "setCurrentFeature"
855 FeaturePtr aCurrent = currentFeature(false);
856 if (aCurrent.get()) { // if not, do nothing because null is the upper
857 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
858 // do not flush: it is called only on remove, it will be flushed in the end of transaction
859 setCurrentFeature(aPrev, false, false);
863 TDF_Label Model_Document::generalLabel() const
865 return myDoc->Main().FindChild(TAG_GENERAL);
868 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
869 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
871 return myObjs->createConstruction(theFeatureData, theIndex);
874 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
875 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
877 return myObjs->createBody(theFeatureData, theIndex);
880 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
881 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
883 return myObjs->createPart(theFeatureData, theIndex);
886 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
887 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
888 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
890 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
893 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
894 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
896 return myObjs->createGroup(theFeatureData, theIndex);
899 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
900 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
902 return myObjs->createParameter(theFeatureData, theIndex);
905 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
906 const std::shared_ptr<ModelAPI_Result>& theResult)
908 return myObjs->feature(theResult);
911 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
913 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
916 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
918 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
921 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
923 myNamingNames[theName] = theLabel;
926 TDF_Label Model_Document::findNamingName(std::string theName)
928 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
929 if (aFind == myNamingNames.end())
930 return TDF_Label(); // not found
931 return aFind->second;
934 ResultPtr Model_Document::findByName(const std::string theName)
936 return myObjs->findByName(theName);
939 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
941 return myObjs->allFeatures();
944 void Model_Document::setActive(const bool theFlag)
946 if (theFlag != myIsActive) {
947 myIsActive = theFlag;
948 // redisplay all the objects of this part
949 static Events_Loop* aLoop = Events_Loop::loop();
950 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
952 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
953 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
954 object(ModelAPI_Feature::group(), a));
955 if (aFeature.get() && aFeature->data()->isValid()) {
956 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
957 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
958 for(; aRes != aResList.end(); aRes++) {
959 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
966 bool Model_Document::isActive() const
971 int Model_Document::transactionID()
973 Handle(TDataStd_Integer) anIndex;
974 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
975 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
976 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
978 return anIndex->Get();
981 void Model_Document::incrementTransactionID()
983 int aNewVal = transactionID() + 1;
984 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
986 void Model_Document::decrementTransactionID()
988 int aNewVal = transactionID() - 1;
989 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
992 bool Model_Document::isOpened()
994 return myObjs && !myDoc.IsNull();
997 int Model_Document::numInternalFeatures()
999 return myObjs->numInternalFeatures();
1002 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
1004 return myObjs->internalFeature(theIndex);
1007 void Model_Document::synchronizeTransactions()
1009 Model_Document* aRoot =
1010 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
1012 return; // don't need to synchronise root with root
1014 std::shared_ptr<Model_Session> aSession =
1015 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
1016 while(myRedos.size() > aRoot->myRedos.size()) { // remove redos in this
1017 aSession->setCheckTransactions(false);
1019 aSession->setCheckTransactions(true);
1021 /* this case can not be reproduced in any known case for the current moment, so, just comment
1022 while(myRedos.size() < aRoot->myRedos.size()) { // add more redos in this
1023 undoInternal(false, true);
1027 // Feature that is used for selection in the Part document by the external request
1028 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1030 /// Nothing to do in constructor
1031 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1033 /// Returns the unique kind of a feature
1034 virtual const std::string& getKind() {
1035 static std::string MY_KIND("InternalSelectionInPartFeature");
1038 /// Request for initialization of data model of the object: adding all attributes
1039 virtual void initAttributes() {
1040 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1042 /// Nothing to do in the execution function
1043 virtual void execute() {}
1047 //! Returns the feature that is used for calculation of selection externally from the document
1048 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1050 // return already created, otherwise create
1051 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1053 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1055 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1056 std::shared_ptr<Model_Data> aData(new Model_Data);
1057 aData->setLabel(aFeatureLab.FindChild(1));
1058 aData->setObject(mySelectionFeature);
1059 mySelectionFeature->setDoc(myObjs->owner());
1060 mySelectionFeature->setData(aData);
1061 std::string aName = id() + "_Part";
1062 mySelectionFeature->data()->setName(aName);
1063 mySelectionFeature->setDoc(myObjs->owner());
1064 mySelectionFeature->initAttributes();
1066 return mySelectionFeature->selectionList("selection");
1069 FeaturePtr Model_Document::lastFeature()
1072 return myObjs->lastFeature();
1073 return FeaturePtr();