1 // Copyright (C) 2014-2017 CEA/DEN, EDF R&D
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
21 #include <Model_Document.h>
22 #include <Model_Data.h>
23 #include <Model_Objects.h>
24 #include <Model_Application.h>
25 #include <Model_Session.h>
26 #include <Model_Events.h>
27 #include <ModelAPI_ResultPart.h>
28 #include <ModelAPI_Validator.h>
29 #include <ModelAPI_CompositeFeature.h>
30 #include <ModelAPI_AttributeSelectionList.h>
31 #include <ModelAPI_Tools.h>
32 #include <ModelAPI_ResultBody.h>
33 #include <Events_Loop.h>
34 #include <Events_InfoMessage.h>
35 #include <GeomAPI_Tools.h>
37 #include <TDataStd_Integer.hxx>
38 #include <TDataStd_Comment.hxx>
39 #include <TDF_ChildIDIterator.hxx>
40 #include <TDataStd_ReferenceArray.hxx>
41 #include <TDataStd_ReferenceList.hxx>
42 #include <TDataStd_IntegerArray.hxx>
43 #include <TDataStd_HLabelArray1.hxx>
44 #include <TDataStd_Name.hxx>
45 #include <TDataStd_AsciiString.hxx>
46 #include <TDF_Reference.hxx>
47 #include <TDF_ChildIDIterator.hxx>
48 #include <TDF_Delta.hxx>
49 #include <TDF_AttributeDelta.hxx>
50 #include <TDF_AttributeDeltaList.hxx>
51 #include <TDF_ListIteratorOfAttributeDeltaList.hxx>
52 #include <TDF_ListIteratorOfLabelList.hxx>
53 #include <TDF_LabelMap.hxx>
54 #include <TDF_Tool.hxx>
55 #include <TDF_DeltaOnAddition.hxx>
56 #include <TDataStd_ExtStringList.hxx>
57 #include <TDataStd_UAttribute.hxx>
58 #include <TNaming_Builder.hxx>
59 #include <TNaming_SameShapeIterator.hxx>
60 #include <TNaming_Iterator.hxx>
61 #include <TNaming_NamedShape.hxx>
62 #include <TNaming_Tool.hxx>
63 #include<TNaming_OldShapeIterator.hxx>
64 #include <TopTools_DataMapOfShapeShape.hxx>
65 #include <TopTools_ListOfShape.hxx>
67 #include <TopExp_Explorer.hxx>
68 #include <TopoDS_Shape.hxx>
70 #include <OSD_File.hxx>
71 #include <OSD_Path.hxx>
72 #include <CDF_Session.hxx>
73 #include <CDF_Directory.hxx>
81 # define _separator_ '\\'
83 # define _separator_ '/'
86 static const int UNDO_LIMIT = 1000; // number of possible undo operations (big for sketcher)
88 static const int TAG_GENERAL = 1; // general properties tag
91 /// where the reference to the current feature label is located (or no attribute if null feature)
92 static const int TAG_CURRENT_FEATURE = 1; ///< reference to the current feature
93 /// integer, index of the transaction + GUID for auto recomputation blocking
94 static const int TAG_CURRENT_TRANSACTION = 2;
95 static const int TAG_SELECTION_FEATURE = 3; ///< integer, tag of the selection feature label
96 static const int TAG_NODES_STATE = 4; ///< array, tag of the Object Browser nodes states
97 ///< naming structures constructions selected from other document
98 static const int TAG_EXTERNAL_CONSTRUCTIONS = 5;
100 /// reference to the shape in external document: sting list attribute identifier
101 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
103 Model_Document::Model_Document(const int theID, const std::string theKind)
104 : myID(theID), myKind(theKind), myIsActive(false), myIsSetCurrentFeature(false),
105 myDoc(new TDocStd_Document("BinOcaf")) // binary OCAF format
108 CDF_Session::CurrentSession()->Directory()->Add(myDoc);
110 myObjs = new Model_Objects(myDoc->Main());
111 myDoc->SetUndoLimit(UNDO_LIMIT);
112 myTransactionSave = 0;
113 myExecuteFeatures = true;
114 // to have something in the document and avoid empty doc open/save problem
115 // in transaction for nesting correct working
117 TDataStd_Integer::Set(myDoc->Main().Father(), 0);
118 // this to avoid creation of integer attribute outside the transaction after undo
120 myDoc->CommitCommand();
123 void Model_Document::setThis(DocumentPtr theDoc)
125 myObjs->setOwner(theDoc);
128 /// Returns the file name of this document by the name of directory and identifier of a document
129 static TCollection_ExtendedString DocFileName(const char* theDirName, const std::string& theID)
131 TCollection_ExtendedString aPath((const Standard_CString) theDirName);
132 // remove end-separators
133 while(aPath.Length() &&
134 (aPath.Value(aPath.Length()) == '\\' || aPath.Value(aPath.Length()) == '/'))
135 aPath.Remove(aPath.Length());
136 aPath += _separator_;
137 aPath += theID.c_str();
138 aPath += ".cbf"; // standard binary file extension
142 bool Model_Document::isRoot() const
144 return this == Model_Session::get()->moduleDocument().get();
147 /// Makes all modification and generation naming shapes that have old shapes corresponding to
148 /// shapes in a root document be equal to this root document
149 static void updateShapesFromRoot(const TDF_Label theThisAccess, const TDF_Label theRootAccess)
151 TopTools_DataMapOfShapeShape aCurrentToRoot; // shapes that must be updated: from this to root
152 TDF_ChildIDIterator aThisIter(theThisAccess.Root(), kEXTERNAL_SHAPE_REF, true);
153 for(; aThisIter.More(); aThisIter.Next()) {
154 aCurrentToRoot.Clear();
155 Handle(TNaming_NamedShape) aNS;
156 if (!aThisIter.Value()->Label().FindAttribute(TNaming_NamedShape::GetID(), aNS))
158 if (aNS->Evolution() != TNaming_GENERATED && aNS->Evolution() != TNaming_MODIFY)
160 for (TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next()) {
161 const TopoDS_Shape& anOld = aNSIter.OldShape();
164 TNaming_OldShapeIterator aNewIter(anOld, theThisAccess);
165 for (; aNewIter.More(); aNewIter.Next()) {
166 TNaming_Evolution anEvolution = aNewIter.NamedShape()->Evolution();
167 if (anEvolution != TNaming_SELECTED && anEvolution != TNaming_DELETE)
172 GeomShapePtr anOldShape(new GeomAPI_Shape), aRootShape(new GeomAPI_Shape);
173 anOldShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(anOld));
174 anOldShape = GeomAPI_Tools::getTypedShape(anOldShape);
176 // search the same shape in the root document
177 Handle(TDataStd_ExtStringList) anEntries =
178 Handle(TDataStd_ExtStringList)::DownCast(aThisIter.Value());
179 TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
180 for (; anIter.More(); anIter.Next()) {
182 TDF_Tool::Label(theRootAccess.Data(), anIter.Value(), aRootLab);
183 if (aRootLab.IsNull())
185 Handle(TNaming_NamedShape) aRootNS;
186 if (!aRootLab.FindAttribute(TNaming_NamedShape::GetID(), aRootNS))
188 TNaming_Iterator aRootShapes(aRootNS);
189 for (; aRootShapes.More(); aRootShapes.Next()) {
190 if (aRootShapes.NewShape().IsNull())
192 aRootShape->setImpl(new TopoDS_Shape(aRootShapes.NewShape()));
193 aRootShape = GeomAPI_Tools::getTypedShape(aRootShape);
194 if (!anOldShape->isEqual(aRootShape)) // special checking by geometry
196 // found a good corresponded shape
197 if (!anOld.IsEqual(aRootShapes.NewShape()))
198 aCurrentToRoot.Bind(anOld, aRootShapes.NewShape());
202 if (!aCurrentToRoot.IsEmpty()) { // update the whole named shape content
203 TopTools_ListOfShape anOld, aNew;
204 TNaming_Evolution anEvol = aNS->Evolution();
205 for(TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next()) {
206 anOld.Prepend(aCurrentToRoot.IsBound(aNSIter.OldShape()) ?
207 aCurrentToRoot.Find(aNSIter.OldShape()) : aNSIter.OldShape());
208 aNew.Prepend(aNSIter.NewShape());
210 TNaming_Builder aBuilder(aNS->Label());
211 TopTools_ListOfShape::Iterator anOldIter(anOld), aNewIter(aNew);
212 for(; anOldIter.More(); anOldIter.Next(), aNewIter.Next()) {
213 if (anEvol == TNaming_GENERATED) {
214 aBuilder.Generated(anOldIter.Value(), aNewIter.Value());
215 } else if (anEvol == TNaming_MODIFY) {
216 aBuilder.Modify(anOldIter.Value(), aNewIter.Value());
223 bool Model_Document::load(const char* theDirName, const char* theFileName, DocumentPtr theThis)
225 Handle(Model_Application) anApp = Model_Application::getApplication();
227 anApp->setLoadPath(theDirName);
229 TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
230 PCDM_ReaderStatus aStatus = (PCDM_ReaderStatus) -1;
231 Handle(TDocStd_Document) aLoaded;
233 aStatus = anApp->Open(aPath, aLoaded);
234 } catch (Standard_Failure const& anException) {
235 Events_InfoMessage("Model_Document",
236 "Exception in opening of document: %1").arg(anException.GetMessageString()).send();
239 bool isError = aStatus != PCDM_RS_OK;
242 case PCDM_RS_UnknownDocument:
243 Events_InfoMessage("Model_Document", "Can not open document").send();
245 case PCDM_RS_AlreadyRetrieved:
246 Events_InfoMessage("Model_Document", "Can not open document: already opened").send();
248 case PCDM_RS_AlreadyRetrievedAndModified:
249 Events_InfoMessage("Model_Document",
250 "Can not open document: already opened and modified").send();
252 case PCDM_RS_NoDriver:
253 Events_InfoMessage("Model_Document",
254 "Can not open document: driver library is not found").send();
256 case PCDM_RS_UnknownFileDriver:
257 Events_InfoMessage("Model_Document",
258 "Can not open document: unknown driver for opening").send();
260 case PCDM_RS_OpenError:
261 Events_InfoMessage("Model_Document", "Can not open document: file open error").send();
263 case PCDM_RS_NoVersion:
264 Events_InfoMessage("Model_Document", "Can not open document: invalid version").send();
266 case PCDM_RS_NoModel:
267 Events_InfoMessage("Model_Document", "Can not open document: no data model").send();
269 case PCDM_RS_NoDocument:
270 Events_InfoMessage("Model_Document", "Can not open document: no document inside").send();
272 case PCDM_RS_FormatFailure:
273 Events_InfoMessage("Model_Document", "Can not open document: format failure").send();
275 case PCDM_RS_TypeNotFoundInSchema:
276 Events_InfoMessage("Model_Document", "Can not open document: invalid object").send();
278 case PCDM_RS_UnrecognizedFileFormat:
279 Events_InfoMessage("Model_Document",
280 "Can not open document: unrecognized file format").send();
282 case PCDM_RS_MakeFailure:
283 Events_InfoMessage("Model_Document", "Can not open document: make failure").send();
285 case PCDM_RS_PermissionDenied:
286 Events_InfoMessage("Model_Document", "Can not open document: permission denied").send();
288 case PCDM_RS_DriverFailure:
289 Events_InfoMessage("Model_Document", "Can not open document: driver failure").send();
292 Events_InfoMessage("Model_Document", "Can not open document: unknown error").send();
296 std::shared_ptr<Model_Session> aSession =
297 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
300 myDoc->SetUndoLimit(UNDO_LIMIT);
302 // to avoid the problem that feature is created in the current, not this, document
303 aSession->setActiveDocument(anApp->document(myID), false);
304 aSession->setCheckTransactions(false);
307 myObjs = new Model_Objects(myDoc->Main()); // synchronization is inside
308 myObjs->setOwner(theThis);
309 // update the current features status
310 setCurrentFeature(currentFeature(false), false);
311 aSession->setCheckTransactions(true);
312 aSession->setActiveDocument(aSession->moduleDocument(), false);
313 // this is done in Part result "activate", so no needed here. Causes not-blue active part.
314 // aSession->setActiveDocument(anApp->getDocument(myID), true);
316 // make sub-parts as loaded by demand
317 std::list<ResultPtr> aPartResults;
318 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
319 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
320 for(; aPartRes != aPartResults.end(); aPartRes++) {
321 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
323 anApp->setLoadByDemand(aPart->data()->name(),
324 aPart->data()->document(ModelAPI_ResultPart::DOC_REF())->docId());
327 updateShapesFromRoot(myDoc->Main(),
328 std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument())->generalLabel());
330 } else { // open failed, but new document was created to work with it: inform the model
331 aSession->setActiveDocument(Model_Session::get()->moduleDocument(), false);
336 bool Model_Document::save(
337 const char* theDirName, const char* theFileName, std::list<std::string>& theResults)
339 // if the history line is not in the end, move it to the end before save, otherwise
340 // problems with results restore and (the most important) naming problems will appear
341 // due to change evolution to SELECTION (problems in NamedShape and Name)
342 FeaturePtr aWasCurrent;
343 std::shared_ptr<Model_Session> aSession =
344 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
345 if (currentFeature(false) != lastFeature()) {
346 aSession->setCheckTransactions(false);
347 aWasCurrent = currentFeature(false);
348 // if last is nested into something else, make this something else as last:
349 // otherwise it will look like edition of sub-element, so, the main will be disabled
350 FeaturePtr aLast = lastFeature();
352 CompositeFeaturePtr aMain = ModelAPI_Tools::compositeOwner(aLast);
355 aMain = ModelAPI_Tools::compositeOwner(aLast);
358 setCurrentFeature(aLast, true);
360 // create a directory in the root document if it is not yet exist
361 Handle(Model_Application) anApp = Model_Application::getApplication();
364 CreateDirectory((LPTSTR) theDirName, NULL);
366 mkdir(theDirName, 0x1ff);
369 // filename in the dir is id of document inside of the given directory
370 TCollection_ExtendedString aPath(DocFileName(theDirName, theFileName));
371 PCDM_StoreStatus aStatus;
373 aStatus = anApp->SaveAs(myDoc, aPath);
374 } catch (Standard_Failure const& anException) {
375 Events_InfoMessage("Model_Document",
376 "Exception in saving of document: %1").arg(anException.GetMessageString()).send();
377 if (aWasCurrent.get()) { // return the current feature to the initial position
378 setCurrentFeature(aWasCurrent, false);
379 aSession->setCheckTransactions(true);
383 bool isDone = aStatus == PCDM_SS_OK || aStatus == PCDM_SS_No_Obj;
386 case PCDM_SS_DriverFailure:
387 Events_InfoMessage("Model_Document",
388 "Can not save document: save driver-library failure").send();
390 case PCDM_SS_WriteFailure:
391 Events_InfoMessage("Model_Document", "Can not save document: file writing failure").send();
393 case PCDM_SS_Failure:
395 Events_InfoMessage("Model_Document", "Can not save document").send();
400 if (aWasCurrent.get()) { // return the current feature to the initial position
401 setCurrentFeature(aWasCurrent, false);
402 aSession->setCheckTransactions(true);
405 myTransactionSave = int(myTransactions.size());
406 if (isDone) { // save also sub-documents if any
407 theResults.push_back(TCollection_AsciiString(aPath).ToCString());
408 // iterate all result parts to find all loaded or not yet loaded documents
409 std::list<ResultPtr> aPartResults;
410 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
411 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
412 for(; aPartRes != aPartResults.end(); aPartRes++) {
413 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
414 if (!aPart->isActivated()) {
415 // copy not-activated document that is not in the memory
416 std::string aDocName = aPart->data()->name();
417 if (!aDocName.empty()) {
419 TCollection_AsciiString aSubPath(DocFileName(anApp->loadPath().c_str(), aDocName));
420 OSD_Path aPath(aSubPath);
421 OSD_File aFile(aPath);
422 if (aFile.Exists()) {
423 TCollection_AsciiString aDestinationDir(DocFileName(theDirName, aDocName));
424 OSD_Path aDestination(aDestinationDir);
425 aFile.Copy(aDestination);
426 theResults.push_back(aDestinationDir.ToCString());
428 Events_InfoMessage("Model_Document",
429 "Can not open file %1 for saving").arg(aSubPath.ToCString()).send();
432 } else { // simply save opened document
433 isDone = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc())->
434 save(theDirName, aPart->data()->name().c_str(), theResults);
441 void Model_Document::close(const bool theForever)
443 std::shared_ptr<ModelAPI_Session> aPM = Model_Session::get();
444 if (!isRoot() && this == aPM->activeDocument().get()) {
445 aPM->setActiveDocument(aPM->moduleDocument());
446 } else if (isRoot()) {
447 // erase the active document if root is closed
448 aPM->setActiveDocument(DocumentPtr());
451 const std::set<int> aSubs = subDocuments();
452 std::set<int>::iterator aSubIter = aSubs.begin();
453 for (; aSubIter != aSubs.end(); aSubIter++) {
454 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
455 if (aSub->myObjs) // if it was not closed before
456 aSub->close(theForever);
459 // close for this document needs no transaction in this document
460 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(false);
462 // close all only if it is really asked, otherwise it can be undone/redone
464 // flush everything to avoid messages with bad objects
467 if (myDoc->CanClose() == CDM_CCS_OK)
469 mySelectionFeature.reset();
471 setCurrentFeature(FeaturePtr(), false); // disables all features
472 // update the OB: features are disabled (on remove of Part)
473 Events_Loop* aLoop = Events_Loop::loop();
474 static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
475 aLoop->flush(aDeleteEvent);
478 std::static_pointer_cast<Model_Session>(Model_Session::get())->setCheckTransactions(true);
481 void Model_Document::startOperation()
483 incrementTransactionID(); // outside of transaction in order to avoid empty transactions keeping
484 if (myDoc->HasOpenCommand()) { // start of nested command
485 if (myDoc->CommitCommand()) {
486 // commit the current: it will contain all nested after compactification
487 myTransactions.rbegin()->myOCAFNum++; // if has open command, the list is not empty
489 myNestedNum.push_back(0); // start of nested operation with zero transactions inside yet
490 myDoc->OpenCommand();
491 } else { // start the simple command
494 // starts a new operation
495 myTransactions.push_back(Transaction());
496 if (!myNestedNum.empty())
497 (*myNestedNum.rbegin())++;
499 // new command for all subs
500 const std::set<int> aSubs = subDocuments();
501 std::set<int>::iterator aSubIter = aSubs.begin();
502 for (; aSubIter != aSubs.end(); aSubIter++)
503 subDoc(*aSubIter)->startOperation();
506 void Model_Document::compactNested()
508 if (!myNestedNum.empty()) {
509 int aNumToCompact = *(myNestedNum.rbegin());
510 int aSumOfTransaction = 0;
511 for(int a = 0; a < aNumToCompact; a++) {
512 aSumOfTransaction += myTransactions.rbegin()->myOCAFNum;
513 myTransactions.pop_back();
515 // the latest transaction is the start of lower-level operation which starts the nested
516 myTransactions.rbegin()->myOCAFNum += aSumOfTransaction;
517 myNestedNum.pop_back();
521 /// Compares the content of the given attributes, returns true if equal.
522 /// This method is used to avoid empty transactions when only "current" is changed
523 /// to some value and then comes back in this transaction, so, it compares only
524 /// references and Boolean and Integer Arrays for the current moment.
525 static bool isEqualContent(Handle(TDF_Attribute) theAttr1, Handle(TDF_Attribute) theAttr2)
527 if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_Reference::GetID())) { // reference
528 Handle(TDF_Reference) aRef1 = Handle(TDF_Reference)::DownCast(theAttr1);
529 Handle(TDF_Reference) aRef2 = Handle(TDF_Reference)::DownCast(theAttr2);
530 if (aRef1.IsNull() && aRef2.IsNull())
532 if (aRef1.IsNull() || aRef2.IsNull())
534 return aRef1->Get().IsEqual(aRef2->Get()) == Standard_True;
535 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_BooleanArray::GetID())) {
536 Handle(TDataStd_BooleanArray) anArr1 = Handle(TDataStd_BooleanArray)::DownCast(theAttr1);
537 Handle(TDataStd_BooleanArray) anArr2 = Handle(TDataStd_BooleanArray)::DownCast(theAttr2);
538 if (anArr1.IsNull() && anArr2.IsNull())
540 if (anArr1.IsNull() || anArr2.IsNull())
542 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
543 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++) {
544 if (a == 1 && // second is for display
545 anArr2->Label().Tag() == 1 && (anArr2->Label().Depth() == 4 ||
546 anArr2->Label().Depth() == 6))
548 if (anArr1->Value(a) != anArr2->Value(a))
553 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_IntegerArray::GetID())) {
554 Handle(TDataStd_IntegerArray) anArr1 = Handle(TDataStd_IntegerArray)::DownCast(theAttr1);
555 Handle(TDataStd_IntegerArray) anArr2 = Handle(TDataStd_IntegerArray)::DownCast(theAttr2);
556 if (anArr1.IsNull() && anArr2.IsNull())
558 if (anArr1.IsNull() || anArr2.IsNull())
560 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
561 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
562 if (anArr1->Value(a) != anArr2->Value(a)) {
563 // avoid the transaction ID checking
564 if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
565 (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
571 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceArray::GetID())) {
572 Handle(TDataStd_ReferenceArray) anArr1 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr1);
573 Handle(TDataStd_ReferenceArray) anArr2 = Handle(TDataStd_ReferenceArray)::DownCast(theAttr2);
574 if (anArr1.IsNull() && anArr2.IsNull())
576 if (anArr1.IsNull() || anArr2.IsNull())
578 if (anArr1->Lower() == anArr2->Lower() && anArr1->Upper() == anArr2->Upper()) {
579 for(int a = anArr1->Lower(); a <= anArr1->Upper(); a++)
580 if (anArr1->Value(a) != anArr2->Value(a)) {
581 // avoid the transaction ID checking
582 if (a == 2 && anArr1->Upper() == 2 && anArr2->Label().Tag() == 1 &&
583 (anArr2->Label().Depth() == 4 || anArr2->Label().Depth() == 6))
589 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDataStd_ReferenceList::GetID())) {
590 Handle(TDataStd_ReferenceList) aList1 = Handle(TDataStd_ReferenceList)::DownCast(theAttr1);
591 Handle(TDataStd_ReferenceList) aList2= Handle(TDataStd_ReferenceList)::DownCast(theAttr2);
592 if (aList1.IsNull() && aList2.IsNull())
594 if (aList1.IsNull() || aList2.IsNull())
596 const TDF_LabelList& aLList1 = aList1->List();
597 const TDF_LabelList& aLList2 = aList2->List();
598 TDF_ListIteratorOfLabelList aLIter1(aLList1);
599 TDF_ListIteratorOfLabelList aLIter2(aLList2);
600 for(; aLIter1.More() && aLIter2.More(); aLIter1.Next(), aLIter2.Next()) {
601 if (aLIter1.Value() != aLIter2.Value())
604 return !aLIter1.More() && !aLIter2.More(); // both lists are with the same size
605 } else if (Standard_GUID::IsEqual(theAttr1->ID(), TDF_TagSource::GetID())) {
606 return true; // it just for created and removed feature: nothing is changed
611 /// Returns true if the last transaction is actually empty: modification to the same values
612 /// were performed only
613 static bool isEmptyTransaction(const Handle(TDocStd_Document)& theDoc) {
614 Handle(TDF_Delta) aDelta;
615 aDelta = theDoc->GetUndos().Last();
616 TDF_LabelList aDeltaList;
617 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
618 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
621 // add also label of the modified attributes
622 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
623 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
624 Handle(TDF_AttributeDelta)& anADelta = anAttr.Value();
625 Handle(TDF_DeltaOnAddition) anAddition = Handle(TDF_DeltaOnAddition)::DownCast(anADelta);
626 if (anAddition.IsNull()) { // if the attribute was added, transaction is not empty
627 if (!anADelta->Label().IsNull() && !anADelta->Attribute().IsNull()) {
628 Handle(TDF_Attribute) aCurrentAttr;
629 if (anADelta->Label().FindAttribute(anADelta->Attribute()->ID(), aCurrentAttr)) {
630 if (isEqualContent(anADelta->Attribute(), aCurrentAttr)) {
631 continue; // attribute is not changed actually
634 if (Standard_GUID::IsEqual(anADelta->Attribute()->ID(), TDataStd_AsciiString::GetID())) {
635 continue; // error message is disappeared
644 bool Model_Document::finishOperation()
646 bool isNestedClosed = !myDoc->HasOpenCommand() && !myNestedNum.empty();
647 static std::shared_ptr<Model_Session> aSession =
648 std::static_pointer_cast<Model_Session>(Model_Session::get());
650 // open transaction if nested is closed to fit inside
651 // all synchronizeBackRefs and flushed consequences
652 if (isNestedClosed) {
653 myDoc->OpenCommand();
655 // do it before flashes to enable and recompute nesting features correctly
656 if (myNestedNum.empty() || (isNestedClosed && myNestedNum.size() == 1)) {
657 // if all nested operations are closed, make current the higher level objects (to perform
658 // it in the python scripts correctly): sketch become current after creation of sub-elements
659 FeaturePtr aCurrent = currentFeature(false);
660 CompositeFeaturePtr aMain, aNext = ModelAPI_Tools::compositeOwner(aCurrent);
663 aNext = ModelAPI_Tools::compositeOwner(aMain);
665 if (aMain.get() && aMain != aCurrent)
666 setCurrentFeature(aMain, false);
668 myObjs->synchronizeBackRefs();
669 Events_Loop* aLoop = Events_Loop::loop();
670 static const Events_ID kCreatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_CREATED);
671 static const Events_ID kUpdatedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
672 static const Events_ID kRedispEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
673 static const Events_ID kDeletedEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_DELETED);
674 aLoop->flush(kCreatedEvent);
675 aLoop->flush(kUpdatedEvent);
676 aLoop->flush(kRedispEvent);
677 aLoop->flush(kDeletedEvent);
679 if (isNestedClosed) {
680 if (myDoc->CommitCommand())
681 myTransactions.rbegin()->myOCAFNum++;
684 // this must be here just after everything is finished but before real transaction stop
685 // to avoid messages about modifications outside of the transaction
686 // and to rebuild everything after all updates and creates
687 if (isRoot()) { // once for root document
688 static std::shared_ptr<Events_Message> aFinishMsg
689 (new Events_Message(Events_Loop::eventByName("FinishOperation")));
690 Events_Loop::loop()->send(aFinishMsg);
693 // for open of document with primitive box inside (finish transaction in initAttributes)
694 bool aWasActivatedFlushes = aLoop->activateFlushes(true);
695 while(aLoop->hasGrouppedEvent(kCreatedEvent) || aLoop->hasGrouppedEvent(kUpdatedEvent) ||
696 aLoop->hasGrouppedEvent(kRedispEvent) || aLoop->hasGrouppedEvent(kDeletedEvent)) {
697 aLoop->flush(kCreatedEvent);
698 aLoop->flush(kUpdatedEvent);
699 aLoop->flush(kRedispEvent);
700 aLoop->flush(kDeletedEvent);
702 aLoop->activateFlushes(aWasActivatedFlushes);
704 // to avoid "updated" message appearance by updater
705 //aLoop->clear(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
707 // finish for all subs first: to avoid nested finishing and "isOperation" calls problems inside
708 bool aResult = false;
709 const std::set<int> aSubs = subDocuments();
710 std::set<int>::iterator aSubIter = aSubs.begin();
711 for (; aSubIter != aSubs.end(); aSubIter++)
712 if (subDoc(*aSubIter)->finishOperation())
715 // transaction may be empty if this document was created during this transaction (create part)
716 if (!myTransactions.empty() && myDoc->CommitCommand()) {
717 // if commit is successful, just increment counters
718 if (isEmptyTransaction(myDoc)) { // erase this transaction
722 myTransactions.rbegin()->myOCAFNum++;
727 if (isNestedClosed) {
730 if (!aResult && !myTransactions.empty() /* it can be for just created part document */)
731 aResult = myTransactions.rbegin()->myOCAFNum != 0;
733 if (!aResult && isRoot()) {
734 // nothing inside in all documents, so remove this transaction from the transactions list
735 undoInternal(true, false);
737 // on finish clear redo in any case (issue 446) and for all subs (issue 408)
740 for (aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
741 subDoc(*aSubIter)->myDoc->ClearRedos();
742 subDoc(*aSubIter)->myRedos.clear();
748 /// Returns in theDelta labels that has been modified in the latest transaction of theDoc
749 static void modifiedLabels(const Handle(TDocStd_Document)& theDoc, TDF_LabelList& theDelta,
750 const bool isRedo = false) {
751 Handle(TDF_Delta) aDelta;
753 aDelta = theDoc->GetRedos().First();
755 aDelta = theDoc->GetUndos().Last();
756 TDF_LabelList aDeltaList;
757 aDelta->Labels(aDeltaList); // it clears list, so, use new one and then append to the result
758 for(TDF_ListIteratorOfLabelList aListIter(aDeltaList); aListIter.More(); aListIter.Next()) {
759 theDelta.Append(aListIter.Value());
761 // add also label of the modified attributes
762 const TDF_AttributeDeltaList& anAttrs = aDelta->AttributeDeltas();
763 /// named shape evolution also modifies integer on this label: exclude it
764 TDF_LabelMap anExcludedInt;
765 for (TDF_ListIteratorOfAttributeDeltaList anAttr(anAttrs); anAttr.More(); anAttr.Next()) {
766 if (anAttr.Value()->Attribute()->ID() == TDataStd_BooleanArray::GetID()) {
767 // Boolean array is used for feature auxiliary attributes only, feature args are not modified
770 if (anAttr.Value()->Attribute()->ID() == TNaming_NamedShape::GetID()) {
771 anExcludedInt.Add(anAttr.Value()->Label());
772 // named shape evolution is changed in history update => skip them,
773 // they are not the features arguments
776 if (anAttr.Value()->Attribute()->ID() == TDataStd_Integer::GetID()) {
777 if (anExcludedInt.Contains(anAttr.Value()->Label()))
780 theDelta.Append(anAttr.Value()->Label());
782 TDF_ListIteratorOfLabelList aDeltaIter(theDelta);
783 for(; aDeltaIter.More(); aDeltaIter.Next()) {
784 if (anExcludedInt.Contains(aDeltaIter.Value())) {
785 theDelta.Remove(aDeltaIter);
786 if (!aDeltaIter.More())
792 void Model_Document::abortOperation()
794 TDF_LabelList aDeltaLabels; // labels that are updated during "abort"
795 if (!myNestedNum.empty() && !myDoc->HasOpenCommand()) { // abort all what was done in nested
797 // store undo-delta here as undo actually does in the method later
798 int a, aNumTransactions = myTransactions.rbegin()->myOCAFNum;
799 for(a = 0; a < aNumTransactions; a++) {
800 modifiedLabels(myDoc, aDeltaLabels);
803 for(a = 0; a < aNumTransactions; a++) {
807 undoInternal(false, false);
810 } else { // abort the current
811 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
812 myTransactions.pop_back();
813 if (!myNestedNum.empty())
814 (*myNestedNum.rbegin())--;
815 // roll back the needed number of transactions
816 //myDoc->AbortCommand();
817 // instead of abort, do commit and undo: to get the delta of modifications
818 if (myDoc->CommitCommand()) {
819 modifiedLabels(myDoc, aDeltaLabels);
822 for(int a = 0; a < aNumTransactions; a++) {
823 modifiedLabels(myDoc, aDeltaLabels);
828 // abort for all subs, flushes will be later, in the end of root abort
829 const std::set<int> aSubs = subDocuments();
830 std::set<int>::iterator aSubIter = aSubs.begin();
831 for (; aSubIter != aSubs.end(); aSubIter++)
832 subDoc(*aSubIter)->abortOperation();
833 // references may be changed because they are set in attributes on the fly
834 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
837 bool Model_Document::isOperation() const
839 // operation is opened for all documents: no need to check subs
840 return myDoc->HasOpenCommand() == Standard_True ;
843 bool Model_Document::isModified()
845 // is modified if at least one operation was committed and not undone
846 return myTransactions.size() != myTransactionSave || isOperation();
849 bool Model_Document::canUndo()
851 // issue 406 : if transaction is opened, but nothing to undo behind, can not undo
852 int aCurrentNum = isOperation() ? 1 : 0;
853 if (myDoc->GetAvailableUndos() > 0 &&
854 // there is something to undo in nested
855 (myNestedNum.empty() || *myNestedNum.rbegin() - aCurrentNum > 0) &&
856 myTransactions.size() - aCurrentNum > 0 /* for omitting the first useless transaction */)
858 // check other subs contains operation that can be undone
859 const std::set<int> aSubs = subDocuments();
860 std::set<int>::iterator aSubIter = aSubs.begin();
861 for (; aSubIter != aSubs.end(); aSubIter++) {
862 std::shared_ptr<Model_Document> aSub = subDoc(*aSubIter);
863 if (aSub->myObjs) {// if it was not closed before
872 void Model_Document::undoInternal(const bool theWithSubs, const bool theSynchronize)
874 if (myTransactions.empty())
876 int aNumTransactions = myTransactions.rbegin()->myOCAFNum;
877 myRedos.push_back(*myTransactions.rbegin());
878 myTransactions.pop_back();
879 if (!myNestedNum.empty())
880 (*myNestedNum.rbegin())--;
881 // roll back the needed number of transactions
882 TDF_LabelList aDeltaLabels;
883 for(int a = 0; a < aNumTransactions; a++) {
885 modifiedLabels(myDoc, aDeltaLabels);
891 const std::set<int> aSubs = subDocuments();
892 std::set<int>::iterator aSubIter = aSubs.begin();
893 for (; aSubIter != aSubs.end(); aSubIter++) {
894 if (!subDoc(*aSubIter)->myObjs)
896 subDoc(*aSubIter)->undoInternal(theWithSubs, theSynchronize);
899 // after undo of all sub-documents to avoid updates on not-modified data (issue 370)
900 if (theSynchronize) {
901 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
902 // update the current features status
903 setCurrentFeature(currentFeature(false), false);
907 void Model_Document::undo()
909 undoInternal(true, true);
912 bool Model_Document::canRedo()
914 if (!myRedos.empty())
916 // check other subs contains operation that can be redone
917 const std::set<int> aSubs = subDocuments();
918 std::set<int>::iterator aSubIter = aSubs.begin();
919 for (; aSubIter != aSubs.end(); aSubIter++) {
920 if (!subDoc(*aSubIter)->myObjs)
922 if (subDoc(*aSubIter)->canRedo())
928 void Model_Document::redo()
930 if (!myNestedNum.empty())
931 (*myNestedNum.rbegin())++;
932 int aNumRedos = myRedos.rbegin()->myOCAFNum;
933 myTransactions.push_back(*myRedos.rbegin());
935 TDF_LabelList aDeltaLabels;
936 for(int a = 0; a < aNumRedos; a++) {
937 modifiedLabels(myDoc, aDeltaLabels, true);
942 const std::set<int> aSubs = subDocuments();
943 std::set<int>::iterator aSubIter = aSubs.begin();
944 for (; aSubIter != aSubs.end(); aSubIter++)
945 subDoc(*aSubIter)->redo();
947 // after redo of all sub-documents to avoid updates on not-modified data (issue 370)
948 myObjs->synchronizeFeatures(aDeltaLabels, true, false, false, isRoot());
949 // update the current features status
950 setCurrentFeature(currentFeature(false), false);
953 std::list<std::string> Model_Document::undoList() const
955 std::list<std::string> aResult;
956 // the number of skipped current operations (on undo they will be aborted)
957 int aSkipCurrent = isOperation() ? 1 : 0;
958 std::list<Transaction>::const_reverse_iterator aTrIter = myTransactions.crbegin();
959 int aNumUndo = int(myTransactions.size());
960 if (!myNestedNum.empty())
961 aNumUndo = *myNestedNum.rbegin();
962 for( ; aNumUndo > 0; aTrIter++, aNumUndo--) {
963 if (aSkipCurrent == 0) aResult.push_back(aTrIter->myId);
969 std::list<std::string> Model_Document::redoList() const
971 std::list<std::string> aResult;
972 std::list<Transaction>::const_reverse_iterator aTrIter = myRedos.crbegin();
973 for( ; aTrIter != myRedos.crend(); aTrIter++) {
974 aResult.push_back(aTrIter->myId);
979 void Model_Document::operationId(const std::string& theId)
981 myTransactions.rbegin()->myId = theId;
984 FeaturePtr Model_Document::addFeature(std::string theID, const bool theMakeCurrent)
986 std::shared_ptr<Model_Session> aSession =
987 std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
988 FeaturePtr aFeature = aSession->createFeature(theID, this);
992 Model_Document* aDocToAdd;
993 if (!aFeature->documentToAdd().empty()) { // use the customized document to add
994 if (aFeature->documentToAdd() != kind()) { // the root document by default
995 aDocToAdd = std::dynamic_pointer_cast<Model_Document>(aSession->moduleDocument()).get();
999 } else { // if customized is not presented, add to "this" document
1003 // searching for feature after which must be added the next feature: this is the current feature
1004 // but also all sub-features of this feature
1005 FeaturePtr aCurrent = aDocToAdd->currentFeature(false);
1006 bool isModified = true;
1007 for(CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent);
1008 aComp.get() && isModified;
1009 aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aCurrent)) {
1011 int aSubs = aComp->numberOfSubs(false);
1012 for(int a = 0; a < aSubs; a++) {
1013 FeaturePtr aSub = aComp->subFeature(a, false);
1014 if (aSub && myObjs->isLater(aSub, aCurrent)) {
1020 aDocToAdd->myObjs->addFeature(aFeature, aCurrent);
1021 if (!aFeature->isAction()) { // do not add action to the data model
1022 if (theMakeCurrent) // after all this feature stays in the document, so make it current
1023 aDocToAdd->setCurrentFeature(aFeature, false);
1024 } else { // feature must be executed
1025 // no creation event => updater not working, problem with remove part
1026 aFeature->execute();
1033 void Model_Document::refsToFeature(FeaturePtr theFeature,
1034 std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
1036 myObjs->refsToFeature(theFeature, theRefs, isSendError);
1039 void Model_Document::removeFeature(FeaturePtr theFeature)
1041 myObjs->removeFeature(theFeature);
1042 // fix for #2723: send signal that part is updated
1044 std::shared_ptr<Model_Document> aRoot =
1045 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument());
1046 std::list<ResultPtr> allParts;
1047 aRoot->objects()->allResults(ModelAPI_ResultPart::group(), allParts);
1048 std::list<ResultPtr>::iterator aParts = allParts.begin();
1049 for(; aParts != allParts.end(); aParts++) {
1050 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aParts);
1051 if (aPart->partDoc().get() == this) {
1052 static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1053 ModelAPI_EventCreator::get()->sendUpdated(aRoot->feature(aPart), anEvent);
1060 // recursive function to check if theSub is a child of theMain composite feature
1061 // through all the hierarchy of parents
1062 static bool isSub(const CompositeFeaturePtr theMain, const FeaturePtr theSub) {
1063 CompositeFeaturePtr aParent = ModelAPI_Tools::compositeOwner(theSub);
1066 if (aParent == theMain)
1068 return isSub(theMain, aParent);
1072 void Model_Document::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
1074 bool aCurrentUp = theMoved == currentFeature(false);
1076 setCurrentFeatureUp();
1078 // if user adds after high-level feature with nested,
1079 // add it after all nested (otherwise the nested will be disabled)
1080 CompositeFeaturePtr aCompositeAfter =
1081 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theAfterThis);
1082 FeaturePtr anAfterThisSub = theAfterThis;
1083 if (aCompositeAfter.get()) {
1084 FeaturePtr aSub = aCompositeAfter;
1085 int anIndex = kUNDEFINED_FEATURE_INDEX;
1087 FeaturePtr aNext = myObjs->nextFeature(aSub, anIndex);
1088 if (!isSub(aCompositeAfter, aNext)) {
1089 anAfterThisSub = aSub;
1093 } while (aSub.get());
1096 myObjs->moveFeature(theMoved, anAfterThisSub);
1097 if (aCurrentUp) { // make the moved feature enabled or disabled due to the real status
1098 setCurrentFeature(currentFeature(false), false);
1099 } else if (theAfterThis == currentFeature(false) || anAfterThisSub == currentFeature(false)) {
1100 // must be after move to make enabled all features which are before theMoved
1101 setCurrentFeature(theMoved, true);
1105 void Model_Document::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
1108 myObjs->updateHistory(theObject);
1111 void Model_Document::updateHistory(const std::string theGroup)
1114 myObjs->updateHistory(theGroup);
1117 const std::set<int> Model_Document::subDocuments() const
1119 std::set<int> aResult;
1120 std::list<ResultPtr> aPartResults;
1121 myObjs->allResults(ModelAPI_ResultPart::group(), aPartResults);
1122 std::list<ResultPtr>::iterator aPartRes = aPartResults.begin();
1123 for(; aPartRes != aPartResults.end(); aPartRes++) {
1124 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(*aPartRes);
1125 if (aPart && aPart->isActivated()) {
1126 aResult.insert(aPart->original()->partDoc()->id());
1132 std::shared_ptr<Model_Document> Model_Document::subDoc(int theDocID)
1134 // just store sub-document identifier here to manage it later
1135 return std::dynamic_pointer_cast<Model_Document>(
1136 Model_Application::getApplication()->document(theDocID));
1139 ObjectPtr Model_Document::object(const std::string& theGroupID,
1141 const bool theAllowFolder)
1143 return myObjs->object(theGroupID, theIndex, theAllowFolder);
1146 std::shared_ptr<ModelAPI_Object> Model_Document::objectByName(
1147 const std::string& theGroupID, const std::string& theName)
1149 return myObjs->objectByName(theGroupID, theName);
1152 const int Model_Document::index(std::shared_ptr<ModelAPI_Object> theObject,
1153 const bool theAllowFolder)
1155 return myObjs->index(theObject, theAllowFolder);
1158 int Model_Document::size(const std::string& theGroupID, const bool theAllowFolder)
1160 if (myObjs == 0) // may be on close
1162 return myObjs->size(theGroupID, theAllowFolder);
1165 std::shared_ptr<ModelAPI_Object> Model_Document::parent(
1166 const std::shared_ptr<ModelAPI_Object> theChild)
1168 if(myObjs == 0) // may be on close
1170 return myObjs->parent(theChild);
1173 std::shared_ptr<ModelAPI_Feature> Model_Document::currentFeature(const bool theVisible)
1175 if (!myObjs) // on close document feature destruction it may call this method
1176 return std::shared_ptr<ModelAPI_Feature>();
1177 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
1178 Handle(TDF_Reference) aRef;
1179 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1180 TDF_Label aLab = aRef->Get();
1181 FeaturePtr aResult = myObjs->feature(aLab);
1182 if (theVisible) { // get nearest visible (in history) going up
1183 int anIndex = kUNDEFINED_FEATURE_INDEX;
1184 while(aResult.get() && !aResult->isInHistory()) {
1185 aResult = myObjs->nextFeature(aResult, anIndex, true);
1190 return std::shared_ptr<ModelAPI_Feature>(); // null feature means the higher than first
1193 void Model_Document::setCurrentFeature(
1194 std::shared_ptr<ModelAPI_Feature> theCurrent, const bool theVisible)
1196 if (myIsSetCurrentFeature)
1198 myIsSetCurrentFeature = true;
1199 // blocks the flush signals to avoid each objects visualization in the viewer
1200 // they should not be shown once after all modifications are performed
1201 Events_Loop* aLoop = Events_Loop::loop();
1202 bool isActive = aLoop->activateFlushes(false);
1204 TDF_Label aRefLab = generalLabel().FindChild(TAG_CURRENT_FEATURE);
1205 CompositeFeaturePtr aMain; // main feature that may nest the new current
1206 std::set<FeaturePtr> anOwners; // composites that contain theCurrent (with any level of nesting)
1207 if (theCurrent.get()) {
1208 aMain = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theCurrent);
1209 CompositeFeaturePtr anOwner = ModelAPI_Tools::compositeOwner(theCurrent);
1210 while(anOwner.get()) {
1214 anOwners.insert(anOwner);
1215 anOwner = ModelAPI_Tools::compositeOwner(anOwner);
1219 if (theVisible && !theCurrent.get()) {
1220 // needed to avoid disabling of PartSet initial constructions
1221 int anIndex = kUNDEFINED_FEATURE_INDEX;
1223 theCurrent.get() ? myObjs->nextFeature(theCurrent, anIndex, false) : myObjs->firstFeature();
1224 for (; aNext.get(); aNext = myObjs->nextFeature(theCurrent, anIndex, false)) {
1225 if (aNext->isInHistory()) {
1226 break; // next in history is not needed
1227 } else { // next not in history is good for making current
1232 if (theCurrent.get()) {
1233 std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1234 if (!aData.get() || !aData->isValid()) {
1235 aLoop->activateFlushes(isActive);
1236 myIsSetCurrentFeature = false;
1239 TDF_Label aFeatureLabel = aData->label().Father();
1241 Handle(TDF_Reference) aRef;
1242 if (aRefLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1243 aRef->Set(aFeatureLabel);
1245 aRef = TDF_Reference::Set(aRefLab, aFeatureLabel);
1247 } else { // remove reference for the null feature
1248 aRefLab.ForgetAttribute(TDF_Reference::GetID());
1250 // make all features after this feature disabled in reversed order
1251 // (to remove results without dependencies)
1252 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1254 bool aPassed = false; // flag that the current object is already passed in cycle
1255 FeaturePtr anIter = myObjs->lastFeature();
1256 bool aWasChanged = false;
1257 bool isCurrentParameter = theCurrent.get() && theCurrent->getKind() == "Parameter";
1258 int anIndex = kUNDEFINED_FEATURE_INDEX;
1259 for(; anIter.get(); anIter = myObjs->nextFeature(anIter, anIndex, true)) {
1260 // check this before passed become enabled: the current feature is enabled!
1261 if (anIter == theCurrent) aPassed = true;
1263 bool aDisabledFlag = !aPassed;
1265 if (isSub(aMain, anIter)) // sub-elements of not-disabled feature are not disabled
1266 aDisabledFlag = false;
1267 else if (anOwners.find(anIter) != anOwners.end())
1268 // disable the higher-level feature if the nested is the current
1269 if (aMain->getKind() != "Import") // exception for the import XAO feature with Group (2430)
1270 aDisabledFlag = true;
1273 if (anIter->getKind() == "Parameter") {
1274 // parameters are always out of the history of features, but not parameters
1275 // due to the issue 1491 all parameters are kept enabled any time
1276 //if (!isCurrentParameter)
1277 aDisabledFlag = false;
1278 } else if (isCurrentParameter) {
1279 // if parameter is active, all other features become enabled (issue 1307)
1280 aDisabledFlag = false;
1283 if (anIter->setDisabled(aDisabledFlag)) {
1284 static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
1285 // state of feature is changed => so inform that it must be updated if it has such state
1286 if (!aDisabledFlag &&
1287 (anIter->data()->execState() == ModelAPI_StateMustBeUpdated ||
1288 anIter->data()->execState() == ModelAPI_StateInvalidArgument))
1289 ModelAPI_EventCreator::get()->sendUpdated(anIter, anUpdateEvent);
1290 // flush is in the end of this method
1291 ModelAPI_EventCreator::get()->sendUpdated(anIter, aRedispEvent /*, false*/);
1294 // update for everyone concealment flag immediately: on edit feature in the middle of history
1296 std::list<ResultPtr> aResults;
1297 ModelAPI_Tools::allResults(anIter, aResults);
1298 std::list<ResultPtr>::const_iterator aRes = aResults.begin();
1299 for(; aRes != aResults.end(); aRes++) {
1300 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1301 std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->updateConcealmentFlag();
1303 // update the concealment status for display in isConcealed of ResultBody
1304 for(aRes = aResults.begin(); aRes != aResults.end(); aRes++) {
1305 if ((*aRes).get() && (*aRes)->data()->isValid() && !(*aRes)->isDisabled())
1306 (*aRes)->isConcealed();
1310 myIsSetCurrentFeature = false;
1311 // unblock the flush signals and up them after this
1312 aLoop->activateFlushes(isActive);
1315 void Model_Document::setCurrentFeatureUp()
1317 // on remove just go up for minimum step: highlight external objects in sketch causes
1318 // problems if it is true: here and in "setCurrentFeature"
1319 FeaturePtr aCurrent = currentFeature(false);
1320 if (aCurrent.get()) { // if not, do nothing because null is the upper
1321 int anIndex = kUNDEFINED_FEATURE_INDEX;
1322 FeaturePtr aPrev = myObjs->nextFeature(aCurrent, anIndex, true);
1323 // make the higher level composite as current (sketch becomes disabled if line is enabled)
1325 FeaturePtr aComp = ModelAPI_Tools::compositeOwner(aPrev);
1326 // without cycle (issue 1555): otherwise extrusion fuse
1327 // will be enabled and displayed when inside sketch
1331 // do not flush: it is called only on remove, it will be flushed in the end of transaction
1332 setCurrentFeature(aPrev, false);
1336 TDF_Label Model_Document::generalLabel() const
1338 return myDoc->Main().FindChild(TAG_GENERAL);
1341 std::shared_ptr<ModelAPI_ResultConstruction> Model_Document::createConstruction(
1342 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1344 return myObjs->createConstruction(theFeatureData, theIndex);
1347 std::shared_ptr<ModelAPI_ResultBody> Model_Document::createBody(
1348 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1350 return myObjs->createBody(theFeatureData, theIndex);
1353 std::shared_ptr<ModelAPI_ResultPart> Model_Document::createPart(
1354 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1356 return myObjs->createPart(theFeatureData, theIndex);
1359 std::shared_ptr<ModelAPI_ResultPart> Model_Document::copyPart(
1360 const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1361 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1363 return myObjs->copyPart(theOrigin, theFeatureData, theIndex);
1366 std::shared_ptr<ModelAPI_ResultGroup> Model_Document::createGroup(
1367 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1369 return myObjs->createGroup(theFeatureData, theIndex);
1372 std::shared_ptr<ModelAPI_ResultField> Model_Document::createField(
1373 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1375 return myObjs->createField(theFeatureData, theIndex);
1378 std::shared_ptr<ModelAPI_ResultParameter> Model_Document::createParameter(
1379 const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1381 return myObjs->createParameter(theFeatureData, theIndex);
1384 std::shared_ptr<ModelAPI_Folder> Model_Document::addFolder(
1385 std::shared_ptr<ModelAPI_Feature> theAddBefore)
1387 return myObjs->createFolder(theAddBefore);
1390 void Model_Document::removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder)
1393 myObjs->removeFolder(theFolder);
1396 std::shared_ptr<ModelAPI_Folder> Model_Document::findFolderAbove(
1397 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures)
1399 return myObjs->findFolder(theFeatures, false);
1402 std::shared_ptr<ModelAPI_Folder> Model_Document::findFolderBelow(
1403 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures)
1405 return myObjs->findFolder(theFeatures, true);
1408 std::shared_ptr<ModelAPI_Folder> Model_Document::findContainingFolder(
1409 const std::shared_ptr<ModelAPI_Feature>& theFeature,
1410 int& theIndexInFolder)
1412 return myObjs->findContainingFolder(theFeature, theIndexInFolder);
1415 bool Model_Document::moveToFolder(
1416 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1417 const std::shared_ptr<ModelAPI_Folder>& theFolder)
1419 return myObjs->moveToFolder(theFeatures, theFolder);
1422 bool Model_Document::removeFromFolder(
1423 const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1424 const bool theBefore)
1426 return myObjs->removeFromFolder(theFeatures, theBefore);
1429 std::shared_ptr<ModelAPI_Feature> Model_Document::feature(
1430 const std::shared_ptr<ModelAPI_Result>& theResult)
1432 if (myObjs == 0) // may be on close
1433 return std::shared_ptr<ModelAPI_Feature>();
1434 return myObjs->feature(theResult);
1437 FeaturePtr Model_Document::featureByLab(const TDF_Label& theLab) {
1438 TDF_Label aCurrentLab = theLab;
1439 while(aCurrentLab.Depth() > 3)
1440 aCurrentLab = aCurrentLab.Father();
1441 return myObjs->feature(aCurrentLab);
1444 ResultPtr Model_Document::resultByLab(const TDF_Label& theLab)
1446 TDF_Label aCurrentLab = theLab;
1447 while(aCurrentLab.Depth() > 3) {
1448 ObjectPtr aResultObj = myObjs->object(aCurrentLab);
1449 if (aResultObj.get()) {
1450 return std::dynamic_pointer_cast<ModelAPI_Result>(aResultObj); // this may be null if feature
1452 aCurrentLab = aCurrentLab.Father();
1454 return ResultPtr(); // not found
1458 void Model_Document::addNamingName(const TDF_Label theLabel, std::string theName)
1460 std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
1462 if (aFind != myNamingNames.end()) { // to avoid duplicate-labels
1463 // to keep correct order in spite of history line management
1464 std::list<TDF_Label>::iterator anAddAfterThis = aFind->second.end();
1465 FeaturePtr anAddedFeature = featureByLab(theLabel);
1466 std::list<TDF_Label>::iterator aLabIter = aFind->second.begin();
1467 while(aLabIter != aFind->second.end()) {
1468 if (theLabel.IsEqual(*aLabIter)) {
1469 std::list<TDF_Label>::iterator aTmpIter = aLabIter;
1471 aFind->second.erase(aTmpIter);
1473 FeaturePtr aCurFeature = featureByLab(*aLabIter);
1474 if (aCurFeature.get() && anAddedFeature.get() &&
1475 myObjs->isLater(anAddedFeature, aCurFeature))
1476 anAddAfterThis = aLabIter;
1481 if (anAddAfterThis != aFind->second.end()) {
1483 if (anAddAfterThis != aFind->second.end()) {
1484 myNamingNames[theName].insert(anAddAfterThis, theLabel); // inserts before anAddAfterThis
1489 myNamingNames[theName].push_back(theLabel);
1492 void Model_Document::changeNamingName(const std::string theOldName,
1493 const std::string theNewName,
1494 const TDF_Label& theLabel)
1496 std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theOldName);
1497 if (aFind != myNamingNames.end()) {
1498 std::list<TDF_Label>::iterator aLabIter = aFind->second.begin();
1499 for(; aLabIter != aFind->second.end(); aLabIter++) {
1500 if (theLabel.IsEqual(*aLabIter)) { // found the label
1501 myNamingNames[theNewName].push_back(theLabel);
1502 if (aFind->second.size() == 1) { // only one element, so, just change the name
1503 myNamingNames.erase(theOldName);
1504 } else { // remove from the list
1505 aFind->second.erase(aLabIter);
1507 // check the sketch vertex name located under renamed sketch line
1508 TDF_ChildIDIterator aChild(theLabel, TDataStd_Name::GetID());
1509 for(; aChild.More(); aChild.Next()) {
1510 Handle(TDataStd_Name) aSubName = Handle(TDataStd_Name)::DownCast(aChild.Value());
1511 std::string aName = TCollection_AsciiString(aSubName->Get()).ToCString();
1512 if (aName.find(theOldName) == 0) { // started from parent name
1513 std::string aNewSubName = theNewName + aName.substr(theNewName.size());
1514 changeNamingName(aName, aNewSubName, aSubName->Label());
1515 aSubName->Set(aNewSubName.c_str());
1524 TDF_Label Model_Document::findNamingName(std::string theName, ResultPtr theContext)
1526 std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(theName);
1527 if (aFind != myNamingNames.end()) {
1528 std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1529 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1530 if (theContext.get()) {
1531 // context is defined and not like this, so, skip
1532 if (theContext == myObjs->object(aLabIter->Father()))
1536 return *(aFind->second.rbegin()); // no more variants, so, return the last
1538 // not found exact name, try to find by sub-components
1539 std::string::size_type aSlash = theName.rfind('/');
1540 if (aSlash != std::string::npos) {
1541 std::string anObjName = theName.substr(0, aSlash);
1542 aFind = myNamingNames.find(anObjName);
1543 if (aFind != myNamingNames.end()) {
1544 TCollection_ExtendedString aSubName(theName.substr(aSlash + 1).c_str());
1545 // iterate all possible same-named labels starting from the last one (the recent)
1546 std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1547 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1548 if (theContext.get()) {
1549 // context is defined and not like this, so, skip
1550 if (theContext != myObjs->object(aLabIter->Father()))
1553 // copy aSubName to avoid incorrect further processing after its suffix cutting
1554 TCollection_ExtendedString aSubNameCopy(aSubName);
1555 // searching sub-labels with this name
1556 TDF_ChildIDIterator aNamesIter(*aLabIter, TDataStd_Name::GetID(), Standard_True);
1557 for(; aNamesIter.More(); aNamesIter.Next()) {
1558 Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
1559 if (aName->Get() == aSubNameCopy)
1560 return aName->Label();
1562 // If not found child label with the exact sub-name, then try to find compound with
1563 // such sub-name without suffix.
1564 Standard_Integer aSuffixPos = aSubNameCopy.SearchFromEnd('_');
1565 if (aSuffixPos != -1 && aSuffixPos != aSubNameCopy.Length()) {
1566 TCollection_ExtendedString anIndexStr = aSubNameCopy.Split(aSuffixPos);
1567 aSubNameCopy.Remove(aSuffixPos);
1568 aNamesIter.Initialize(*aLabIter, TDataStd_Name::GetID(), Standard_True);
1569 for(; aNamesIter.More(); aNamesIter.Next()) {
1570 Handle(TDataStd_Name) aName = Handle(TDataStd_Name)::DownCast(aNamesIter.Value());
1571 if (aName->Get() == aSubNameCopy) {
1572 return aName->Label();
1575 // check also "this" label
1576 Handle(TDataStd_Name) aName;
1577 if (aLabIter->FindAttribute(TDataStd_Name::GetID(), aName)) {
1578 if (aName->Get() == aSubNameCopy) {
1579 return aName->Label();
1584 // verify context's name is same as sub-component's and use context's label
1585 if (aSubName.IsEqual(anObjName.c_str()))
1586 return *(aFind->second.rbegin());
1589 return TDF_Label(); // not found
1592 bool Model_Document::isLaterByDep(FeaturePtr theThis, FeaturePtr theOther) {
1593 // check dependencies first: if theOther depends on theThis, theThis is not later
1594 std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
1595 theOther->data()->referencesToObjects(aRefs);
1596 std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > >::iterator
1597 aRefIt = aRefs.begin();
1598 for(; aRefIt != aRefs.end(); aRefIt++) {
1599 std::list<ObjectPtr>::iterator aRefObjIt = aRefIt->second.begin();
1600 for(; aRefObjIt != aRefIt->second.end(); aRefObjIt++) {
1601 ObjectPtr aRefObj = *aRefObjIt;
1602 if (aRefObj.get()) {
1603 FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(aRefObj);
1604 if (!aRefFeat.get()) { // take feature of the result
1605 aRefFeat = feature(std::dynamic_pointer_cast<ModelAPI_Result>(aRefObj));
1607 if (aRefFeat.get()) {
1608 if (aRefFeat == theThis)
1609 return false; // other references to this, so other later than this
1610 //if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aRefFeat)) {
1611 // if (!isLaterByDep(theThis, aRefFeat)) // nested composites: recursion
1618 FeaturePtr aThisOwner = ModelAPI_Tools::compositeOwner(theThis);
1619 if (aThisOwner.get()) {
1620 if (aThisOwner == theOther)
1621 return true; // composite owner is later that its sub
1622 if (!isLaterByDep(aThisOwner, theOther))
1625 return myObjs->isLater(theThis, theOther);
1628 int Model_Document::numberOfNameInHistory(
1629 const ObjectPtr& theNameObject, const TDF_Label& theStartFrom)
1631 std::map<std::string, std::list<TDF_Label> >::iterator aFind =
1632 myNamingNames.find(theNameObject->data()->name());
1633 if (aFind == myNamingNames.end() || aFind->second.size() < 2) {
1634 return 1; // no need to specify the name by additional identifiers
1636 // get the feature of the object for relative compare
1637 FeaturePtr aStart = myObjs->feature(theStartFrom);
1638 if (!aStart.get()) // strange, but can not find feature by the label
1640 // feature that contain result with this name
1641 FeaturePtr aNameFeature;
1642 ResultPtr aNameResult = std::dynamic_pointer_cast<ModelAPI_Result>(theNameObject);
1644 aNameFeature = myObjs->feature(aNameResult);
1646 aNameFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theNameObject);
1647 // iterate all labels with this name to find the nearest just before or equal relative
1648 std::list<TDF_Label>::reverse_iterator aLabIter = aFind->second.rbegin();
1649 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1650 FeaturePtr aLabFeat = featureByLab(*aLabIter);
1651 if (!aLabFeat.get())
1653 if (isLaterByDep(aStart, aLabFeat)) // skip also start: its result don't used
1657 for(; aLabIter != aFind->second.rend(); aLabIter++) {
1658 FeaturePtr aLabFeat = featureByLab(*aLabIter);
1659 if (!aLabFeat.get())
1661 if (aLabFeat == aNameFeature || isLaterByDep(aNameFeature, aLabFeat))
1665 return aResIndex; // strange
1668 ResultPtr Model_Document::findByName(
1669 std::string& theName, std::string& theSubShapeName, bool& theUniqueContext)
1671 int aNumInHistory = 0;
1672 std::string aName = theName;
1673 ResultPtr aRes = myObjs->findByName(aName);
1674 theUniqueContext = !(aRes.get() && myNamingNames.find(aName) != myNamingNames.end());
1675 while(!aRes.get() && aName[0] == '_') { // this may be theContext with the history index
1677 aName = aName.substr(1);
1678 aRes = myObjs->findByName(aName);
1680 if (aNumInHistory) {
1681 std::map<std::string, std::list<TDF_Label> >::iterator aFind = myNamingNames.find(aName);
1682 if (aFind != myNamingNames.end() && aFind->second.size() > aNumInHistory) {
1683 std::list<TDF_Label>::reverse_iterator aLibIt = aFind->second.rbegin();
1684 for(; aNumInHistory != 0; aNumInHistory--)
1686 const TDF_Label& aResultLab = *aLibIt;
1687 aRes = std::dynamic_pointer_cast<ModelAPI_Result>(myObjs->object(aResultLab.Father()));
1688 if (aRes) { // modify the incoming names
1689 if (!theSubShapeName.empty())
1690 theSubShapeName = theSubShapeName.substr(theName.size() - aName.size());
1698 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Document::allFeatures()
1700 return myObjs->allFeatures();
1703 std::list<std::shared_ptr<ModelAPI_Object> > Model_Document::allObjects()
1705 return myObjs->allObjects();
1708 void Model_Document::setActive(const bool theFlag)
1710 if (theFlag != myIsActive) {
1711 myIsActive = theFlag;
1712 // redisplay all the objects of this part
1713 static Events_Loop* aLoop = Events_Loop::loop();
1714 static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1716 for(int a = size(ModelAPI_Feature::group()) - 1; a >= 0; a--) {
1717 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(
1718 object(ModelAPI_Feature::group(), a));
1719 if (aFeature.get() && aFeature->data()->isValid()) {
1720 std::list<ResultPtr> aResults;
1721 ModelAPI_Tools::allResults(aFeature, aResults);
1722 for (std::list<ResultPtr>::iterator aRes = aResults.begin();
1723 aRes != aResults.end(); aRes++) {
1724 ModelAPI_EventCreator::get()->sendUpdated(*aRes, aRedispEvent);
1731 bool Model_Document::isActive() const
1736 int Model_Document::transactionID()
1738 Handle(TDataStd_Integer) anIndex;
1739 if (!generalLabel().FindChild(TAG_CURRENT_TRANSACTION).
1740 FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
1741 anIndex = TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), 1);
1743 return anIndex->Get();
1746 void Model_Document::incrementTransactionID()
1748 int aNewVal = transactionID() + 1;
1749 TDataStd_Integer::Set(generalLabel().FindChild(TAG_CURRENT_TRANSACTION), aNewVal);
1752 TDF_Label Model_Document::extConstructionsLabel() const
1754 return myDoc->Main().FindChild(TAG_EXTERNAL_CONSTRUCTIONS);
1757 bool Model_Document::isOpened()
1759 return myObjs && !myDoc.IsNull();
1762 int Model_Document::numInternalFeatures()
1764 return myObjs->numInternalFeatures();
1767 std::shared_ptr<ModelAPI_Feature> Model_Document::internalFeature(const int theIndex)
1769 return myObjs->internalFeature(theIndex);
1772 void Model_Document::synchronizeTransactions()
1774 Model_Document* aRoot =
1775 std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument()).get();
1777 return; // don't need to synchronize root with root
1779 std::shared_ptr<Model_Session> aSession =
1780 std::dynamic_pointer_cast<Model_Session>(Model_Session::get());
1781 while(myRedos.size() > aRoot->myRedos.size()) { // remove redo in this
1782 aSession->setCheckTransactions(false);
1784 aSession->setCheckTransactions(true);
1786 /* this case can not be reproduced in any known case for the current moment, so, just comment
1787 while(myRedos.size() < aRoot->myRedos.size()) { // add more redo in this
1788 undoInternal(false, true);
1792 /// Feature that is used for selection in the Part document by the external request
1793 class Model_SelectionInPartFeature : public ModelAPI_Feature {
1795 /// Nothing to do in constructor
1796 Model_SelectionInPartFeature() : ModelAPI_Feature() {}
1798 /// Returns the unique kind of a feature
1799 virtual const std::string& getKind() {
1800 static std::string MY_KIND("InternalSelectionInPartFeature");
1803 /// Request for initialization of data model of the object: adding all attributes
1804 virtual void initAttributes() {
1805 data()->addAttribute("selection", ModelAPI_AttributeSelectionList::typeId());
1807 /// Nothing to do in the execution function
1808 virtual void execute() {}
1812 //! Returns the feature that is used for calculation of selection externally from the document
1813 AttributeSelectionListPtr Model_Document::selectionInPartFeature()
1815 // return already created, otherwise create
1816 if (!mySelectionFeature.get() || !mySelectionFeature->data()->isValid()) {
1818 mySelectionFeature = FeaturePtr(new Model_SelectionInPartFeature);
1820 TDF_Label aFeatureLab = generalLabel().FindChild(TAG_SELECTION_FEATURE);
1821 std::shared_ptr<Model_Data> aData(new Model_Data);
1822 aData->setLabel(aFeatureLab.FindChild(1));
1823 aData->setObject(mySelectionFeature);
1824 mySelectionFeature->setDoc(myObjs->owner());
1825 mySelectionFeature->setData(aData);
1826 std::string aName = id() + "_Part";
1827 mySelectionFeature->data()->setName(aName);
1828 mySelectionFeature->setDoc(myObjs->owner());
1829 mySelectionFeature->initAttributes();
1830 mySelectionFeature->init(); // to make it enabled and Update correctly
1831 // this update may cause recomputation of the part after selection on it, that is not needed
1832 mySelectionFeature->data()->blockSendAttributeUpdated(true);
1834 return mySelectionFeature->selectionList("selection");
1837 FeaturePtr Model_Document::lastFeature()
1840 return myObjs->lastFeature();
1841 return FeaturePtr();
1844 static Handle(TNaming_NamedShape) searchForOriginalShape(TopoDS_Shape theShape, TDF_Label aMain) {
1845 Handle(TNaming_NamedShape) aResult;
1846 while(!theShape.IsNull()) { // searching for the very initial shape that produces this one
1847 TopoDS_Shape aShape = theShape;
1849 // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
1850 if (!TNaming_Tool::HasLabel(aMain, aShape))
1852 for(TNaming_SameShapeIterator anIter(aShape, aMain); anIter.More(); anIter.Next()) {
1853 TDF_Label aNSLab = anIter.Label();
1854 Handle(TNaming_NamedShape) aNS;
1855 if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1856 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
1857 if (aShapesIter.Evolution() == TNaming_SELECTED ||
1858 aShapesIter.Evolution() == TNaming_DELETE)
1859 continue; // don't use the selection evolution
1860 if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
1862 if (aResult->Evolution() == TNaming_MODIFY)
1863 theShape = aShapesIter.OldShape();
1864 // otherwise may me searching for another item of this shape with longer history
1865 if (!theShape.IsNull())
1875 std::shared_ptr<ModelAPI_Feature> Model_Document::producedByFeature(
1876 std::shared_ptr<ModelAPI_Result> theResult,
1877 const std::shared_ptr<GeomAPI_Shape>& theShape)
1879 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theResult);
1881 return feature(theResult); // for not-body just returns the feature that produced this result
1883 // otherwise get the shape and search the very initial label for it
1884 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1885 if (aShape.IsNull())
1886 return FeaturePtr();
1888 // for compsolids and compounds all the naming is located in the main object, so, try to use
1890 ResultBodyPtr aMain = ModelAPI_Tools::bodyOwner(theResult);
1891 while (aMain.get()) { // get the top-most main
1892 ResultBodyPtr aNextMain = ModelAPI_Tools::bodyOwner(aMain);
1893 if (aNextMain.get())
1898 FeaturePtr aMainRes = producedByFeature(aMain, theShape);
1903 std::shared_ptr<Model_Data> aBodyData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1904 if (!aBodyData.get() || !aBodyData->isValid())
1905 return FeaturePtr();
1907 TopoDS_Shape anOldShape; // old shape in the pair old shape->theShape in the named shape
1908 TopoDS_Shape aShapeContainer; // old shape of the shape that contains aShape as sub-element
1909 Handle(TNaming_NamedShape) aCandidatInThis, aCandidatContainer;
1910 TDF_Label aBodyLab = aBodyData->shapeLab();
1911 // use child and this label (the lowest priority)
1912 TDF_ChildIDIterator aNSIter(aBodyLab, TNaming_NamedShape::GetID(), Standard_True);
1913 bool aUseThis = !aNSIter.More();
1914 while(anOldShape.IsNull() && (aNSIter.More() || aUseThis)) {
1915 Handle(TNaming_NamedShape) aNS;
1917 if (!aBodyLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
1920 aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1922 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
1923 if (aShapesIter.Evolution() == TNaming_SELECTED || aShapesIter.Evolution() == TNaming_DELETE)
1924 continue; // don't use the selection evolution
1925 if (aShapesIter.NewShape().IsSame(aShape)) { // found the original shape
1926 aCandidatInThis = aNS;
1927 if (aCandidatInThis->Evolution() == TNaming_MODIFY)
1928 anOldShape = aShapesIter.OldShape();
1929 // otherwise may me searching for another item of this shape with longer history
1930 if (!anOldShape.IsNull())
1933 // check that the shape contains aShape as sub-shape to fill container
1934 if (aShapesIter.NewShape().ShapeType() < aShape.ShapeType() && aCandidatContainer.IsNull()) {
1935 TopExp_Explorer anExp(aShapesIter.NewShape(), aShape.ShapeType());
1936 for(; anExp.More(); anExp.Next()) {
1937 if (aShape.IsSame(anExp.Current())) {
1938 aCandidatContainer = aNS;
1939 aShapeContainer = aShapesIter.NewShape();
1944 // iterate to the next label or to the body label in the end
1947 if (!aNSIter.More()) {
1953 if (aCandidatInThis.IsNull()) {
1954 // to fix 1512: searching for original shape of this shape
1955 // if modification of it is not in this result
1956 aCandidatInThis = searchForOriginalShape(aShape, myDoc->Main());
1957 if (aCandidatInThis.IsNull()) {
1958 if (aCandidatContainer.IsNull())
1959 return FeaturePtr();
1960 // with the lower priority use the higher level shape that contains aShape
1961 aCandidatInThis = aCandidatContainer;
1962 anOldShape = aShapeContainer;
1964 // to stop the searching by the following searchForOriginalShape
1965 anOldShape.Nullify();
1969 Handle(TNaming_NamedShape) aNS = searchForOriginalShape(anOldShape, myDoc->Main());
1971 aCandidatInThis = aNS;
1974 TDF_Label aResultLab = aCandidatInThis->Label();
1975 while(aResultLab.Depth() > 3)
1976 aResultLab = aResultLab.Father();
1977 FeaturePtr aFeature = myObjs->feature(aResultLab);
1978 if (aFeature.get()) {
1979 if (!aResult.get() || myObjs->isLater(aResult, aFeature)) {
1986 bool Model_Document::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
1988 return myObjs->isLater(theLater, theCurrent);
1991 void Model_Document::storeNodesState(const std::list<bool>& theStates)
1993 TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
1994 aLab.ForgetAllAttributes();
1995 if (!theStates.empty()) {
1996 Handle(TDataStd_BooleanArray) anArray =
1997 TDataStd_BooleanArray::Set(aLab, 0, int(theStates.size()) - 1);
1998 std::list<bool>::const_iterator aState = theStates.begin();
1999 for(int anIndex = 0; aState != theStates.end(); aState++, anIndex++) {
2000 anArray->SetValue(anIndex, *aState);
2005 void Model_Document::restoreNodesState(std::list<bool>& theStates) const
2007 TDF_Label aLab = generalLabel().FindChild(TAG_NODES_STATE);
2008 Handle(TDataStd_BooleanArray) anArray;
2009 if (aLab.FindAttribute(TDataStd_BooleanArray::GetID(), anArray)) {
2010 int anUpper = anArray->Upper();
2011 for(int anIndex = 0; anIndex <= anUpper; anIndex++) {
2012 theStates.push_back(anArray->Value(anIndex) == Standard_True);
2017 void Model_Document::eraseAllFeatures()
2020 myObjs->eraseAllFeatures();
2023 void Model_Document::setExecuteFeatures(const bool theFlag)
2025 myExecuteFeatures = theFlag;
2026 const std::set<int> aSubs = subDocuments();
2027 std::set<int>::iterator aSubIter = aSubs.begin();
2028 for (; aSubIter != aSubs.end(); aSubIter++) {
2029 if (!subDoc(*aSubIter)->myObjs)
2031 subDoc(*aSubIter)->setExecuteFeatures(theFlag);
2035 void Model_Document::appendTransactionToPrevious()
2037 Transaction anAppended = myTransactions.back();
2038 myTransactions.pop_back();
2039 if (!myTransactions.empty()) { // if it is empty, just forget the appended
2040 myTransactions.back().myOCAFNum += anAppended.myOCAFNum;
2042 // propagate the same action to sub-documents
2043 const std::set<int> aSubs = subDocuments();
2044 for (std::set<int>::iterator aSubIter = aSubs.begin(); aSubIter != aSubs.end(); aSubIter++) {
2045 subDoc(*aSubIter)->appendTransactionToPrevious();
2049 /// GUID for keeping information about the auto-recomputation state
2050 static const Standard_GUID kAutoRecomputationID("8493fb74-0674-4912-a100-1cf46c7cfab3");
2052 void Model_Document::setAutoRecomutationState(const bool theState)
2055 generalLabel().FindChild(TAG_CURRENT_TRANSACTION).ForgetAttribute(kAutoRecomputationID);
2057 TDataStd_UAttribute::Set(
2058 generalLabel().FindChild(TAG_CURRENT_TRANSACTION), kAutoRecomputationID);
2061 bool Model_Document::autoRecomutationState() const
2063 return !generalLabel().FindChild(TAG_CURRENT_TRANSACTION).IsAttribute(kAutoRecomputationID);