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 <ModelAPI_ResultCompSolid.h>
20 #include <Events_Loop.h>
21 #include <Events_InfoMessage.h>
23 #include <TDataStd_Integer.hxx>
24 #include <TDataStd_Comment.hxx>
25 #include <TDF_ChildIDIterator.hxx>
26 #include <TDataStd_ReferenceArray.hxx>
27 #include <TDataStd_ReferenceList.hxx>
28 #include <TDataStd_IntegerArray.hxx>
29 #include <TDataStd_HLabelArray1.hxx>
30 #include <TDataStd_Name.hxx>
31 #include <TDataStd_AsciiString.hxx>
32 #include <TDF_Reference.hxx>
33 #include <TDF_ChildIDIterator.hxx>
34 #include <TDF_LabelMapHasher.hxx>
35 #include <TDF_Delta.hxx>
36 #include <TDF_AttributeDelta.hxx>
37 #include <TDF_AttributeDeltaList.hxx>
38 #include <TDF_ListIteratorOfAttributeDeltaList.hxx>
39 #include <TDF_ListIteratorOfLabelList.hxx>
40 #include <TDF_LabelMap.hxx>
41 #include <TDF_DeltaOnAddition.hxx>
42 #include <TNaming_Builder.hxx>
43 #include <TNaming_SameShapeIterator.hxx>
44 #include <TNaming_Iterator.hxx>
45 #include <TNaming_NamedShape.hxx>
46 #include <TNaming_Tool.hxx>
48 #include <TopExp_Explorer.hxx>
49 #include <TopoDS_Shape.hxx>
51 #include <OSD_File.hxx>
52 #include <OSD_Path.hxx>
53 #include <CDF_Session.hxx>
54 #include <CDF_Directory.hxx>
62 # define _separator_ '\\'
64 # define _separator_ '/'
67 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
69 static const int TAG_GENERAL = 1; // general properties tag
72 /// where the reference to the current feature label is located (or no attribute if null feature)
73 static const int TAG_CURRENT_FEATURE = 1; ///< reference to the current feature
74 static const int TAG_CURRENT_TRANSACTION = 2; ///< integer, index of the transaction
75 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
76 static const int TAG_NODES_STATE = 4; ///< array, tag of the Object Browser nodes states
77 ///< naming structures constructions selected from other document
78 static const int TAG_EXTERNAL_CONSTRUCTIONS = 5;
80 Model_Document::Model_Document(const int theID, const std::string theKind)
81 : myID(theID), myKind(theKind), myIsActive(false),
82 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
85 CDF_Session::CurrentSession()->Directory()->Add(myDoc);
87 myObjs = new Model_Objects(myDoc->Main());
88 myDoc->SetUndoLimit(UNDO_LIMIT);
89 myTransactionSave = 0;
90 myExecuteFeatures = true;
91 // to have something in the document and avoid empty doc open/save problem
92 // in transaction for nesting correct working
94 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
95 // this to avoid creation of integer attribute outside the transaction after undo
97 myDoc->CommitCommand();
100 void Model_Document::setThis(DocumentPtr theDoc)
102 myObjs->setOwner(theDoc);
105 /// Returns the file name of this document by the name of directory and identifier of a document
106 static TCollection_ExtendedString DocFileName(const char* theDirName, const std::string& theID)
108 TCollection_ExtendedString aPath((const Standard_CString) theDirName);
109 // remove end-separators
110 while(aPath.Length() &&
111 (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
112 aPath.Remove(aPath.Length());
113 aPath += _separator_;
114 aPath += theID.c_str();
115 aPath += ".cbf"; // standard binary file extension
119 bool Model_Document::isRoot() const
121 return this == Model_Session::get()->moduleDocument().get();
124 bool Model_Document::load(const char* theDirName, const char* theFileName, DocumentPtr theThis)
126 Handle(Model_Application) anApp = Model_Application::getApplication();
128 anApp->setLoadPath(theDirName);
130 TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
131 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
132 Handle(TDocStd_Document) aLoaded;
134 aStatus = anApp->Open(aPath, aLoaded);
135 } catch (Standard_Failure) {
136 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
137 Events_InfoMessage("Model_Document",
138 "Exception in opening of document: %1").arg(aFail->GetMessageString()).send();
141 bool isError = aStatus != PCDM_RS_OK;
144 case PCDM_RS_UnknownDocument:
145 Events_InfoMessage("Model_Document", "Can not open document").send();
147 case PCDM_RS_AlreadyRetrieved:
148 Events_InfoMessage("Model_Document", "Can not open document: already opened").send();
150 case PCDM_RS_AlreadyRetrievedAndModified:
151 Events_InfoMessage("Model_Document",
152 "Can not open document: already opened and modified").send();
154 case PCDM_RS_NoDriver:
155 Events_InfoMessage("Model_Document",
156 "Can not open document: driver library is not found").send();
158 case PCDM_RS_UnknownFileDriver:
159 Events_InfoMessage("Model_Document",
160 "Can not open document: unknown driver for opening").send();
162 case PCDM_RS_OpenError:
163 Events_InfoMessage("Model_Document", "Can not open document: file open error").send();
165 case PCDM_RS_NoVersion:
166 Events_InfoMessage("Model_Document", "Can not open document: invalid version").send();
168 case PCDM_RS_NoModel:
169 Events_InfoMessage("Model_Document", "Can not open document: no data model").send();
171 case PCDM_RS_NoDocument:
172 Events_InfoMessage("Model_Document", "Can not open document: no document inside").send();
174 case PCDM_RS_FormatFailure:
175 Events_InfoMessage("Model_Document", "Can not open document: format failure").send();
177 case PCDM_RS_TypeNotFoundInSchema:
178 Events_InfoMessage("Model_Document", "Can not open document: invalid object").send();
180 case PCDM_RS_UnrecognizedFileFormat:
181 Events_InfoMessage("Model_Document",
182 "Can not open document: unrecognized file format").send();
184 case PCDM_RS_MakeFailure:
185 Events_InfoMessage("Model_Document", "Can not open document: make failure").send();
187 case PCDM_RS_PermissionDenied:
188 Events_InfoMessage("Model_Document", "Can not open document: permission denied").send();
190 case PCDM_RS_DriverFailure:
191 Events_InfoMessage("Model_Document", "Can not open document: driver failure").send();
194 Events_InfoMessage("Model_Document", "Can not open document: unknown error").send();
198 std::shared_ptr<Model_Session> aSession =
199 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
202 myDoc->SetUndoLimit(UNDO_LIMIT);
204 // to avoid the problem that feature is created in the current, not this, document
205 aSession->setActiveDocument(anApp->document(myID), false);
206 aSession->setCheckTransactions(false);
209 myObjs = new Model_Objects(myDoc->Main()); // synchronisation is inside
210 myObjs->setOwner(theThis);
211 // update the current features status
212 setCurrentFeature(currentFeature(false), false);
213 aSession->setCheckTransactions(true);
214 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
215 // this is done in Part result "activate", so no needed here. Causes not-blue active part.
216 // aSession->setActiveDocument(anApp->getDocument(myID), true);
218 // make sub-parts as loaded by demand
219 std::list<ResultPtr> aPartResults;
220 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
221 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
222 for(; aPartRes != aPartResults.end(); aPartRes++) {
223 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
225 anApp->setLoadByDemand(aPart->data()->name(),
226 aPart->data()->document(ModelAPI_ResultPart::DOC_REF())->docId());
229 } else { // open failed, but new documnet was created to work with it: inform the model
230 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
235 bool Model_Document::save(
236 const char* theDirName, const char* theFileName, std::list<std::string>& theResults)
238 // if the history line is not in the end, move it to the end before save, otherwise
239 // problems with results restore and (the most important) naming problems will appear
240 // due to change evolution to SELECTION (problems in NamedShape and Name)
241 FeaturePtr aWasCurrent;
242 std::shared_ptr<Model_Session> aSession =
243 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
244 if (currentFeature(false) != lastFeature()) {
245 aSession->setCheckTransactions(false);
246 aWasCurrent = currentFeature(false);
247 setCurrentFeature(lastFeature(), false);
249 // create a directory in the root document if it is not yet exist
250 Handle(Model_Application) anApp = Model_Application::getApplication();
253 CreateDirectory(theDirName, NULL);
255 mkdir(theDirName, 0x1ff);
258 // filename in the dir is id of document inside of the given directory
259 TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
260 PCDM_StoreStatus aStatus;
262 aStatus = anApp->SaveAs(myDoc, aPath);
263 } catch (Standard_Failure) {
264 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
265 Events_InfoMessage("Model_Document",
266 "Exception in saving of document: %1").arg(aFail->GetMessageString()).send();
267 if (aWasCurrent.get()) { // return the current feature to the initial position
268 setCurrentFeature(aWasCurrent, false);
269 aSession->setCheckTransactions(true);
273 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
276 case PCDM_SS_DriverFailure:
277 Events_InfoMessage("Model_Document",
278 "Can not save document: save driver-library failure").send();
280 case PCDM_SS_WriteFailure:
281 Events_InfoMessage("Model_Document", "Can not save document: file writing failure").send();
283 case PCDM_SS_Failure:
285 Events_InfoMessage("Model_Document", "Can not save document").send();
290 if (aWasCurrent.get()) { // return the current feature to the initial position
291 setCurrentFeature(aWasCurrent, false);
292 aSession->setCheckTransactions(true);
295 myTransactionSave = int(myTransactions.size());
296 if (isDone) { // save also sub-documents if any
297 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
298 // iterate all result parts to find all loaded or not yet loaded documents
299 std::list<ResultPtr> aPartResults;
300 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
301 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
302 for(; aPartRes != aPartResults.end(); aPartRes++) {
303 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
304 if (!aPart->isActivated()) {
305 // copy not-activated document that is not in the memory
306 std::string aDocName = aPart->data()->name();
307 if (!aDocName.empty()) {
309 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
310 OSD_Path aPath(aSubPath);
311 OSD_File aFile(aPath);
312 if (aFile.Exists()) {
313 TCollection_AsciiString aDestinationDir(DocFileName(theDirName, aDocName));
314 OSD_Path aDestination(aDestinationDir);
315 aFile.Copy(aDestination);
316 theResults.push_back(aDestinationDir.ToCString());
318 Events_InfoMessage("Model_Document",
319 "Can not open file %1 for saving").arg(aSubPath.ToCString()).send();
322 } else { // simply save opened document
323 isDone = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc())->
324 save(theDirName, aPart->data()->name().c_str(), theResults);
331 void Model_Document::close(const bool theForever)
333 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
334 if (!isRoot() && this == aPM->activeDocument().get()) {
335 aPM->setActiveDocument(aPM->moduleDocument());
336 } else if (isRoot()) {
337 // erase the active document if root is closed
338 aPM->setActiveDocument(DocumentPtr());
341 const std::set<int> aSubs = subDocuments();
342 std::set<int>::iterator aSubIter = aSubs.begin();
343 for (; aSubIter != aSubs.end(); aSubIter++) {
344 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
345 if (aSub->myObjs) // if it was not closed before
346 aSub->close(theForever);
349 // close for thid document needs no transaction in this document
350 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
352 // close all only if it is really asked, otherwise it can be undoed/redoed
354 // flush everything to avoid messages with bad objects
357 if (myDoc->CanClose() == CDM_CCS_OK)
359 mySelectionFeature.reset();
361 setCurrentFeature(FeaturePtr(), false); // disables all features
362 // update the OB: features are disabled (on remove of Part)
363 Events_Loop* aLoop = Events_Loop::loop();
364 static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
365 aLoop->flush(aDeleteEvent);
368 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
371 void Model_Document::startOperation()
373 incrementTransactionID(); // outside of transaction in order to avoid empty transactions keeping
374 if (myDoc->HasOpenCommand()) { // start of nested command
375 if (myDoc->CommitCommand()) {
376 // commit the current: it will contain all nested after compactification
377 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
379 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
380 myDoc->OpenCommand();
381 } else { // start the simple command
384 // starts a new operation
385 myTransactions.push_back(Transaction());
386 if (!myNestedNum.empty())
387 (*myNestedNum.rbegin())++;
389 // new command for all subs
390 const std::set<int> aSubs = subDocuments();
391 std::set<int>::iterator aSubIter = aSubs.begin();
392 for (; aSubIter != aSubs.end(); aSubIter++)
393 subDoc(*aSubIter)->startOperation();
396 void Model_Document::compactNested()
398 if (!myNestedNum.empty()) {
399 int aNumToCompact = *(myNestedNum.rbegin());
400 int aSumOfTransaction = 0;
401 for(int a = 0; a < aNumToCompact; a++) {
402 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
403 myTransactions.pop_back();
405 // the latest transaction is the start of lower-level operation which startes the nested
406 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
407 myNestedNum.pop_back();
411 /// Compares the content of the given attributes, returns true if equal.
412 /// This method is used to avoid empty transactions when only "current" is changed
413 /// to some value and then comes back in this transaction, so, it compares only
414 /// references and Boolean and Integer Arrays for the current moment.
415 static bool isEqualContent(Handle(TDF_Attribute) theAttr1, Handle(TDF_Attribute) theAttr2)
417 if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_Reference::GetID())) { // reference
418 Handle(TDF_Reference) aRef1 = Handle(TDF_Reference)::DownCast(theAttr1);
419 Handle(TDF_Reference) aRef2 = Handle(TDF_Reference)::DownCast(theAttr2);
420 if (aRef1.IsNull() && aRef2.IsNull())
422 if (aRef1.IsNull() || aRef2.IsNull())
424 return aRef1->Get().IsEqual(aRef2->Get()) == Standard_True;
425 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_BooleanArray::GetID())) {
426 Handle(TDataStd_BooleanArray) anArr1 = Handle(TDataStd_BooleanArray)::DownCast(theAttr1);
427 Handle(TDataStd_BooleanArray) anArr2 = Handle(TDataStd_BooleanArray)::DownCast(theAttr2);
428 if (anArr1.IsNull() && anArr2.IsNull())
430 if (anArr1.IsNull() || anArr2.IsNull())
432 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
433 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++) {
434 if (a == 1 && // second is for display
435 anArr2->Label().Tag() == 1 && (anArr2->Label().Depth() == 4 ||
436 anArr2->Label().Depth() == 6))
438 if (anArr1->Value(a) != anArr2->Value(a))
443 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_IntegerArray::GetID())) {
444 Handle(TDataStd_IntegerArray) anArr1 = Handle(TDataStd_IntegerArray)::DownCast(theAttr1);
445 Handle(TDataStd_IntegerArray) anArr2 = Handle(TDataStd_IntegerArray)::DownCast(theAttr2);
446 if (anArr1.IsNull() && anArr2.IsNull())
448 if (anArr1.IsNull() || anArr2.IsNull())
450 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
451 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
452 if (anArr1->Value(a) != anArr2->Value(a)) {
453 // avoid the transaction ID checking
454 if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
455 (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
461 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceArray::GetID())) {
462 Handle(TDataStd_ReferenceArray) anArr1 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr1);
463 Handle(TDataStd_ReferenceArray) anArr2 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr2);
464 if (anArr1.IsNull() && anArr2.IsNull())
466 if (anArr1.IsNull() || anArr2.IsNull())
468 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
469 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
470 if (anArr1->Value(a) != anArr2->Value(a)) {
471 // avoid the transaction ID checking
472 if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
473 (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
479 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceList::GetID())) {
480 Handle(TDataStd_ReferenceList) aList1 = Handle(TDataStd_ReferenceList)::DownCast(theAttr1);
481 Handle(TDataStd_ReferenceList) aList2= Handle(TDataStd_ReferenceList)::DownCast(theAttr2);
482 if (aList1.IsNull() && aList2.IsNull())
484 if (aList1.IsNull() || aList2.IsNull())
486 const TDF_LabelList& aLList1 = aList1->List();
487 const TDF_LabelList& aLList2 = aList2->List();
488 TDF_ListIteratorOfLabelList aLIter1(aLList1);
489 TDF_ListIteratorOfLabelList aLIter2(aLList2);
490 for(; aLIter1.More() && aLIter2.More(); aLIter1.Next(), aLIter2.Next()) {
491 if (aLIter1.Value() != aLIter2.Value())
494 return !aLIter1.More() && !aLIter2.More(); // both lists are with the same size
495 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_TagSource::GetID())) {
496 return true; // it just for created and removed feature: nothing is changed
501 /// Returns true if the last transaction is actually empty: modification to te same values
502 /// were performed only
503 static bool isEmptyTransaction(const Handle(TDocStd_Document)& theDoc) {
504 Handle(TDF_Delta) aDelta;
505 aDelta = theDoc->GetUndos().Last();
506 TDF_LabelList aDeltaList;
507 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
508 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
511 // add also label of the modified attributes
512 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
513 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
514 Handle(TDF_AttributeDelta)& anADelta = anAttr.Value();
515 Handle(TDF_DeltaOnAddition) anAddition = Handle(TDF_DeltaOnAddition)::DownCast(anADelta);
516 if (anAddition.IsNull()) { // if the attribute was added, transaction is not empty
517 if (!anADelta->Label().IsNull() && !anADelta->Attribute().IsNull()) {
518 Handle(TDF_Attribute) aCurrentAttr;
519 if (anADelta->Label().FindAttribute(anADelta->Attribute()->ID(), aCurrentAttr)) {
520 if (isEqualContent(anADelta->Attribute(), aCurrentAttr)) {
521 continue; // attribute is not changed actually
524 if (Standard_GUID::IsEqual(anADelta->Attribute()->ID(), TDataStd_AsciiString::GetID())) {
525 continue; // error message is disappeared
534 bool Model_Document::finishOperation()
536 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
537 static std::shared_ptr<Model_Session> aSession =
538 std::static_pointer_cast<Model_Session>(Model_Session::get());
540 // open transaction if nested is closed to fit inside
541 // all synchronizeBackRefs and flushed consequences
542 if (isNestedClosed) {
543 myDoc->OpenCommand();
545 // do it before flashes to enable and recompute nesting features correctly
546 if (myNestedNum.empty() || (isNestedClosed && myNestedNum.size() == 1)) {
547 // if all nested operations are closed, make current the higher level objects (to perform
548 // it in the python scripts correctly): sketch become current after creation ofsub-elements
549 FeaturePtr aCurrent = currentFeature(false);
550 CompositeFeaturePtr aMain, aNext = ModelAPI_Tools::compositeOwner(aCurrent);
553 aNext = ModelAPI_Tools::compositeOwner(aMain);
555 if (aMain.get() && aMain != aCurrent)
556 setCurrentFeature(aMain, false);
558 myObjs->synchronizeBackRefs();
559 Events_Loop* aLoop = Events_Loop::loop();
560 static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
561 static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
562 static const Events_ID kRedispEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
563 static const Events_ID kDeletedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_DELETED);
564 aLoop->flush(kCreatedEvent);
565 aLoop->flush(kUpdatedEvent);
566 aLoop->flush(kRedispEvent);
567 aLoop->flush(kDeletedEvent);
569 if (isNestedClosed) {
570 if (myDoc->CommitCommand())
571 myTransactions.rbegin()->myOCAFNum++;
574 // this must be here just after everything is finished but before real transaction stop
575 // to avoid messages about modifications outside of the transaction
576 // and to rebuild everything after all updates and creates
577 if (isRoot()) { // once for root document
578 static std::shared_ptr<Events_Message> aFinishMsg
579 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
580 Events_Loop::loop()->send(aFinishMsg);
583 while(aLoop->hasGrouppedEvent(kCreatedEvent) || aLoop->hasGrouppedEvent(kUpdatedEvent) ||
584 aLoop->hasGrouppedEvent(kRedispEvent) || aLoop->hasGrouppedEvent(kDeletedEvent)) {
585 aLoop->flush(kCreatedEvent);
586 aLoop->flush(kUpdatedEvent);
587 aLoop->flush(kRedispEvent);
588 aLoop->flush(kDeletedEvent);
591 // to avoid "updated" message appearance by updater
592 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
594 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
595 bool aResult = false;
596 const std::set<int> aSubs = subDocuments();
597 std::set<int>::iterator aSubIter = aSubs.begin();
598 for (; aSubIter != aSubs.end(); aSubIter++)
599 if (subDoc(*aSubIter)->finishOperation())
602 // transaction may be empty if this document was created during this transaction (create part)
603 if (!myTransactions.empty() && myDoc->CommitCommand()) {
604 // if commit is successfull, just increment counters
605 if (isEmptyTransaction(myDoc)) { // erase this transaction
609 myTransactions.rbegin()->myOCAFNum++;
614 if (isNestedClosed) {
617 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
618 aResult = myTransactions.rbegin()->myOCAFNum != 0;
620 if (!aResult && isRoot()) {
621 // nothing inside in all documents, so remove this transaction from the transactions list
622 undoInternal(true, false);
624 // on finish clear redos in any case (issue 446) and for all subs (issue 408)
627 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
628 subDoc(*aSubIter)->myDoc->ClearRedos();
629 subDoc(*aSubIter)->myRedos.clear();
635 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
636 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
637 const bool isRedo = false) {
638 Handle(TDF_Delta) aDelta;
640 aDelta = theDoc->GetRedos().First();
642 aDelta = theDoc->GetUndos().Last();
643 TDF_LabelList aDeltaList;
644 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
645 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
646 theDelta.Append(aListIter.Value());
648 // add also label of the modified attributes
649 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
650 /// named shape evolution also modifies integer on this label: exclude it
651 TDF_LabelMap anExcludedInt;
652 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
653 if (anAttr.Value()->Attribute()->ID() == TDataStd_BooleanArray::GetID()) {
654 // Boolean array is used for feature auxiliary attributes only, feature args are not modified
657 if (anAttr.Value()->Attribute()->ID() == TNaming_NamedShape::GetID()) {
658 anExcludedInt.Add(anAttr.Value()->Label());
659 // named shape evolution is changed in history update => skip them,
660 // they are not the features arguents
663 if (anAttr.Value()->Attribute()->ID() == TDataStd_Integer::GetID()) {
664 if (anExcludedInt.Contains(anAttr.Value()->Label()))
667 theDelta.Append(anAttr.Value()->Label());
669 TDF_ListIteratorOfLabelList aDeltaIter(theDelta);
670 for(; aDeltaIter.More(); aDeltaIter.Next()) {
671 if (anExcludedInt.Contains(aDeltaIter.Value())) {
672 theDelta.Remove(aDeltaIter);
673 if (!aDeltaIter.More())
679 void Model_Document::abortOperation()
681 TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
682 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
684 // store undo-delta here as undo actually does in the method later
685 int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
686 for(a = 0; a < aNumTransactions; a++) {
687 modifiedLabels(myDoc, aDeltaLabels);
690 for(a = 0; a < aNumTransactions; a++) {
694 undoInternal(false, false);
697 } else { // abort the current
698 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
699 myTransactions.pop_back();
700 if (!myNestedNum.empty())
701 (*myNestedNum.rbegin())--;
702 // roll back the needed number of transactions
703 //myDoc->AbortCommand();
704 // instead of abort, do commit and undo: to get the delta of modifications
705 if (myDoc->CommitCommand()) {
706 modifiedLabels(myDoc, aDeltaLabels);
709 for(int a = 0; a < aNumTransactions; a++) {
710 modifiedLabels(myDoc, aDeltaLabels);
715 // abort for all subs, flushes will be later, in the end of root abort
716 const std::set<int> aSubs = subDocuments();
717 std::set<int>::iterator aSubIter = aSubs.begin();
718 for (; aSubIter != aSubs.end(); aSubIter++)
719 subDoc(*aSubIter)->abortOperation();
720 // references may be changed because they are set in attributes on the fly
721 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
724 bool Model_Document::isOperation() const
726 // operation is opened for all documents: no need to check subs
727 return myDoc->HasOpenCommand() == Standard_True ;
730 bool Model_Document::isModified()
732 // is modified if at least one operation was commited and not undoed
733 return myTransactions.size() != myTransactionSave || isOperation();
736 bool Model_Document::canUndo()
738 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
739 int aCurrentNum = isOperation() ? 1 : 0;
740 if (myDoc->GetAvailableUndos() > 0 &&
741 // there is something to undo in nested
742 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) &&
743 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
745 // check other subs contains operation that can be undoed
746 const std::set<int> aSubs = subDocuments();
747 std::set<int>::iterator aSubIter = aSubs.begin();
748 for (; aSubIter != aSubs.end(); aSubIter++) {
749 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
750 if (aSub->myObjs) {// if it was not closed before
759 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
761 if (myTransactions.empty())
763 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
764 myRedos.push_back(*myTransactions.rbegin());
765 myTransactions.pop_back();
766 if (!myNestedNum.empty())
767 (*myNestedNum.rbegin())--;
768 // roll back the needed number of transactions
769 TDF_LabelList aDeltaLabels;
770 for(int a = 0; a < aNumTransactions; a++) {
772 modifiedLabels(myDoc, aDeltaLabels);
778 const std::set<int> aSubs = subDocuments();
779 std::set<int>::iterator aSubIter = aSubs.begin();
780 for (; aSubIter != aSubs.end(); aSubIter++) {
781 if (!subDoc(*aSubIter)->myObjs)
783 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
786 // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
787 if (theSynchronize) {
788 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
789 // update the current features status
790 setCurrentFeature(currentFeature(false), false);
794 void Model_Document::undo()
796 undoInternal(true, true);
799 bool Model_Document::canRedo()
801 if (!myRedos.empty())
803 // check other subs contains operation that can be redoed
804 const std::set<int> aSubs = subDocuments();
805 std::set<int>::iterator aSubIter = aSubs.begin();
806 for (; aSubIter != aSubs.end(); aSubIter++) {
807 if (!subDoc(*aSubIter)->myObjs)
809 if (subDoc(*aSubIter)->canRedo())
815 void Model_Document::redo()
817 if (!myNestedNum.empty())
818 (*myNestedNum.rbegin())++;
819 int aNumRedos = myRedos.rbegin()->myOCAFNum;
820 myTransactions.push_back(*myRedos.rbegin());
822 TDF_LabelList aDeltaLabels;
823 for(int a = 0; a < aNumRedos; a++) {
824 modifiedLabels(myDoc, aDeltaLabels, true);
829 const std::set<int> aSubs = subDocuments();
830 std::set<int>::iterator aSubIter = aSubs.begin();
831 for (; aSubIter != aSubs.end(); aSubIter++)
832 subDoc(*aSubIter)->redo();
834 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
835 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
836 // update the current features status
837 setCurrentFeature(currentFeature(false), false);
840 std::list<std::string> Model_Document::undoList() const
842 std::list<std::string> aResult;
843 // the number of skipped current operations (on undo they will be aborted)
844 int aSkipCurrent = isOperation() ? 1 : 0;
845 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
846 int aNumUndo = int(myTransactions.size());
847 if (!myNestedNum.empty())
848 aNumUndo = *myNestedNum.rbegin();
849 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
850 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
856 std::list<std::string> Model_Document::redoList() const
858 std::list<std::string> aResult;
859 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
860 for( ; aTrIter != myRedos.crend(); aTrIter++) {
861 aResult.push_back(aTrIter->myId);
866 void Model_Document::operationId(const std::string& theId)
868 myTransactions.rbegin()->myId = theId;
871 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
873 std::shared_ptr<Model_Session> aSession =
874 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
875 FeaturePtr aFeature = aSession->createFeature(theID, this);
879 Model_Document* aDocToAdd;
880 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
881 if (aFeature->documentToAdd() != kind()) { // the root document by default
882 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
886 } else { // if customized is not presented, add to "this" document
890 // searching for feature after which must be added the next feature: this is the current feature
891 // but also all sub-features of this feature
892 FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
893 bool isModified = true;
894 for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
895 aComp.get() && isModified;
896 aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
898 int aSubs = aComp->numberOfSubs(false);
899 for(int a = 0; a < aSubs; a++) {
900 FeaturePtr aSub = aComp->subFeature(a, false);
901 if (myObjs->isLater(aSub, aCurrent)) {
907 aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
908 if (!aFeature->isAction()) { // do not add action to the data model
909 if (theMakeCurrent) // after all this feature stays in the document, so make it current
910 aDocToAdd->setCurrentFeature(aFeature, false);
911 } else { // feature must be executed
912 // no creation event => updater not working, problem with remove part
920 void Model_Document::refsToFeature(FeaturePtr theFeature,
921 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
923 myObjs->refsToFeature(theFeature, theRefs, isSendError);
926 void Model_Document::removeFeature(FeaturePtr theFeature)
928 myObjs->removeFeature(theFeature);
931 // recursive function to check if theSub is a child of theMain composite feature
932 // through all the hierarchy of parents
933 static bool isSub(const CompositeFeaturePtr theMain, const FeaturePtr theSub) {
934 CompositeFeaturePtr aParent = ModelAPI_Tools::compositeOwner(theSub);
937 if (aParent == theMain)
939 return isSub(theMain, aParent);
943 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
945 bool aCurrentUp = theMoved == currentFeature(false);
947 setCurrentFeatureUp();
949 // if user adds after high-level feature with nested,
950 // add it after all nested (otherwise the nested will be disabled)
951 CompositeFeaturePtr aCompositeAfter =
952 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theAfterThis);
953 FeaturePtr anAfterThisSub = theAfterThis;
954 if (aCompositeAfter.get()) {
955 FeaturePtr aSub = aCompositeAfter;
957 FeaturePtr aNext = myObjs->nextFeature(aSub);
958 if (!isSub(aCompositeAfter, aNext)) {
959 anAfterThisSub = aSub;
963 } while (aSub.get());
966 myObjs->moveFeature(theMoved, anAfterThisSub);
967 if (aCurrentUp) { // make the moved feature enabled or disabled due to the real status
968 setCurrentFeature(currentFeature(false), false);
969 } else if (theAfterThis == currentFeature(false) || anAfterThisSub == currentFeature(false)) {
970 // must be after move to make enabled all features which are before theMoved
971 setCurrentFeature(theMoved, true);
975 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
977 myObjs->updateHistory(theObject);
980 void Model_Document::updateHistory(const std::string theGroup)
982 myObjs->updateHistory(theGroup);
985 const std::set<int> Model_Document::subDocuments() const
987 std::set<int> aResult;
988 std::list<ResultPtr> aPartResults;
989 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
990 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
991 for(; aPartRes != aPartResults.end(); aPartRes++) {
992 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
993 if (aPart && aPart->isActivated()) {
994 aResult.insert(aPart->original()->partDoc()->id());
1000 std::shared_ptr<Model_Document> Model_Document::subDoc(int theDocID)
1002 // just store sub-document identifier here to manage it later
1003 return std::dynamic_pointer_cast<Model_Document>(
1004 Model_Application::getApplication()->document(theDocID));
1007 ObjectPtr Model_Document::object(const std::string& theGroupID, const int theIndex)
1009 return myObjs->object(theGroupID, theIndex);
1012 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
1013 const std::string& theGroupID, const std::string& theName)
1015 return myObjs->objectByName(theGroupID, theName);
1018 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject)
1020 return myObjs->index(theObject);
1023 int Model_Document::size(const std::string& theGroupID)
1025 if (myObjs == 0) // may be on close
1027 return myObjs->size(theGroupID);
1030 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
1032 if (!myObjs) // on close document feature destruction it may call this method
1033 return std::shared_ptr<ModelAPI_Feature>();
1034 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
1035 Handle(TDF_Reference) aRef;
1036 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1037 TDF_Label aLab = aRef->Get();
1038 FeaturePtr aResult = myObjs->feature(aLab);
1039 if (theVisible) { // get nearest visible (in history) going up
1040 while(aResult.get() && !aResult->isInHistory()) {
1041 aResult = myObjs->nextFeature(aResult, true);
1046 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
1049 void Model_Document::setCurrentFeature(
1050 std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theVisible)
1052 // blocks the flush signals to avoid each objects visualization in the viewer
1053 // they should not be shown once after all modifications are performed
1054 Events_Loop* aLoop = Events_Loop::loop();
1055 bool isActive = aLoop->activateFlushes(false);
1057 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
1058 CompositeFeaturePtr aMain; // main feature that may nest the new current
1059 std::set<FeaturePtr> anOwners; // composites that contain theCurrent (with any level of nesting)
1060 if (theCurrent.get()) {
1061 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
1062 CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theCurrent);
1063 while(anOwner.get()) {
1067 anOwners.insert(anOwner);
1068 anOwner = ModelAPI_Tools::compositeOwner(anOwner);
1072 if (theVisible && !theCurrent.get()) {
1073 // needed to avoid disabling of PartSet initial constructions
1075 theCurrent.get() ? myObjs->nextFeature(theCurrent) : myObjs->firstFeature();
1076 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent)) {
1077 if (aNext->isInHistory()) {
1078 break; // next in history is not needed
1079 } else { // next not in history is good for making current
1084 if (theCurrent.get()) {
1085 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1086 if (!aData.get() || !aData->isValid()) {
1087 aLoop->activateFlushes(isActive);
1090 TDF_Label aFeatureLabel = aData->label().Father();
1092 Handle(TDF_Reference) aRef;
1093 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1094 aRef->Set(aFeatureLabel);
1096 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
1098 } else { // remove reference for the null feature
1099 aRefLab.ForgetAttribute(TDF_Reference::GetID());
1101 // make all features after this feature disabled in reversed order
1102 // (to remove results without deps)
1103 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1105 bool aPassed = false; // flag that the current object is already passed in cycle
1106 FeaturePtr anIter = myObjs->lastFeature();
1107 bool aWasChanged = false;
1108 bool isCurrentParameter = theCurrent.get() && theCurrent->getKind() == "Parameter";
1109 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, true)) {
1110 // check this before passed become enabled: the current feature is enabled!
1111 if (anIter == theCurrent) aPassed = true;
1113 bool aDisabledFlag = !aPassed;
1115 if (isSub(aMain, anIter)) // sub-elements of not-disabled feature are not disabled
1116 aDisabledFlag = false;
1117 else if (anOwners.find(anIter) != anOwners.end())
1118 // disable the higher-level feature is the nested is the current
1119 aDisabledFlag = true;
1122 if (anIter->getKind() == "Parameter") {
1123 // parameters are always out of the history of features, but not parameters
1124 // due to the issue 1491 all parameters are kept enabled any time
1125 //if (!isCurrentParameter)
1126 aDisabledFlag = false;
1127 } else if (isCurrentParameter) {
1128 // if paramater is active, all other features become enabled (issue 1307)
1129 aDisabledFlag = false;
1132 if (anIter->setDisabled(aDisabledFlag)) {
1133 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
1134 // state of feature is changed => so inform that it must be updated if it has such state
1135 if (!aDisabledFlag &&
1136 (anIter->data()->execState() == ModelAPI_StateMustBeUpdated ||
1137 anIter->data()->execState() == ModelAPI_StateInvalidArgument))
1138 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
1139 // flush is in the end of this method
1140 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
1143 // update for everyone the concealment flag immideately: on edit feature in the midle of history
1145 std::list<ResultPtr> aResults;
1146 ModelAPI_Tools::allResults(anIter, aResults);
1147 std::list<ResultPtr>::const_iterator aRes = aResults.begin();
1148 for(; aRes != aResults.end(); aRes++) {
1149 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1150 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
1152 // update the concealment status for disply in isConcealed of ResultBody
1153 for(aRes = aResults.begin(); aRes != aResults.end(); aRes++) {
1154 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1155 (*aRes)->isConcealed();
1159 // unblock the flush signals and up them after this
1160 aLoop->activateFlushes(isActive);
1163 void Model_Document::setCurrentFeatureUp()
1165 // on remove just go up for minimum step: highlight external objects in sketch causes
1166 // problems if it is true: here and in "setCurrentFeature"
1167 FeaturePtr aCurrent = currentFeature(false);
1168 if (aCurrent.get()) { // if not, do nothing because null is the upper
1169 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, true);
1170 // make the higher level composite as current (sketch becomes disabled if line is enabled)
1172 FeaturePtr aComp = ModelAPI_Tools::compositeOwner(aPrev);
1173 // without cycle (issue 1555): otherwise extrusion fuse
1174 // will be enabled and displayed whaen inside sketch
1178 // do not flush: it is called only on remove, it will be flushed in the end of transaction
1179 setCurrentFeature(aPrev, false);
1183 TDF_Label Model_Document::generalLabel() const
1185 return myDoc->Main().FindChild(TAG_GENERAL);
1188 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
1189 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1191 return myObjs->createConstruction(theFeatureData, theIndex);
1194 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1195 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1197 return myObjs->createBody(theFeatureData, theIndex);
1200 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1201 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1203 return myObjs->createPart(theFeatureData, theIndex);
1206 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
1207 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1208 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1210 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
1213 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1214 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1216 return myObjs->createGroup(theFeatureData, theIndex);
1219 std::shared_ptr<ModelAPI_ResultField> Model_Document::createField(
1220 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1222 return myObjs->createField(theFeatureData, theIndex);
1225 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
1226 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1228 return myObjs->createParameter(theFeatureData, theIndex);
1231 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1232 const std::shared_ptr<ModelAPI_Result>& theResult)
1234 return myObjs->feature(theResult);
1237 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1239 return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1242 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1244 return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1247 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1249 myNamingNames[theName] = theLabel;
1252 void Model_Document::changeNamingName(const std::string theOldName, const std::string theNewName)
1254 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theOldName);
1255 if (aFind != myNamingNames.end()) {
1256 myNamingNames[theNewName] = aFind->second;
1257 myNamingNames.erase(theOldName);
1261 TDF_Label Model_Document::findNamingName(std::string theName)
1263 std::map<std::string, TDF_Label>::iterator aFind = myNamingNames.find(theName);
1264 if (aFind != myNamingNames.end()) {
1265 return aFind->second;
1267 // not found exact name, try to find by sub-components
1268 std::string::size_type aSlash = theName.rfind('/');
1269 if (aSlash != std::string::npos) {
1270 std::string anObjName = theName.substr(0, aSlash);
1271 aFind = myNamingNames.find(anObjName);
1272 if (aFind != myNamingNames.end()) {
1273 TCollection_ExtendedString aSubName(theName.substr(aSlash + 1).c_str());
1274 // searching sub-labels with this name
1275 TDF_ChildIDIterator aNamesIter(aFind->second, TDataStd_Name::GetID(), Standard_True);
1276 for(; aNamesIter.More(); aNamesIter.Next()) {
1277 Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
1278 if (aName->Get() == aSubName)
1279 return aName->Label();
1281 // If not found child label with the exact sub-name, then try to find compound with
1282 // such sub-name without suffix.
1283 Standard_Integer aSuffixPos = aSubName.SearchFromEnd('_');
1284 if (aSuffixPos != -1) {
1285 TCollection_ExtendedString anIndexStr = aSubName.Split(aSuffixPos);
1286 aSubName.Remove(aSuffixPos);
1287 aNamesIter.Initialize(aFind->second, TDataStd_Name::GetID(), Standard_True);
1288 for(; aNamesIter.More(); aNamesIter.Next()) {
1289 Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
1290 if (aName->Get() == aSubName) {
1291 return aName->Label();
1297 return TDF_Label(); // not found
1300 ResultPtr Model_Document::findByName(const std::string theName)
1302 return myObjs->findByName(theName);
1305 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
1307 return myObjs->allFeatures();
1310 void Model_Document::setActive(const bool theFlag)
1312 if (theFlag != myIsActive) {
1313 myIsActive = theFlag;
1314 // redisplay all the objects of this part
1315 static Events_Loop* aLoop = Events_Loop::loop();
1316 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1318 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
1319 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
1320 object(ModelAPI_Feature::group(), a));
1321 if (aFeature.get() && aFeature->data()->isValid()) {
1322 const std::list<std::shared_ptr<ModelAPI_Result> >& aResList = aFeature->results();
1323 std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResList.begin();
1324 for(; aRes != aResList.end(); aRes++) {
1325 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
1326 // #issue 1048: sub-compsolids also
1327 ResultCompSolidPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRes);
1328 if (aCompRes.get()) {
1329 int aNumSubs = aCompRes->numberOfSubs();
1330 for(int a = 0; a < aNumSubs; a++) {
1331 ResultPtr aSub = aCompRes->subResult(a);
1333 ModelAPI_EventCreator::get()->sendUpdated(aSub, aRedispEvent);
1343 bool Model_Document::isActive() const
1348 int Model_Document::transactionID()
1350 Handle(TDataStd_Integer) anIndex;
1351 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
1352 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
1353 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
1355 return anIndex->Get();
1358 void Model_Document::incrementTransactionID()
1360 int aNewVal = transactionID() + 1;
1361 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1363 void Model_Document::decrementTransactionID()
1365 int aNewVal = transactionID() - 1;
1366 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1369 TDF_Label Model_Document::extConstructionsLabel() const
1371 return myDoc->Main().FindChild(TAG_EXTERNAL_CONSTRUCTIONS);
1374 bool Model_Document::isOpened()
1376 return myObjs && !myDoc.IsNull();
1379 int Model_Document::numInternalFeatures()
1381 return myObjs->numInternalFeatures();
1384 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
1386 return myObjs->internalFeature(theIndex);
1389 std::shared_ptr<ModelAPI_Feature> Model_Document::featureById(const int theId)
1391 return myObjs->featureById(theId);
1394 void Model_Document::synchronizeTransactions()
1396 Model_Document* aRoot =
1397 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
1399 return; // don't need to synchronise root with root
1401 std::shared_ptr<Model_Session> aSession =
1402 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
1403 while(myRedos.size() > aRoot->myRedos.size()) { // remove redos in this
1404 aSession->setCheckTransactions(false);
1406 aSession->setCheckTransactions(true);
1408 /* this case can not be reproduced in any known case for the current moment, so, just comment
1409 while(myRedos.size() < aRoot->myRedos.size()) { // add more redos in this
1410 undoInternal(false, true);
1414 /// Feature that is used for selection in the Part document by the external request
1415 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1417 /// Nothing to do in constructor
1418 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1420 /// Returns the unique kind of a feature
1421 virtual const std::string& getKind() {
1422 static std::string MY_KIND("InternalSelectionInPartFeature");
1425 /// Request for initialization of data model of the object: adding all attributes
1426 virtual void initAttributes() {
1427 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1429 /// Nothing to do in the execution function
1430 virtual void execute() {}
1434 //! Returns the feature that is used for calculation of selection externally from the document
1435 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1437 // return already created, otherwise create
1438 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1440 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1442 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1443 std::shared_ptr<Model_Data> aData(new Model_Data);
1444 aData->setLabel(aFeatureLab.FindChild(1));
1445 aData->setObject(mySelectionFeature);
1446 mySelectionFeature->setDoc(myObjs->owner());
1447 mySelectionFeature->setData(aData);
1448 std::string aName = id() + "_Part";
1449 mySelectionFeature->data()->setName(aName);
1450 mySelectionFeature->setDoc(myObjs->owner());
1451 mySelectionFeature->initAttributes();
1452 mySelectionFeature->init(); // to make it enabled and Update correctly
1453 // this update may cause recomputation of the part after selection on it, that is not needed
1454 mySelectionFeature->data()->blockSendAttributeUpdated(true);
1456 return mySelectionFeature->selectionList("selection");
1459 FeaturePtr Model_Document::lastFeature()
1462 return myObjs->lastFeature();
1463 return FeaturePtr();
1466 static Handle(TNaming_NamedShape) searchForOriginalShape(TopoDS_Shape theShape, TDF_Label aMain) {
1467 Handle(TNaming_NamedShape) aResult;
1468 while(!theShape.IsNull()) { // searching for the very initial shape that produces this one
1469 TopoDS_Shape aShape = theShape;
1471 // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
1472 if (!TNaming_Tool::HasLabel(aMain, aShape))
1474 for(TNaming_SameShapeIterator anIter(aShape, aMain); anIter.More(); anIter.Next()) {
1475 TDF_Label aNSLab = anIter.Label();
1476 Handle(TNaming_NamedShape) aNS;
1477 if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1478 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
1479 if (aShapesIter.Evolution() == TNaming_SELECTED ||
1480 aShapesIter.Evolution() == TNaming_DELETE)
1481 continue; // don't use the selection evolution
1482 if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
1484 if (aResult->Evolution() == TNaming_MODIFY)
1485 theShape = aShapesIter.OldShape();
1486 // otherwise may me searching for another item of this shape with longer history
1487 if (!theShape.IsNull())
1497 std::shared_ptr<ModelAPI_Feature> Model_Document::producedByFeature(
1498 std::shared_ptr<ModelAPI_Result> theResult,
1499 const std::shared_ptr<GeomAPI_Shape>& theShape)
1501 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
1503 return feature(theResult); // for not-body just returns the feature that produced this result
1505 // otherwise get the shape and search the very initial label for it
1506 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1507 if (aShape.IsNull())
1508 return FeaturePtr();
1510 // for comsolids and compounds all the naming is located in the main object, so, try to use
1512 ResultCompSolidPtr aMain = ModelAPI_Tools::compSolidOwner(theResult);
1514 FeaturePtr aMainRes = producedByFeature(aMain, theShape);
1519 std::shared_ptr<Model_Data> aBodyData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1520 if (!aBodyData.get() || !aBodyData->isValid())
1521 return FeaturePtr();
1523 TopoDS_Shape anOldShape; // old shape in the pair oldshape->theShape in the named shape
1524 TopoDS_Shape aShapeContainer; // old shape of the shape that contains aShape as sub-element
1525 Handle(TNaming_NamedShape) aCandidatInThis, aCandidatContainer;
1526 TDF_Label aBodyLab = aBodyData->label();
1527 // use childs and this label (the lowest priority)
1528 TDF_ChildIDIterator aNSIter(aBodyLab, TNaming_NamedShape::GetID(), Standard_True);
1529 bool aUseThis = !aNSIter.More();
1530 while(anOldShape.IsNull() && (aNSIter.More() || aUseThis)) {
1531 Handle(TNaming_NamedShape) aNS;
1533 if (!aBodyLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
1536 aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1538 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
1539 if (aShapesIter.Evolution() == TNaming_SELECTED || aShapesIter.Evolution() == TNaming_DELETE)
1540 continue; // don't use the selection evolution
1541 if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
1542 aCandidatInThis = aNS;
1543 if (aCandidatInThis->Evolution() == TNaming_MODIFY)
1544 anOldShape = aShapesIter.OldShape();
1545 // otherwise may me searching for another item of this shape with longer history
1546 if (!anOldShape.IsNull())
1549 // check that the shape contains aShape as sub-shape to fill container
1550 if (aShapesIter.NewShape().ShapeType() < aShape.ShapeType() && aCandidatContainer.IsNull()) {
1551 TopExp_Explorer anExp(aShapesIter.NewShape(), aShape.ShapeType());
1552 for(; anExp.More(); anExp.Next()) {
1553 if (aShape.IsSame(anExp.Current())) {
1554 aCandidatContainer = aNS;
1555 aShapeContainer = aShapesIter.NewShape();
1560 // iterate to the next label or to the body label in the end
1563 if (!aNSIter.More()) {
1569 if (aCandidatInThis.IsNull()) {
1570 // to fix 1512: searching for original shape of this shape
1571 // if modification of it is not in this result
1572 aCandidatInThis = searchForOriginalShape(aShape, myDoc->Main());
1573 if (aCandidatInThis.IsNull()) {
1574 if (aCandidatContainer.IsNull())
1575 return FeaturePtr();
1576 // with the lower priority use the higher level shape that contains aShape
1577 aCandidatInThis = aCandidatContainer;
1578 anOldShape = aShapeContainer;
1580 // to stop the searching by the following searchForOriginalShape
1581 anOldShape.Nullify();
1585 Handle(TNaming_NamedShape) aNS = searchForOriginalShape(anOldShape, myDoc->Main());
1587 aCandidatInThis = aNS;
1590 TDF_Label aResultLab = aCandidatInThis->Label();
1591 while(aResultLab.Depth() > 3)
1592 aResultLab = aResultLab.Father();
1593 FeaturePtr aFeature = myObjs->feature(aResultLab);
1594 if (aFeature.get()) {
1595 if (!aResult.get() || myObjs->isLater(aResult, aFeature)) {
1602 bool Model_Document::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
1604 return myObjs->isLater(theLater, theCurrent);
1607 void Model_Document::storeNodesState(const std::list<bool>& theStates)
1609 TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
1610 aLab.ForgetAllAttributes();
1611 if (!theStates.empty()) {
1612 Handle(TDataStd_BooleanArray) anArray =
1613 TDataStd_BooleanArray::Set(aLab, 0, int(theStates.size()) - 1);
1614 std::list<bool>::const_iterator aState = theStates.begin();
1615 for(int anIndex = 0; aState != theStates.end(); aState++, anIndex++) {
1616 anArray->SetValue(anIndex, *aState);
1621 void Model_Document::restoreNodesState(std::list<bool>& theStates) const
1623 TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
1624 Handle(TDataStd_BooleanArray) anArray;
1625 if (aLab.FindAttribute(TDataStd_BooleanArray::GetID(), anArray)) {
1626 int anUpper = anArray->Upper();
1627 for(int anIndex = 0; anIndex <= anUpper; anIndex++) {
1628 theStates.push_back(anArray->Value(anIndex) == Standard_True);