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>
18 #include <ModelAPI_ResultBody.h>
19 #include <Events_Loop.h>
20 #include <Events_InfoMessage.h>
22 #include <TDataStd_Integer.hxx>
23 #include <TDataStd_Comment.hxx>
24 #include <TDF_ChildIDIterator.hxx>
25 #include <TDataStd_ReferenceArray.hxx>
26 #include <TDataStd_ReferenceList.hxx>
27 #include <TDataStd_IntegerArray.hxx>
28 #include <TDataStd_HLabelArray1.hxx>
29 #include <TDataStd_Name.hxx>
30 #include <TDataStd_AsciiString.hxx>
31 #include <TDF_Reference.hxx>
32 #include <TDF_ChildIDIterator.hxx>
33 #include <TDF_LabelMapHasher.hxx>
34 #include <TDF_Delta.hxx>
35 #include <TDF_AttributeDelta.hxx>
36 #include <TDF_AttributeDeltaList.hxx>
37 #include <TDF_ListIteratorOfAttributeDeltaList.hxx>
38 #include <TDF_ListIteratorOfLabelList.hxx>
39 #include <TDF_LabelMap.hxx>
40 #include <TNaming_SameShapeIterator.hxx>
41 #include <TNaming_Iterator.hxx>
42 #include <TNaming_NamedShape.hxx>
43 #include <TNaming_Tool.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <TopoDS_Shape.hxx>
48 #include <OSD_File.hxx>
49 #include <OSD_Path.hxx>
57 # define _separator_ '\\'
59 # define _separator_ '/'
62 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
64 static const int TAG_GENERAL = 1; // general properties tag
67 static const int TAG_CURRENT_FEATURE = 1; ///< where the reference to the current feature label is located (or no attribute if null feature)
68 static const int TAG_CURRENT_TRANSACTION = 2; ///< integer, index of the transaction
69 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
71 Model_Document::Model_Document(const int theID, const std::string theKind)
72 : myID(theID), myKind(theKind), myIsActive(false),
73 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
75 myObjs = new Model_Objects(myDoc->Main());
76 myDoc->SetUndoLimit(UNDO_LIMIT);
77 myTransactionSave = 0;
78 myExecuteFeatures = true;
79 // to have something in the document and avoid empty doc open/save problem
80 // in transaction for nesting correct working
82 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
83 // this to avoid creation of integer attribute outside the transaction after undo
85 myDoc->CommitCommand();
88 void Model_Document::setThis(DocumentPtr theDoc)
90 myObjs->setOwner(theDoc);
93 /// Returns the file name of this document by the name of directory and identifier of a document
94 static TCollection_ExtendedString DocFileName(const char* theDirName, const std::string& theID)
96 TCollection_ExtendedString aPath((const Standard_CString) theDirName);
97 // remove end-separators
98 while(aPath.Length() &&
99 (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
100 aPath.Remove(aPath.Length());
101 aPath += _separator_;
102 aPath += theID.c_str();
103 aPath += ".cbf"; // standard binary file extension
107 bool Model_Document::isRoot() const
109 return this == Model_Session::get()->moduleDocument().get();
112 bool Model_Document::load(const char* theDirName, const char* theFileName, DocumentPtr theThis)
114 Handle(Model_Application) anApp = Model_Application::getApplication();
116 anApp->setLoadPath(theDirName);
118 TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
119 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
120 Handle(TDocStd_Document) aLoaded;
122 aStatus = anApp->Open(aPath, aLoaded);
123 } catch (Standard_Failure) {
124 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
125 Events_InfoMessage("Model_Document",
126 "Exception in opening of document: %1").arg(aFail->GetMessageString()).send();
129 bool isError = aStatus != PCDM_RS_OK;
132 case PCDM_RS_UnknownDocument:
133 Events_InfoMessage("Model_Document", "Can not open document").send();
135 case PCDM_RS_AlreadyRetrieved:
136 Events_InfoMessage("Model_Document", "Can not open document: already opened").send();
138 case PCDM_RS_AlreadyRetrievedAndModified:
139 Events_InfoMessage("Model_Document",
140 "Can not open document: already opened and modified").send();
142 case PCDM_RS_NoDriver:
143 Events_InfoMessage("Model_Document", "Can not open document: driver library is not found").send();
145 case PCDM_RS_UnknownFileDriver:
146 Events_InfoMessage("Model_Document", "Can not open document: unknown driver for opening").send();
148 case PCDM_RS_OpenError:
149 Events_InfoMessage("Model_Document", "Can not open document: file open error").send();
151 case PCDM_RS_NoVersion:
152 Events_InfoMessage("Model_Document", "Can not open document: invalid version").send();
154 case PCDM_RS_NoModel:
155 Events_InfoMessage("Model_Document", "Can not open document: no data model").send();
157 case PCDM_RS_NoDocument:
158 Events_InfoMessage("Model_Document", "Can not open document: no document inside").send();
160 case PCDM_RS_FormatFailure:
161 Events_InfoMessage("Model_Document", "Can not open document: format failure").send();
163 case PCDM_RS_TypeNotFoundInSchema:
164 Events_InfoMessage("Model_Document", "Can not open document: invalid object").send();
166 case PCDM_RS_UnrecognizedFileFormat:
167 Events_InfoMessage("Model_Document", "Can not open document: unrecognized file format").send();
169 case PCDM_RS_MakeFailure:
170 Events_InfoMessage("Model_Document", "Can not open document: make failure").send();
172 case PCDM_RS_PermissionDenied:
173 Events_InfoMessage("Model_Document", "Can not open document: permission denied").send();
175 case PCDM_RS_DriverFailure:
176 Events_InfoMessage("Model_Document", "Can not open document: driver failure").send();
179 Events_InfoMessage("Model_Document", "Can not open document: unknown error").send();
183 std::shared_ptr<Model_Session> aSession =
184 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
187 myDoc->SetUndoLimit(UNDO_LIMIT);
188 // to avoid the problem that feature is created in the current, not this, document
189 aSession->setActiveDocument(anApp->document(myID), false);
190 aSession->setCheckTransactions(false);
193 myObjs = new Model_Objects(myDoc->Main()); // synchronisation is inside
194 myObjs->setOwner(theThis);
195 // update the current features status
196 setCurrentFeature(currentFeature(false), false);
197 aSession->setCheckTransactions(true);
198 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
199 // this is done in Part result "activate", so no needed here. Causes not-blue active part.
200 // aSession->setActiveDocument(anApp->getDocument(myID), true);
202 // make sub-parts as loaded by demand
203 std::list<ResultPtr> aPartResults;
204 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
205 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
206 for(; aPartRes != aPartResults.end(); aPartRes++) {
207 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
209 anApp->setLoadByDemand(aPart->data()->name());
212 } else { // open failed, but new documnet was created to work with it: inform the model
213 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
218 bool Model_Document::save(
219 const char* theDirName, const char* theFileName, std::list<std::string>& theResults)
221 // create a directory in the root document if it is not yet exist
222 Handle(Model_Application) anApp = Model_Application::getApplication();
225 CreateDirectory(theFileName, NULL);
227 mkdir(theFileName, 0x1ff);
230 // filename in the dir is id of document inside of the given directory
231 TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
232 PCDM_StoreStatus aStatus;
234 aStatus = anApp->SaveAs(myDoc, aPath);
235 } catch (Standard_Failure) {
236 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
237 Events_InfoMessage("Model_Document",
238 "Exception in saving of document: %1").arg(aFail->GetMessageString()).send();
241 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
244 case PCDM_SS_DriverFailure:
245 Events_InfoMessage("Model_Document", "Can not save document: save driver-library failure").send();
247 case PCDM_SS_WriteFailure:
248 Events_InfoMessage("Model_Document", "Can not save document: file writing failure").send();
250 case PCDM_SS_Failure:
252 Events_InfoMessage("Model_Document", "Can not save document").send();
256 myTransactionSave = int(myTransactions.size());
257 if (isDone) { // save also sub-documents if any
258 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
259 // iterate all result parts to find all loaded or not yet loaded documents
260 std::list<ResultPtr> aPartResults;
261 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
262 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
263 for(; aPartRes != aPartResults.end(); aPartRes++) {
264 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
265 if (!aPart->isActivated()) {
266 // copy not-activated document that is not in the memory
267 std::string aDocName = aPart->data()->name();
268 if (!aDocName.empty()) {
270 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
271 OSD_Path aPath(aSubPath);
272 OSD_File aFile(aPath);
273 if (aFile.Exists()) {
274 TCollection_AsciiString aDestinationDir(DocFileName(theDirName, aDocName));
275 OSD_Path aDestination(aDestinationDir);
276 aFile.Copy(aDestination);
277 theResults.push_back(aDestinationDir.ToCString());
279 Events_InfoMessage("Model_Document",
280 "Can not open file %1 for saving").arg(aSubPath.ToCString()).send();
283 } else { // simply save opened document
284 isDone = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc())->
285 save(theDirName, aPart->data()->name().c_str(), theResults);
292 void Model_Document::close(const bool theForever)
294 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
295 if (!isRoot() && this == aPM->activeDocument().get()) {
296 aPM->setActiveDocument(aPM->moduleDocument());
297 } else if (isRoot()) {
298 // erase the active document if root is closed
299 aPM->setActiveDocument(DocumentPtr());
302 const std::set<int> aSubs = subDocuments();
303 std::set<int>::iterator aSubIter = aSubs.begin();
304 for (; aSubIter != aSubs.end(); aSubIter++) {
305 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
306 if (aSub->myObjs) // if it was not closed before
307 aSub->close(theForever);
310 // close for thid document needs no transaction in this document
311 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
313 // close all only if it is really asked, otherwise it can be undoed/redoed
315 // flush everything to avoid messages with bad objects
318 if (myDoc->CanClose() == CDM_CCS_OK)
320 mySelectionFeature.reset();
322 setCurrentFeature(FeaturePtr(), false); // disables all features
323 // update the OB: features are disabled (on remove of Part)
324 Events_Loop* aLoop = Events_Loop::loop();
325 static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
326 aLoop->flush(aDeleteEvent);
329 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
332 void Model_Document::startOperation()
334 incrementTransactionID(); // outside of transaction in order to avoid empty transactions keeping
335 if (myDoc->HasOpenCommand()) { // start of nested command
336 if (myDoc->CommitCommand()) { // commit the current: it will contain all nested after compactification
337 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
339 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
340 myDoc->OpenCommand();
341 } else { // start the simple command
344 // starts a new operation
345 myTransactions.push_back(Transaction());
346 if (!myNestedNum.empty())
347 (*myNestedNum.rbegin())++;
349 // new command for all subs
350 const std::set<int> aSubs = subDocuments();
351 std::set<int>::iterator aSubIter = aSubs.begin();
352 for (; aSubIter != aSubs.end(); aSubIter++)
353 subDoc(*aSubIter)->startOperation();
356 void Model_Document::compactNested()
358 if (!myNestedNum.empty()) {
359 int aNumToCompact = *(myNestedNum.rbegin());
360 int aSumOfTransaction = 0;
361 for(int a = 0; a < aNumToCompact; a++) {
362 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
363 myTransactions.pop_back();
365 // the latest transaction is the start of lower-level operation which startes the nested
366 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
367 myNestedNum.pop_back();
371 /// Compares the content of the given attributes, returns true if equal.
372 /// This method is used to avoid empty transactions when only "current" is changed
373 /// to some value and then comes back in this transaction, so, it compares only
374 /// references and Boolean and Integer Arrays for the current moment.
375 static bool isEqualContent(Handle(TDF_Attribute) theAttr1, Handle(TDF_Attribute) theAttr2)
377 if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_Reference::GetID())) { // reference
378 Handle(TDF_Reference) aRef1 = Handle(TDF_Reference)::DownCast(theAttr1);
379 Handle(TDF_Reference) aRef2 = Handle(TDF_Reference)::DownCast(theAttr2);
380 if (aRef1.IsNull() && aRef2.IsNull())
382 if (aRef1.IsNull() || aRef2.IsNull())
384 return aRef1->Get().IsEqual(aRef2->Get()) == Standard_True;
385 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_BooleanArray::GetID())) {
386 Handle(TDataStd_BooleanArray) anArr1 = Handle(TDataStd_BooleanArray)::DownCast(theAttr1);
387 Handle(TDataStd_BooleanArray) anArr2 = Handle(TDataStd_BooleanArray)::DownCast(theAttr2);
388 if (anArr1.IsNull() && anArr2.IsNull())
390 if (anArr1.IsNull() || anArr2.IsNull())
392 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
393 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
394 if (a != 1 && anArr1->Value(a) != anArr2->Value(a)) // second is for display
398 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_IntegerArray::GetID())) {
399 Handle(TDataStd_IntegerArray) anArr1 = Handle(TDataStd_IntegerArray)::DownCast(theAttr1);
400 Handle(TDataStd_IntegerArray) anArr2 = Handle(TDataStd_IntegerArray)::DownCast(theAttr2);
401 if (anArr1.IsNull() && anArr2.IsNull())
403 if (anArr1.IsNull() || anArr2.IsNull())
405 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
406 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
407 if (anArr1->Value(a) != anArr2->Value(a)) {
408 // avoid the transaction ID checking
409 if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
410 (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
416 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceArray::GetID())) {
417 Handle(TDataStd_ReferenceArray) anArr1 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr1);
418 Handle(TDataStd_ReferenceArray) anArr2 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr2);
419 if (anArr1.IsNull() && anArr2.IsNull())
421 if (anArr1.IsNull() || anArr2.IsNull())
423 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
424 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
425 if (anArr1->Value(a) != anArr2->Value(a)) {
426 // avoid the transaction ID checking
427 if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
428 (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
434 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceList::GetID())) {
435 Handle(TDataStd_ReferenceList) aList1 = Handle(TDataStd_ReferenceList)::DownCast(theAttr1);
436 Handle(TDataStd_ReferenceList) aList2= Handle(TDataStd_ReferenceList)::DownCast(theAttr2);
437 if (aList1.IsNull() && aList2.IsNull())
439 if (aList1.IsNull() || aList2.IsNull())
441 const TDF_LabelList& aLList1 = aList1->List();
442 const TDF_LabelList& aLList2 = aList2->List();
443 TDF_ListIteratorOfLabelList aLIter1(aLList1);
444 TDF_ListIteratorOfLabelList aLIter2(aLList2);
445 for(; aLIter1.More() && aLIter2.More(); aLIter1.Next(), aLIter2.Next()) {
446 if (aLIter1.Value() != aLIter2.Value())
449 return !aLIter1.More() && !aLIter2.More(); // both lists are with the same size
450 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_TagSource::GetID())) {
451 return true; // it just for created and removed feature: nothing is changed
456 /// Returns true if the last transaction is actually empty: modification to te same values
457 /// were performed only
458 static bool isEmptyTransaction(const Handle(TDocStd_Document)& theDoc) {
459 Handle(TDF_Delta) aDelta;
460 aDelta = theDoc->GetUndos().Last();
461 TDF_LabelList aDeltaList;
462 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
463 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
466 // add also label of the modified attributes
467 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
468 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
469 Handle(TDF_AttributeDelta)& anADelta = anAttr.Value();
470 Handle(TDF_DeltaOnAddition) anAddition = Handle(TDF_DeltaOnAddition)::DownCast(anADelta);
471 if (anAddition.IsNull()) { // if the attribute was added, transaction is not empty
472 if (!anADelta->Label().IsNull() && !anADelta->Attribute().IsNull()) {
473 Handle(TDF_Attribute) aCurrentAttr;
474 if (anADelta->Label().FindAttribute(anADelta->Attribute()->ID(), aCurrentAttr)) {
475 if (isEqualContent(anADelta->Attribute(), aCurrentAttr)) {
476 continue; // attribute is not changed actually
478 } else if (Standard_GUID::IsEqual(anADelta->Attribute()->ID(), TDataStd_AsciiString::GetID())) {
479 continue; // error message is disappeared
488 bool Model_Document::finishOperation()
490 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
491 static std::shared_ptr<Model_Session> aSession =
492 std::static_pointer_cast<Model_Session>(Model_Session::get());
493 // do it before flashes to enable and recompute nesting features correctly
494 if (myNestedNum.empty() || (isNestedClosed && myNestedNum.size() == 1)) {
495 // if all nested operations are closed, make current the higher level objects (to perform
496 // it in the python scripts correctly): sketch become current after creation ofsub-elements
497 FeaturePtr aCurrent = currentFeature(false);
498 CompositeFeaturePtr aMain, aNext = ModelAPI_Tools::compositeOwner(aCurrent);
501 aNext = ModelAPI_Tools::compositeOwner(aMain);
503 if (aMain.get() && aMain != aCurrent)
504 setCurrentFeature(aMain, false);
506 myObjs->synchronizeBackRefs();
507 Events_Loop* aLoop = Events_Loop::loop();
508 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
509 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
510 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
511 aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
512 // this must be here just after everything is finished but before real transaction stop
513 // to avoid messages about modifications outside of the transaction
514 // and to rebuild everything after all updates and creates
515 if (isRoot()) { // once for root document
516 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
517 static std::shared_ptr<Events_Message> aFinishMsg
518 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
519 Events_Loop::loop()->send(aFinishMsg);
520 Events_Loop::loop()->autoFlush(Events_Loop::eventByName(EVENT_OBJECT_UPDATED), false);
522 // to avoid "updated" message appearance by updater
523 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
525 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
526 bool aResult = false;
527 const std::set<int> aSubs = subDocuments();
528 std::set<int>::iterator aSubIter = aSubs.begin();
529 for (; aSubIter != aSubs.end(); aSubIter++)
530 if (subDoc(*aSubIter)->finishOperation())
533 // transaction may be empty if this document was created during this transaction (create part)
534 if (!myTransactions.empty() && myDoc->CommitCommand()) { // if commit is successfull, just increment counters
535 if (isEmptyTransaction(myDoc)) { // erase this transaction
539 myTransactions.rbegin()->myOCAFNum++;
544 if (isNestedClosed) {
547 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
548 aResult = myTransactions.rbegin()->myOCAFNum != 0;
550 if (!aResult && isRoot()) {
551 // nothing inside in all documents, so remove this transaction from the transactions list
552 undoInternal(true, false);
554 // on finish clear redos in any case (issue 446) and for all subs (issue 408)
557 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
558 subDoc(*aSubIter)->myDoc->ClearRedos();
559 subDoc(*aSubIter)->myRedos.clear();
565 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
566 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
567 const bool isRedo = false) {
568 Handle(TDF_Delta) aDelta;
570 aDelta = theDoc->GetRedos().First();
572 aDelta = theDoc->GetUndos().Last();
573 TDF_LabelList aDeltaList;
574 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
575 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
576 theDelta.Append(aListIter.Value());
578 // add also label of the modified attributes
579 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
580 TDF_LabelMap anExcludedInt; /// named shape evolution also modifies integer on this label: exclude it
581 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
582 if (anAttr.Value()->Attribute()->ID() == TDataStd_BooleanArray::GetID()) {
583 continue; // Boolean array is used for feature auxiliary attributes only, feature args are not modified
585 if (anAttr.Value()->Attribute()->ID() == TNaming_NamedShape::GetID()) {
586 anExcludedInt.Add(anAttr.Value()->Label());
587 continue; // named shape evolution is changed in history update => skip them, they are not the features arguents
589 if (anAttr.Value()->Attribute()->ID() == TDataStd_Integer::GetID()) {
590 if (anExcludedInt.Contains(anAttr.Value()->Label()))
593 theDelta.Append(anAttr.Value()->Label());
595 TDF_ListIteratorOfLabelList aDeltaIter(theDelta);
596 for(; aDeltaIter.More(); aDeltaIter.Next()) {
597 if (anExcludedInt.Contains(aDeltaIter.Value())) {
598 theDelta.Remove(aDeltaIter);
599 if (!aDeltaIter.More())
605 void Model_Document::abortOperation()
607 TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
608 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
610 // store undo-delta here as undo actually does in the method later
611 int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
612 for(a = 0; a < aNumTransactions; a++) {
613 modifiedLabels(myDoc, aDeltaLabels);
616 for(a = 0; a < aNumTransactions; a++) {
620 undoInternal(false, false);
623 } else { // abort the current
624 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
625 myTransactions.pop_back();
626 if (!myNestedNum.empty())
627 (*myNestedNum.rbegin())--;
628 // roll back the needed number of transactions
629 //myDoc->AbortCommand();
630 // instead of abort, do commit and undo: to get the delta of modifications
631 if (myDoc->CommitCommand()) {
632 modifiedLabels(myDoc, aDeltaLabels);
635 for(int a = 0; a < aNumTransactions; a++) {
636 modifiedLabels(myDoc, aDeltaLabels);
641 // abort for all subs, flushes will be later, in the end of root abort
642 const std::set<int> aSubs = subDocuments();
643 std::set<int>::iterator aSubIter = aSubs.begin();
644 for (; aSubIter != aSubs.end(); aSubIter++)
645 subDoc(*aSubIter)->abortOperation();
646 // references may be changed because they are set in attributes on the fly
647 myObjs->synchronizeFeatures(aDeltaLabels, true, false, isRoot());
650 bool Model_Document::isOperation() const
652 // operation is opened for all documents: no need to check subs
653 return myDoc->HasOpenCommand() == Standard_True ;
656 bool Model_Document::isModified()
658 // is modified if at least one operation was commited and not undoed
659 return myTransactions.size() != myTransactionSave || isOperation();
662 bool Model_Document::canUndo()
664 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
665 int aCurrentNum = isOperation() ? 1 : 0;
666 if (myDoc->GetAvailableUndos() > 0 &&
667 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) && // there is something to undo in nested
668 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
670 // check other subs contains operation that can be undoed
671 const std::set<int> aSubs = subDocuments();
672 std::set<int>::iterator aSubIter = aSubs.begin();
673 for (; aSubIter != aSubs.end(); aSubIter++) {
674 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
675 if (aSub->myObjs) {// if it was not closed before
684 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
686 if (myTransactions.empty())
688 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
689 myRedos.push_back(*myTransactions.rbegin());
690 myTransactions.pop_back();
691 if (!myNestedNum.empty())
692 (*myNestedNum.rbegin())--;
693 // roll back the needed number of transactions
694 TDF_LabelList aDeltaLabels;
695 for(int a = 0; a < aNumTransactions; a++) {
697 modifiedLabels(myDoc, aDeltaLabels);
703 const std::set<int> aSubs = subDocuments();
704 std::set<int>::iterator aSubIter = aSubs.begin();
705 for (; aSubIter != aSubs.end(); aSubIter++) {
706 if (!subDoc(*aSubIter)->myObjs)
708 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
711 // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
712 if (theSynchronize) {
713 myObjs->synchronizeFeatures(aDeltaLabels, true, false, isRoot());
714 // update the current features status
715 setCurrentFeature(currentFeature(false), false);
719 void Model_Document::undo()
721 undoInternal(true, true);
724 bool Model_Document::canRedo()
726 if (!myRedos.empty())
728 // check other subs contains operation that can be redoed
729 const std::set<int> aSubs = subDocuments();
730 std::set<int>::iterator aSubIter = aSubs.begin();
731 for (; aSubIter != aSubs.end(); aSubIter++) {
732 if (!subDoc(*aSubIter)->myObjs)
734 if (subDoc(*aSubIter)->canRedo())
740 void Model_Document::redo()
742 if (!myNestedNum.empty())
743 (*myNestedNum.rbegin())++;
744 int aNumRedos = myRedos.rbegin()->myOCAFNum;
745 myTransactions.push_back(*myRedos.rbegin());
747 TDF_LabelList aDeltaLabels;
748 for(int a = 0; a < aNumRedos; a++) {
749 modifiedLabels(myDoc, aDeltaLabels, true);
754 const std::set<int> aSubs = subDocuments();
755 std::set<int>::iterator aSubIter = aSubs.begin();
756 for (; aSubIter != aSubs.end(); aSubIter++)
757 subDoc(*aSubIter)->redo();
759 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
760 myObjs->synchronizeFeatures(aDeltaLabels, true, false, isRoot());
761 // update the current features status
762 setCurrentFeature(currentFeature(false), false);
765 std::list<std::string> Model_Document::undoList() const
767 std::list<std::string> aResult;
768 // the number of skipped current operations (on undo they will be aborted)
769 int aSkipCurrent = isOperation() ? 1 : 0;
770 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
771 int aNumUndo = int(myTransactions.size());
772 if (!myNestedNum.empty())
773 aNumUndo = *myNestedNum.rbegin();
774 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
775 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
781 std::list<std::string> Model_Document::redoList() const
783 std::list<std::string> aResult;
784 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
785 for( ; aTrIter != myRedos.crend(); aTrIter++) {
786 aResult.push_back(aTrIter->myId);
791 void Model_Document::operationId(const std::string& theId)
793 myTransactions.rbegin()->myId = theId;
796 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
798 std::shared_ptr<Model_Session> aSession =
799 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
800 FeaturePtr aFeature = aSession->createFeature(theID, this);
804 Model_Document* aDocToAdd;
805 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
806 if (aFeature->documentToAdd() != kind()) { // the root document by default
807 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
811 } else { // if customized is not presented, add to "this" document
815 // searching for feature after which must be added the next feature: this is the current feature
816 // but also all sub-features of this feature
817 FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
818 bool isModified = true;
819 for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
820 aComp.get() && isModified;
821 aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
823 int aSubs = aComp->numberOfSubs(false);
824 for(int a = 0; a < aSubs; a++) {
825 FeaturePtr aSub = aComp->subFeature(a, false);
826 if (myObjs->isLater(aSub, aCurrent)) {
832 aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
833 if (!aFeature->isAction()) { // do not add action to the data model
834 if (theMakeCurrent) // after all this feature stays in the document, so make it current
835 aDocToAdd->setCurrentFeature(aFeature, false);
836 } else { // feature must be executed
837 // no creation event => updater not working, problem with remove part
845 void Model_Document::refsToFeature(FeaturePtr theFeature,
846 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
848 myObjs->refsToFeature(theFeature, theRefs, isSendError);
851 void Model_Document::removeFeature(FeaturePtr theFeature)
853 myObjs->removeFeature(theFeature);
856 // recursive function to check if theSub is a child of theMain composite feature
857 // through all the hierarchy of parents
858 static bool isSub(const CompositeFeaturePtr theMain, const FeaturePtr theSub) {
859 CompositeFeaturePtr aParent = ModelAPI_Tools::compositeOwner(theSub);
862 if (aParent == theMain)
864 return isSub(theMain, aParent);
868 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
870 bool aCurrentUp = theMoved == currentFeature(false);
872 setCurrentFeatureUp();
874 // if user adds after high-level feature with nested, add it after all nested (otherwise the nested will be disabled)
875 CompositeFeaturePtr aCompositeAfter = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theAfterThis);
876 if (aCompositeAfter.get()) {
877 FeaturePtr aSub = aCompositeAfter;
879 FeaturePtr aNext = myObjs->nextFeature(aSub);
880 if (!isSub(aCompositeAfter, aNext)) {
885 } while (aSub.get());
888 myObjs->moveFeature(theMoved, theAfterThis);
889 if (aCurrentUp) { // make the moved feature enabled or disabled due to the real status
890 setCurrentFeature(currentFeature(false), false);
891 } else if (theAfterThis == currentFeature(false)) {
892 // must be after move to make enabled all features which are before theMoved
893 setCurrentFeature(theMoved, true);
897 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
899 myObjs->updateHistory(theObject);
902 void Model_Document::updateHistory(const std::string theGroup)
904 myObjs->updateHistory(theGroup);
907 const std::set<int> Model_Document::subDocuments() const
909 std::set<int> aResult;
910 std::list<ResultPtr> aPartResults;
911 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
912 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
913 for(; aPartRes != aPartResults.end(); aPartRes++) {
914 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
915 if (aPart && aPart->isActivated()) {
916 aResult.insert(aPart->original()->partDoc()->id());
922 std::shared_ptr<Model_Document> Model_Document::subDoc(int theDocID)
924 // just store sub-document identifier here to manage it later
925 return std::dynamic_pointer_cast<Model_Document>(
926 Model_Application::getApplication()->document(theDocID));
929 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
931 return myObjs->object(theGroupID, theIndex);
934 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
935 const std::string& theGroupID, const std::string& theName)
937 return myObjs->objectByName(theGroupID, theName);
940 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
942 return myObjs->index(theObject);
945 int Model_Document::size(const std::string& theGroupID)
947 if (myObjs == 0) // may be on close
949 return myObjs->size(theGroupID);
952 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
954 if (!myObjs) // on close document feature destruction it may call this method
955 return std::shared_ptr<ModelAPI_Feature>();
956 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
957 Handle(TDF_Reference) aRef;
958 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
959 TDF_Label aLab = aRef->Get();
960 FeaturePtr aResult = myObjs->feature(aLab);
961 if (theVisible) { // get nearest visible (in history) going up
962 while(aResult.get() && !aResult->isInHistory()) {
963 aResult = myObjs->nextFeature(aResult, true);
968 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
971 void Model_Document::setCurrentFeature(
972 std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theVisible)
974 // blocks the flush signals to avoid each objects visualization in the viewer
975 // they should not be shown once after all modifications are performed
976 Events_Loop* aLoop = Events_Loop::loop();
977 bool isActive = aLoop->activateFlushes(false);
979 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
980 CompositeFeaturePtr aMain; // main feature that may nest the new current
981 std::set<FeaturePtr> anOwners; // composites that contain theCurrent (with any level of nesting)
982 if (theCurrent.get()) {
983 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
984 CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theCurrent);
985 while(anOwner.get()) {
989 anOwners.insert(anOwner);
990 anOwner = ModelAPI_Tools::compositeOwner(anOwner);
994 if (theVisible && !theCurrent.get()) { // needed to avoid disabling of PartSet initial constructions
996 theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
997 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
998 if (aNext->isInHistory()) {
999 break; // next in history is not needed
1000 } else { // next not in history is good for making current
1005 if (theCurrent.get()) {
1006 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1007 if (!aData.get() || !aData->isValid()) {
1008 aLoop->activateFlushes(isActive);
1011 TDF_Label aFeatureLabel = aData->label().Father();
1013 Handle(TDF_Reference) aRef;
1014 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1015 aRef->Set(aFeatureLabel);
1017 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
1019 } else { // remove reference for the null feature
1020 aRefLab.ForgetAttribute(TDF_Reference::GetID());
1022 // make all features after this feature disabled in reversed order (to remove results without deps)
1023 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1025 bool aPassed = false; // flag that the current object is already passed in cycle
1026 FeaturePtr anIter = myObjs->lastFeature();
1027 bool aWasChanged = false;
1028 bool isCurrentParameter = theCurrent.get() && theCurrent->getKind() == "Parameter";
1029 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
1030 // check this before passed become enabled: the current feature is enabled!
1031 if (anIter == theCurrent) aPassed = true;
1033 bool aDisabledFlag = !aPassed;
1035 if (isSub(aMain, anIter)) // sub-elements of not-disabled feature are not disabled
1036 aDisabledFlag = false;
1037 else if (anOwners.find(anIter) != anOwners.end()) // disable the higher-level feature is the nested is the current
1038 aDisabledFlag = true;
1041 if (anIter->getKind() == "Parameter") {// parameters are always out of the history of features, but not parameters
1042 // due to the issue 1491 all parameters are kept enabled any time
1043 //if (!isCurrentParameter)
1044 aDisabledFlag = false;
1045 } else if (isCurrentParameter) { // if paramater is active, all other features become enabled (issue 1307)
1046 aDisabledFlag = false;
1049 if (anIter->setDisabled(aDisabledFlag)) {
1050 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
1051 // state of feature is changed => so inform that it must be updated if it has such state
1052 if (!aDisabledFlag && anIter->data()->execState() == ModelAPI_StateMustBeUpdated)
1053 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
1054 // flush is in the end of this method
1055 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
1058 // update for everyone the concealment flag immideately: on edit feature in the midle of history
1060 std::list<ResultPtr> aResults;
1061 ModelAPI_Tools::allResults(anIter, aResults);
1062 std::list<ResultPtr>::const_iterator aRes = aResults.begin();
1063 for(; aRes != aResults.end(); aRes++) {
1064 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1065 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
1067 // update the concealment status for disply in isConcealed of ResultBody
1068 for(aRes = aResults.begin(); aRes != aResults.end(); aRes++) {
1069 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1070 (*aRes)->isConcealed();
1074 // unblock the flush signals and up them after this
1075 aLoop->activateFlushes(isActive);
1078 void Model_Document::setCurrentFeatureUp()
1080 // on remove just go up for minimum step: highlight external objects in sketch causes
1081 // problems if it is true: here and in "setCurrentFeature"
1082 FeaturePtr aCurrent = currentFeature(false);
1083 if (aCurrent.get()) { // if not, do nothing because null is the upper
1084 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
1085 // make the higher level composite as current (sketch becomes disabled if line is enabled)
1087 FeaturePtr aComp = ModelAPI_Tools::compositeOwner(aPrev);
1088 // without cycle (issue 1555): otherwise extrusion fuse will be enabled and displayed whaen inside sketch
1092 // do not flush: it is called only on remove, it will be flushed in the end of transaction
1093 setCurrentFeature(aPrev, false);
1097 TDF_Label Model_Document::generalLabel() const
1099 return myDoc->Main().FindChild(TAG_GENERAL);
1102 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
1103 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1105 return myObjs->createConstruction(theFeatureData, theIndex);
1108 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1109 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1111 return myObjs->createBody(theFeatureData, theIndex);
1114 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1115 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1117 return myObjs->createPart(theFeatureData, theIndex);
1120 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
1121 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1122 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1124 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
1127 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1128 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1130 return myObjs->createGroup(theFeatureData, theIndex);
1133 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
1134 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1136 return myObjs->createParameter(theFeatureData, theIndex);
1139 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1140 const std::shared_ptr<ModelAPI_Result>& theResult)
1142 return myObjs->feature(theResult);
1145 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1147 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1150 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1152 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1155 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1157 myNamingNames[theName] = theLabel;
1160 TDF_Label Model_Document::findNamingName(std::string theName)
1162 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
1163 if (aFind == myNamingNames.end())
1164 return TDF_Label(); // not found
1165 return aFind->second;
1168 ResultPtr Model_Document::findByName(const std::string theName)
1170 return myObjs->findByName(theName);
1173 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
1175 return myObjs->allFeatures();
1178 void Model_Document::setActive(const bool theFlag)
1180 if (theFlag != myIsActive) {
1181 myIsActive = theFlag;
1182 // redisplay all the objects of this part
1183 static Events_Loop* aLoop = Events_Loop::loop();
1184 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1186 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
1187 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
1188 object(ModelAPI_Feature::group(), a));
1189 if (aFeature.get() && aFeature->data()->isValid()) {
1190 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
1191 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
1192 for(; aRes != aResList.end(); aRes++) {
1193 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
1194 // #issue 1048: sub-compsolids also
1195 ResultCompSolidPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRes);
1196 if (aCompRes.get()) {
1197 int aNumSubs = aCompRes->numberOfSubs();
1198 for(int a = 0; a < aNumSubs; a++) {
1199 ResultPtr aSub = aCompRes->subResult(a);
1201 ModelAPI_EventCreator::get()->sendUpdated(aSub, aRedispEvent);
1211 bool Model_Document::isActive() const
1216 int Model_Document::transactionID()
1218 Handle(TDataStd_Integer) anIndex;
1219 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
1220 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
1221 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
1223 return anIndex->Get();
1226 void Model_Document::incrementTransactionID()
1228 int aNewVal = transactionID() + 1;
1229 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1231 void Model_Document::decrementTransactionID()
1233 int aNewVal = transactionID() - 1;
1234 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1237 bool Model_Document::isOpened()
1239 return myObjs && !myDoc.IsNull();
1242 int Model_Document::numInternalFeatures()
1244 return myObjs->numInternalFeatures();
1247 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
1249 return myObjs->internalFeature(theIndex);
1252 std::shared_ptr<ModelAPI_Feature> Model_Document::featureById(const int theId)
1254 return myObjs->featureById(theId);
1257 void Model_Document::synchronizeTransactions()
1259 Model_Document* aRoot =
1260 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
1262 return; // don't need to synchronise root with root
1264 std::shared_ptr<Model_Session> aSession =
1265 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
1266 while(myRedos.size() > aRoot->myRedos.size()) { // remove redos in this
1267 aSession->setCheckTransactions(false);
1269 aSession->setCheckTransactions(true);
1271 /* this case can not be reproduced in any known case for the current moment, so, just comment
1272 while(myRedos.size() < aRoot->myRedos.size()) { // add more redos in this
1273 undoInternal(false, true);
1277 /// Feature that is used for selection in the Part document by the external request
1278 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1280 /// Nothing to do in constructor
1281 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1283 /// Returns the unique kind of a feature
1284 virtual const std::string& getKind() {
1285 static std::string MY_KIND("InternalSelectionInPartFeature");
1288 /// Request for initialization of data model of the object: adding all attributes
1289 virtual void initAttributes() {
1290 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1292 /// Nothing to do in the execution function
1293 virtual void execute() {}
1297 //! Returns the feature that is used for calculation of selection externally from the document
1298 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1300 // return already created, otherwise create
1301 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1303 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1305 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1306 std::shared_ptr<Model_Data> aData(new Model_Data);
1307 aData->setLabel(aFeatureLab.FindChild(1));
1308 aData->setObject(mySelectionFeature);
1309 mySelectionFeature->setDoc(myObjs->owner());
1310 mySelectionFeature->setData(aData);
1311 std::string aName = id() + "_Part";
1312 mySelectionFeature->data()->setName(aName);
1313 mySelectionFeature->setDoc(myObjs->owner());
1314 mySelectionFeature->initAttributes();
1315 mySelectionFeature->init(); // to make it enabled and Update correctly
1316 // this update may cause recomputation of the part after selection on it, that is not needed
1317 mySelectionFeature->data()->blockSendAttributeUpdated(true);
1319 return mySelectionFeature->selectionList("selection");
1322 FeaturePtr Model_Document::lastFeature()
1325 return myObjs->lastFeature();
1326 return FeaturePtr();
1329 static Handle(TNaming_NamedShape) searchForOriginalShape(TopoDS_Shape theShape, TDF_Label aMain) {
1330 Handle(TNaming_NamedShape) aResult;
1331 while(!theShape.IsNull()) { // searching for the very initial shape that produces this one
1332 TopoDS_Shape aShape = theShape;
1334 if (!TNaming_Tool::HasLabel(aMain, aShape)) // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
1336 for(TNaming_SameShapeIterator anIter(aShape, aMain); anIter.More(); anIter.Next()) {
1337 TDF_Label aNSLab = anIter.Label();
1338 Handle(TNaming_NamedShape) aNS;
1339 if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1340 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
1341 if (aShapesIter.Evolution() == TNaming_SELECTED || aShapesIter.Evolution() == TNaming_DELETE)
1342 continue; // don't use the selection evolution
1343 if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
1345 if (aResult->Evolution() == TNaming_MODIFY)
1346 theShape = aShapesIter.OldShape();
1347 if (!theShape.IsNull()) // otherwise may me searching for another item of this shape with longer history
1357 std::shared_ptr<ModelAPI_Feature> Model_Document::producedByFeature(
1358 std::shared_ptr<ModelAPI_Result> theResult,
1359 const std::shared_ptr<GeomAPI_Shape>& theShape)
1361 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
1363 return feature(theResult); // for not-body just returns the feature that produced this result
1365 // otherwise get the shape and search the very initial label for it
1366 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1367 if (aShape.IsNull())
1368 return FeaturePtr();
1370 // for comsolids and compounds all the naming is located in the main object, so, try to use
1372 ResultCompSolidPtr aMain = ModelAPI_Tools::compSolidOwner(theResult);
1374 FeaturePtr aMainRes = producedByFeature(aMain, theShape);
1379 std::shared_ptr<Model_Data> aBodyData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1380 if (!aBodyData.get() || !aBodyData->isValid())
1381 return FeaturePtr();
1383 TopoDS_Shape anOldShape; // old shape in the pair oldshape->theShape in the named shape
1384 TopoDS_Shape aShapeContainer; // old shape of the shape that contains aShape as sub-element
1385 Handle(TNaming_NamedShape) aCandidatInThis, aCandidatContainer;
1386 TDF_Label aBodyLab = aBodyData->label();
1387 // use childs and this label (the lowest priority)
1388 TDF_ChildIDIterator aNSIter(aBodyLab, TNaming_NamedShape::GetID(), Standard_True);
1389 bool aUseThis = !aNSIter.More();
1390 while(anOldShape.IsNull() && (aNSIter.More() || aUseThis)) {
1391 Handle(TNaming_NamedShape) aNS;
1393 if (!aBodyLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
1396 aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1398 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
1399 if (aShapesIter.Evolution() == TNaming_SELECTED || aShapesIter.Evolution() == TNaming_DELETE)
1400 continue; // don't use the selection evolution
1401 if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
1402 aCandidatInThis = aNS;
1403 if (aCandidatInThis->Evolution() == TNaming_MODIFY)
1404 anOldShape = aShapesIter.OldShape();
1405 if (!anOldShape.IsNull()) // otherwise may me searching for another item of this shape with longer history
1408 // check that the shape contains aShape as sub-shape to fill container
1409 if (aShapesIter.NewShape().ShapeType() < aShape.ShapeType() && aCandidatContainer.IsNull()) {
1410 TopExp_Explorer anExp(aShapesIter.NewShape(), aShape.ShapeType());
1411 for(; anExp.More(); anExp.Next()) {
1412 if (aShape.IsSame(anExp.Current())) {
1413 aCandidatContainer = aNS;
1414 aShapeContainer = aShapesIter.NewShape();
1419 // iterate to the next label or to the body label in the end
1422 if (!aNSIter.More()) {
1428 if (aCandidatInThis.IsNull()) {
1429 // to fix 1512: searching for original shape of this shape if modification of it is not in this result
1430 aCandidatInThis = searchForOriginalShape(aShape, myDoc->Main());
1431 if (aCandidatInThis.IsNull()) {
1432 if (aCandidatContainer.IsNull())
1433 return FeaturePtr();
1434 // with the lower priority use the higher level shape that contains aShape
1435 aCandidatInThis = aCandidatContainer;
1436 anOldShape = aShapeContainer;
1438 // to stop the searching by the following searchForOriginalShape
1439 anOldShape.Nullify();
1443 Handle(TNaming_NamedShape) aNS = searchForOriginalShape(anOldShape, myDoc->Main());
1445 aCandidatInThis = aNS;
1448 TDF_Label aResultLab = aCandidatInThis->Label();
1449 while(aResultLab.Depth() > 3)
1450 aResultLab = aResultLab.Father();
1451 FeaturePtr aFeature = myObjs->feature(aResultLab);
1452 if (aFeature.get()) {
1453 if (!aResult.get() || myObjs->isLater(aResult, aFeature)) {
1460 bool Model_Document::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
1462 return myObjs->isLater(theLater, theCurrent);