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_AttributeSelection.h"
22 #include "Model_Application.h"
23 #include "Model_Events.h"
24 #include "Model_Data.h"
25 #include "Model_Document.h"
26 #include "Model_SelectionNaming.h"
27 #include <Model_Objects.h>
28 #include <Model_AttributeSelectionList.h>
29 #include <Model_ResultConstruction.h>
30 #include <ModelAPI_Feature.h>
31 #include <ModelAPI_ResultBody.h>
32 #include <ModelAPI_ResultCompSolid.h>
33 #include <ModelAPI_ResultConstruction.h>
34 #include <ModelAPI_ResultPart.h>
35 #include <ModelAPI_CompositeFeature.h>
36 #include <ModelAPI_Tools.h>
37 #include <ModelAPI_Session.h>
38 #include <Events_InfoMessage.h>
40 #include <TNaming_Selector.hxx>
41 #include <TNaming_NamedShape.hxx>
42 #include <TNaming_Tool.hxx>
43 #include <TNaming_Builder.hxx>
44 #include <TNaming_SameShapeIterator.hxx>
45 #include <TNaming_Iterator.hxx>
46 #include <TDataStd_Integer.hxx>
47 #include <TDataStd_UAttribute.hxx>
48 #include <TDataStd_Name.hxx>
49 #include <TopTools_ListOfShape.hxx>
50 #include <TopTools_DataMapOfShapeShape.hxx>
51 #include <TopTools_MapOfShape.hxx>
52 #include <TopExp_Explorer.hxx>
53 #include <BRep_Tool.hxx>
56 #include <TDF_ChildIterator.hxx>
57 #include <TDF_ChildIDIterator.hxx>
58 #include <TopoDS_Iterator.hxx>
59 #include <TDF_ChildIDIterator.hxx>
61 //#define DEB_NAMING 1
63 #include <BRepTools.hxx>
65 /// added to the index in the packed map to signalize that the vertex of edge is selected
66 /// (multiplied by the index of the edge)
67 static const int kSTART_VERTEX_DELTA = 1000000;
68 // identifier that there is simple reference: selection equals to context
69 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
70 // reference to Part sub-object
71 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
72 // selection is invalid after recomputation
73 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
75 // on this label is stored:
76 // TNaming_NamedShape - selected shape
77 // TNaming_Naming - topological selection information (for the body)
78 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
79 // TDataStd_Integer - type of the selected shape (for construction)
80 // TDF_Reference - from ReferenceAttribute, the context
81 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
82 const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
84 if (theTemporarily) { // just keep the stored without DF update
85 myTmpContext = theContext;
86 myTmpSubShape = theSubShape;
87 owner()->data()->sendAttributeUpdated(this);
91 myTmpSubShape.reset();
94 const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
95 bool isOldContext = theContext == myRef.value();
96 bool isOldShape = isOldContext &&
97 (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
98 if (isOldShape) return; // shape is the same, so context is also unchanged
99 // update the referenced object if needed
101 myRef.setValue(theContext);
104 // do noth use naming if selected shape is result shape itself, but not sub-shape
105 TDF_Label aSelLab = selectionLabel();
106 aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
107 aSelLab.ForgetAttribute(kINVALID_SELECTION);
109 bool isDegeneratedEdge = false;
110 // do not use the degenerated edge as a shape, a null context and shape is used in the case
111 if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
112 const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
113 if (aSubShape.ShapeType() == TopAbs_EDGE)
114 isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
116 if (!theContext.get() || isDegeneratedEdge) {
117 // to keep the reference attribute label
118 TDF_Label aRefLab = myRef.myRef->Label();
119 aSelLab.ForgetAllAttributes(true);
120 myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
123 if (theContext->groupName() == ModelAPI_ResultBody::group()) {
124 // do not select the whole shape for body:it is already must be in the data framework
125 // equal and null selected objects mean the same: object is equal to context,
126 if (theContext->shape().get() &&
127 (theContext->shape()->isEqual(theSubShape) || !theSubShape.get())) {
128 aSelLab.ForgetAllAttributes(true);
129 TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
131 selectBody(theContext, theSubShape);
133 } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
134 aSelLab.ForgetAllAttributes(true); // to remove old selection data
135 std::shared_ptr<Model_ResultConstruction> aConstruction =
136 std::dynamic_pointer_cast<Model_ResultConstruction>(theContext);
137 std::shared_ptr<GeomAPI_Shape> aSubShape;
138 if (theSubShape.get() && !theContext->shape()->isEqual(theSubShape))
139 aSubShape = theSubShape; // the whole context
140 if (aConstruction->isInfinite()) {
141 // For correct naming selection, put the shape into the naming structure.
142 // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
143 TNaming_Builder aBuilder(aSelLab);
144 aBuilder.Generated(theContext->shape()->impl<TopoDS_Shape>());
146 int anIndex = aConstruction->select(theSubShape, owner()->document());
147 TDataStd_Integer::Set(aSelLab, anIndex);
148 } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
149 aSelLab.ForgetAllAttributes(true);
150 TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
151 selectPart(theContext, theSubShape);
154 owner()->data()->sendAttributeUpdated(this);
157 void Model_AttributeSelection::removeTemporaryValues()
159 if (myTmpContext.get() || myTmpSubShape.get()) {
160 myTmpContext.reset();
161 myTmpSubShape.reset();
165 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
167 GeomShapePtr aResult;
168 if (myTmpContext.get() || myTmpSubShape.get()) {
169 ResultConstructionPtr aResulConstruction =
170 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myTmpContext);
171 if(aResulConstruction.get()) {
172 // it is just reference to construction.
173 return myTmpSubShape;
175 return myTmpSubShape.get() ? myTmpSubShape : myTmpContext->shape();
178 TDF_Label aSelLab = selectionLabel();
179 if (aSelLab.IsAttribute(kINVALID_SELECTION))
182 if (myRef.isInitialized()) {
183 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
184 ResultPtr aContext = context();
186 return aResult; // empty result
187 return aContext->shape();
189 if (aSelLab.IsAttribute(kPART_REF_ID)) {
190 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
191 if (!aPart.get() || !aPart->isActivated())
192 return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
193 Handle(TDataStd_Integer) anIndex;
194 if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
195 if (anIndex->Get()) { // special selection attribute was created, use it
196 return aPart->selectionValue(anIndex->Get());
197 } else { // face with name is already in the data model, so try to take it by name
198 Handle(TDataStd_Name) aName;
199 if (aSelLab.FindAttribute(TDataStd_Name::GetID(), aName)) {
200 std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
201 std::size_t aPartEnd = aSubShapeName.find('/');
202 if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
203 std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
205 std::string aType; // to reuse already existing selection the type is not needed
206 return aPart->shapeInPart(aNameInPart, aType, anIndex);
213 std::shared_ptr<Model_ResultConstruction> aConstr =
214 std::dynamic_pointer_cast<Model_ResultConstruction>(context());
216 if (aConstr->isInfinite())
217 return aResult; // empty result
219 Handle(TNaming_NamedShape) aSelection;
220 if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
221 TopoDS_Shape aSelShape = aSelection->Get();
222 aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
223 aResult->setImpl(new TopoDS_Shape(aSelShape));
224 } else if (aConstr) { // for simple construction element: just shape of this construction element
225 Handle(TDataStd_Integer) anIndex;
226 if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
227 if (anIndex->Get() == 0) // it is just reference to construction, nothing is in value
229 return aConstr->shape(anIndex->Get(), owner()->document());
236 bool Model_AttributeSelection::isInvalid()
238 return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
241 bool Model_AttributeSelection::isInitialized()
243 if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
244 std::shared_ptr<GeomAPI_Shape> aResult;
245 if (myRef.isInitialized()) {
246 TDF_Label aSelLab = selectionLabel();
247 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
248 ResultPtr aContext = context();
249 return aContext.get() != NULL;
251 Handle(TNaming_NamedShape) aSelection;
252 if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
253 return !aSelection->Get().IsNull();
254 } else { // for simple construction element: just shape of this construction element
255 std::shared_ptr<Model_ResultConstruction> aConstr =
256 std::dynamic_pointer_cast<Model_ResultConstruction>(context());
258 Handle(TDataStd_Integer) anIndex;
259 if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
260 // for the whole shape it may return null, so, if index exists, returns true
270 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
273 myIsInitialized = myRef.isInitialized();
277 void Model_AttributeSelection::setID(const std::string theID)
280 ModelAPI_AttributeSelection::setID(theID);
283 ResultPtr Model_AttributeSelection::context() {
284 if (myTmpContext.get() || myTmpSubShape.get()) {
288 ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
289 // for parts there could be same-data result, so take the last enabled
290 if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
291 int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
292 for(int a = aSize - 1; a >= 0; a--) {
293 ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
294 if (aPart.get() && aPart->data() == aResult->data()) {
295 ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
296 FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
297 // check that this result is not this-feature result (it is forbidden t oselect itself)
298 if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
308 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
310 ModelAPI_AttributeSelection::setObject(theObject);
311 myRef.setObject(theObject);
314 TDF_LabelMap& Model_AttributeSelection::scope()
316 if (myScope.IsEmpty()) { // create a new scope if not yet done
317 // gets all features with named shapes that are before this feature label (before in history)
318 DocumentPtr aMyDoc = owner()->document();
319 std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
320 std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
321 bool aMePassed = false;
322 CompositeFeaturePtr aComposite =
323 std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
324 FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
325 CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
326 if (aFeature.get()) {
327 aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
328 if (aCompositeOwner.get()) {
329 aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
332 // for group Scope is not limitet: this is always up to date objects
333 bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
334 for(; aFIter != allFeatures.end(); aFIter++) {
335 if (*aFIter == owner()) { // the left features are created later (except subs of composite)
339 if (isGroup) aMePassed = false;
340 bool isInScope = !aMePassed;
341 if (!isInScope && aComposite.get()) {
342 // try to add sub-elements of composite if this is composite
343 if (aComposite->isSub(*aFIter))
346 // remove the composite-owner of this feature (sketch in extrusion-cut)
347 if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
350 if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
351 TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
352 (*aFIter)->data())->label().Father();
353 TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), true);
354 for(; aNSIter.More(); aNSIter.Next()) {
355 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
356 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
357 myScope.Add(aNS->Label());
362 // also add all naming labels created for external constructions
363 std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(aMyDoc);
364 TDF_Label anExtDocLab = aDoc->extConstructionsLabel();
365 TDF_ChildIDIterator aNSIter(anExtDocLab, TNaming_NamedShape::GetID(), true);
366 for(; aNSIter.More(); aNSIter.Next()) {
367 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
368 if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
369 myScope.Add(aNS->Label());
376 /// Sets the invalid flag if flag is false, or removes it if "true"
378 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
380 theLab.ForgetAttribute(kINVALID_SELECTION);
382 TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
387 void Model_AttributeSelection::split(
388 ResultPtr theContext, TopoDS_Shape theNewShape, TopAbs_ShapeEnum theType)
390 TopTools_ListOfShape aSubs;
391 for(TopoDS_Iterator anExplorer(theNewShape); anExplorer.More(); anExplorer.Next()) {
392 if (!anExplorer.Value().IsNull() &&
393 anExplorer.Value().ShapeType() == theType) {
394 aSubs.Append(anExplorer.Value());
395 } else { // invalid case; bad result shape, so, impossible to split easily
400 if (aSubs.Extent() > 1) { // ok to split
401 TopTools_ListIteratorOfListOfShape aSub(aSubs);
402 GeomShapePtr aSubSh(new GeomAPI_Shape);
403 aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
404 setValue(theContext, aSubSh);
405 for(aSub.Next(); aSub.More(); aSub.Next()) {
406 GeomShapePtr aSubSh(new GeomAPI_Shape);
407 aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
408 myParent->append(theContext, aSubSh);
413 bool Model_AttributeSelection::update()
415 TDF_Label aSelLab = selectionLabel();
416 ResultPtr aContext = context();
418 return setInvalidIfFalse(aSelLab, false);
419 if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
420 return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
423 if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
424 std::shared_ptr<GeomAPI_Shape> aNoSelection;
425 bool aResult = selectPart(aContext, aNoSelection, true);
426 aResult = setInvalidIfFalse(aSelLab, aResult);
428 owner()->data()->sendAttributeUpdated(this);
433 if (aContext->groupName() == ModelAPI_ResultBody::group()) {
434 // body: just a named shape, use selection mechanism from OCCT
435 TNaming_Selector aSelector(aSelLab);
436 TopoDS_Shape anOldShape;
437 if (!aSelector.NamedShape().IsNull()) {
438 anOldShape = aSelector.NamedShape()->Get();
440 bool aResult = aSelector.Solve(scope()) == Standard_True;
441 // must be before sending of updated attribute (1556)
442 aResult = setInvalidIfFalse(aSelLab, aResult);
443 TopoDS_Shape aNewShape;
444 if (!aSelector.NamedShape().IsNull()) {
445 aNewShape = aSelector.NamedShape()->Get();
447 if (anOldShape.IsNull() || aNewShape.IsNull() ||
448 !anOldShape.IsEqual(aSelector.NamedShape()->Get())) {
449 // shape type shoud not not changed: if shape becomes compound of such shapes, then split
450 if (myParent && !anOldShape.IsNull() && !aNewShape.IsNull() &&
451 anOldShape.ShapeType() != aNewShape.ShapeType() &&
452 (aNewShape.ShapeType() == TopAbs_COMPOUND || aNewShape.ShapeType() == TopAbs_COMPSOLID))
454 split(aContext, aNewShape, anOldShape.ShapeType());
456 owner()->data()->sendAttributeUpdated(this); // send updated if shape is changed
461 if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
462 Handle(TDataStd_Integer) anIndex;
463 if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
464 std::shared_ptr<Model_ResultConstruction> aConstructionContext =
465 std::dynamic_pointer_cast<Model_ResultConstruction>(aContext);
466 bool aModified = true;
467 bool aValid = aConstructionContext->update(anIndex->Get(), owner()->document(), aModified);
468 setInvalidIfFalse(aSelLab, aValid);
470 owner()->data()->sendAttributeUpdated(this);
474 return setInvalidIfFalse(aSelLab, false); // unknown case
477 void Model_AttributeSelection::selectBody(
478 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
480 // perform the selection
481 TNaming_Selector aSel(selectionLabel());
482 TopoDS_Shape aContext;
484 ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theContext);//myRef.value()
486 aContext = aBody->shape()->impl<TopoDS_Shape>();
489 std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
491 aContext = aResult->shape()->impl<TopoDS_Shape>();
493 Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
498 // with "recover" feature the selected context may be not up to date (issue 1710)
499 Handle(TNaming_NamedShape) aResult;
500 TDF_Label aSelLab = selectionLabel();
501 TopoDS_Shape aNewContext = aContext;
502 bool isUpdated = true;
503 while(!aNewContext.IsNull() && isUpdated) {
504 // searching for the very last shape that was produced from this one
506 if (!TNaming_Tool::HasLabel(aSelLab, aNewContext))
507 // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
509 for(TNaming_SameShapeIterator anIter(aNewContext, aSelLab); anIter.More(); anIter.Next()) {
510 TDF_Label aNSLab = anIter.Label();
511 if (!scope().Contains(aNSLab))
513 Handle(TNaming_NamedShape) aNS;
514 if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
515 for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
516 if (aShapesIter.Evolution() == TNaming_SELECTED)
517 continue; // don't use the selection evolution
518 if (!aShapesIter.OldShape().IsNull() && aShapesIter.OldShape().IsSame(aNewContext)) {
519 // found the original shape
520 aNewContext = aShapesIter.NewShape(); // go to the newer shape
528 if (aNewContext.IsNull()) { // a context is already deleted
529 setInvalidIfFalse(aSelLab, false);
530 Events_InfoMessage("Model_AttributeSelection", "Failed to select shape already deleted").send();
534 TopoDS_Shape aNewSub = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
535 if (!aNewSub.IsEqual(aContext)) { // searching for subshape in the new context
536 bool isFound = false;
537 TopExp_Explorer anExp(aNewContext, aNewSub.ShapeType());
538 for(; anExp.More(); anExp.Next()) {
539 if (anExp.Current().IsEqual(aNewSub)) {
544 if (!isFound) { // sub-shape is not found in the up-to-date instance of the context shape
545 // if context is sub-result of compound/compsolid, selection of sub-shape better propagate to
546 // the main result (which is may be modified), case is in 1799
547 ResultCompSolidPtr aMain = ModelAPI_Tools::compSolidOwner(theContext);
549 selectBody(aMain, theSubShape);
552 setInvalidIfFalse(aSelLab, false);
553 Events_InfoMessage("Model_AttributeSelection",
554 "Failed to select sub-shape already modified").send();
559 /// fix for issue 411: result modified shapes must not participate in this selection mechanism
560 if (!aContext.IsNull()) {
561 FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
562 bool aEraseResults = false;
563 if (aFeatureOwner.get()) {
564 aEraseResults = !aFeatureOwner->results().empty();
565 if (aEraseResults) // erase results without flash deleted and redisplay: do it after Select
566 aFeatureOwner->removeResults(0, false, false);
568 aSel.Select(aNewSub, aNewContext);
570 if (aEraseResults) { // flash after Select : in Groups it makes selection with shift working
571 static Events_Loop* aLoop = Events_Loop::loop();
572 static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
573 aLoop->flush(kDeletedEvent);
578 bool Model_AttributeSelection::selectPart(
579 const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
580 const bool theUpdate)
582 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
583 if (!aPart.get() || !aPart->isActivated())
584 return true; // postponed naming
586 Handle(TDataStd_Integer) anIndex;
587 if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
588 // by internal selection
589 if (anIndex->Get() > 0) {
590 // update the selection by index
591 return aPart->updateInPart(anIndex->Get());
593 return true; // nothing to do, referencing just by name
596 return true; // nothing to do, referencing just by name
598 // store the shape (in case part is not loaded it should be useful
600 std::string aName = theContext->data()->name();
601 if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
602 aShape = theContext->shape()->impl<TopoDS_Shape>();
604 aShape = theSubShape->impl<TopoDS_Shape>();
606 aName += "/" + aPart->nameInPart(theSubShape, anIndex);
607 TDataStd_Integer::Set(selectionLabel(), anIndex);
609 TNaming_Builder aBuilder(selectionLabel());
610 aBuilder.Select(aShape, aShape);
611 // identify by name in the part
612 TDataStd_Name::Set(selectionLabel(), aName.c_str());
613 return !aName.empty();
616 TDF_Label Model_AttributeSelection::selectionLabel()
618 return myRef.myRef->Label().FindChild(1);
621 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
623 std::string aName("");
624 if(!this->isInitialized())
625 return !theDefaultName.empty() ? theDefaultName : aName;
627 std::shared_ptr<GeomAPI_Shape> aSubSh = value();
628 ResultPtr aCont = context();
630 if (!aCont.get()) // in case of selection of removed result
633 Model_SelectionNaming aSelNaming(selectionLabel());
634 return aSelNaming.namingName(
635 aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
638 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
639 void Model_AttributeSelection::selectSubShape(
640 const std::string& theType, const std::string& theSubShapeName)
642 if(theSubShapeName.empty() || theType.empty()) return;
644 // check this is Part-name: 2 delimiters in the name
645 std::size_t aPartEnd = theSubShapeName.find('/');
646 if (aPartEnd != std::string::npos && aPartEnd != theSubShapeName.rfind('/')) {
647 std::string aPartName = theSubShapeName.substr(0, aPartEnd);
648 ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
649 if (aFound.get()) { // found such part, so asking it for the name
650 ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
651 std::string aNameInPart = theSubShapeName.substr(aPartEnd + 1);
653 std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, theType, anIndex);
654 if (aSelected.get()) {
655 setValue(aPart, aSelected);
656 TDataStd_Integer::Set(selectionLabel(), anIndex);
662 Model_SelectionNaming aSelNaming(selectionLabel());
663 std::shared_ptr<Model_Document> aDoc =
664 std::dynamic_pointer_cast<Model_Document>(owner()->document());
665 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
667 if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
668 // try to find the last context to find the up to date shape
669 if (aCont->shape().get() && !aCont->shape()->isNull() &&
670 aCont->groupName() == ModelAPI_ResultBody::group() && aDoc == owner()->document()) {
671 const TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
672 if (!aConShape.IsNull()) {
673 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
675 aNS = TNaming_Tool::CurrentNamedShape(aNS);
676 if (!aNS.IsNull() && scope().Contains(aNS->Label())) { // scope check is for 2228
677 TDF_Label aLab = aNS->Label();
678 while(aLab.Depth() != 7 && aLab.Depth() > 5)
679 aLab = aLab.Father();
680 ObjectPtr anObj = aDoc->objects()->object(aLab);
682 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
690 setValue(aCont, aShapeToBeSelected);
694 TDF_Label aSelLab = selectionLabel();
695 setInvalidIfFalse(aSelLab, false);
699 int Model_AttributeSelection::Id()
702 std::shared_ptr<GeomAPI_Shape> aSelection = value();
703 std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
704 // support for compsolids:
705 if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
706 aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
709 TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
710 const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
711 // searching for the latest main shape
712 if (aSelection && !aSelection->isNull() &&
713 aContext && !aContext->isNull())
715 std::shared_ptr<Model_Document> aDoc =
716 std::dynamic_pointer_cast<Model_Document>(context()->document());
718 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
720 aMainShape = TNaming_Tool::CurrentShape(aNS);
724 TopTools_IndexedMapOfShape aSubShapesMap;
725 TopExp::MapShapes(aMainShape, aSubShapesMap);
726 anID = aSubShapesMap.FindIndex(aSubShape);
731 void Model_AttributeSelection::setId(int theID)
733 const ResultPtr& aContext = context();
734 std::shared_ptr<GeomAPI_Shape> aSelection;
736 std::shared_ptr<GeomAPI_Shape> aContextShape = aContext->shape();
737 // support for compsolids:
738 if (aContext.get() && ModelAPI_Tools::compSolidOwner(aContext).get())
739 aContextShape = ModelAPI_Tools::compSolidOwner(aContext)->shape();
741 TopoDS_Shape aMainShape = aContextShape->impl<TopoDS_Shape>();
742 // searching for the latest main shape
744 aContextShape && !aContextShape->isNull())
746 std::shared_ptr<Model_Document> aDoc =
747 std::dynamic_pointer_cast<Model_Document>(aContext->document());
749 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
751 aMainShape = TNaming_Tool::CurrentShape(aNS);
755 TopTools_IndexedMapOfShape aSubShapesMap;
756 TopExp::MapShapes(aMainShape, aSubShapesMap);
757 const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
759 std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
760 aResult->setImpl(new TopoDS_Shape(aSelShape));
762 aSelection = aResult;
765 setValue(aContext, aSelection);
768 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
771 if (owner()->document() != theContext->document()) {
772 if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
773 aResult = theContext->document()->kind() + "/";
775 ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
776 ModelAPI_Session::get()->moduleDocument(), theContext->document());
778 aResult = aDocRes->data()->name() + "/";
782 aResult += theContext->data()->name();
786 void Model_AttributeSelection::computeValues(
787 ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
788 TopTools_ListOfShape& theShapes)
790 bool aWasWholeContext = theValShape.IsNull();
791 if (aWasWholeContext) {
792 //theShapes.Append(theValShape);
794 theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
796 //TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
797 TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
798 //if (anOldContShape.IsSame(theValShape)) { // full context shape substituted by new full context
799 //theShapes.Append(aNewContShape);
802 // if a new value is unchanged in the new context, do nothing: value is correct
803 TopExp_Explorer aSubExp(aNewContShape, theValShape.ShapeType());
804 for(; aSubExp.More(); aSubExp.Next()) {
805 if (aSubExp.Current().IsSame(theValShape)) {
806 theShapes.Append(theValShape);
810 // if new context becomes compsolid, the resulting sub may be in sub-solids
811 std::list<ResultPtr> aNewToIterate;
812 aNewToIterate.push_back(theNewContext);
813 ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theNewContext);
815 for(int a = 0; a < aComp->numberOfSubs(); a++)
816 aNewToIterate.push_back(aComp->subResult(a, false));
819 // first iteration: searching for the whole shape appearance (like face of the box)
820 // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
822 TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
823 TopTools_MapOfShape anOlds; // to know how many olds produced new containers
824 for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
825 std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
826 for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
827 std::shared_ptr<Model_Data> aNewData =
828 std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
829 TDF_Label aNewLab = aNewData->label();
830 // searching for produced sub-shape fully on some label
831 TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID(), Standard_True);
832 for(; aNSIter.More(); aNSIter.Next()) {
833 Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
834 for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
835 if (aToFindPart == 0) { // search shape is fully inside
836 if (aPairIter.OldShape().IsSame(theValShape)) {
837 if (aPairIter.NewShape().IsNull()) {// value was removed
841 theShapes.Append(aPairIter.NewShape());
843 } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
844 TopExp_Explorer anExp(aPairIter.OldShape(), theValShape.ShapeType());
845 for(; anExp.More(); anExp.Next()) {
846 if (anExp.Current().IsSame(theValShape)) { // found a new container
847 if (aPairIter.NewShape().IsNull()) {// value was removed
851 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
852 anOlds.Add(aPairIter.OldShape());
861 if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
862 // map of sub-shapes -> number of occurences of these shapes in containers
863 NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
864 TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
865 for(; aContIter.More(); aContIter.Next()) {
866 TopExp_Explorer aSubExp(aContIter.Key(), theValShape.ShapeType());
867 for(; aSubExp.More(); aSubExp.Next()) {
868 if (!aSubs.IsBound(aSubExp.Current())) {
869 aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
871 // store old to know how many olds produced this shape
872 aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
875 // if sub is appeared same times in containers as the number of old shapes that contain it
876 int aCountInOld = anOlds.Size();
877 NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
879 for(; aSubsIter.More(); aSubsIter.Next()) {
880 if (aSubsIter.Value().Size() == aCountInOld) {
881 theShapes.Append(aSubsIter.Key());
885 if (theShapes.IsEmpty()) { // nothing was changed
886 theShapes.Append(aWasWholeContext ? TopoDS_Shape() : theValShape);
890 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
891 const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
892 TDF_Label theAccessLabel,
893 std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
895 std::set<ResultPtr> aResults; // to avoid duplicates, new context, null if deleted
896 TopTools_ListOfShape aResContShapes;
897 TNaming_SameShapeIterator aModifIter(theContShape, theAccessLabel);
898 for(; aModifIter.More(); aModifIter.Next()) {
899 TDF_Label anObjLab = aModifIter.Label().Father();
900 ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
901 (theDoc->objects()->object(anObjLab));
902 if (!aModifierObj.get()) {
903 // #2241: shape may be sub-element of new object, not main (shell created from faces)
904 if (!anObjLab.IsRoot())
905 aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
906 (theDoc->objects()->object(anObjLab.Father()));
907 if (!aModifierObj.get())
910 FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
911 if (!aModifierFeat.get())
913 FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
914 if (aModifierFeat == aThisFeature || theDoc->objects()->isLater(aModifierFeat, aThisFeature))
915 continue; // the modifier feature is later than this, so, should not be used
916 FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
917 if (aCurrentModifierFeat == aModifierFeat ||
918 theDoc->objects()->isLater(aCurrentModifierFeat, aModifierFeat))
919 continue; // the current modifier is later than the found, so, useless
920 Handle(TNaming_NamedShape) aNewNS;
921 aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
922 if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
923 aResults.insert(aModifierObj);
924 //TNaming_Iterator aPairIter(aNewNS);
925 //aResContShapes.Append(aPairIter.NewShape());
926 aResContShapes.Append(aModifierObj->shape()->impl<TopoDS_Shape>());
927 } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
928 aResults.insert(ResultPtr());
929 } else { // not-precessed modification => don't support it
933 if (aResults.empty())
934 return false; // no modifications found, must stay the same
935 // iterate all results to find futher modifications
936 std::set<ResultPtr>::iterator aResIter = aResults.begin();
937 for(; aResIter != aResults.end(); aResIter++) {
938 if (aResIter->get() != NULL) {
939 // compute new values by two contextes: the old and the new
940 TopTools_ListOfShape aValShapes;
941 computeValues(theContext, *aResIter, theValShape, aValShapes);
943 TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
944 for(; aNewVal.More(); aNewVal.Next()) {
945 std::list<ResultPtr> aNewRes;
946 TopTools_ListOfShape aNewUpdatedVal;
947 TopoDS_Shape aNewValSh = aNewVal.Value();
948 TopoDS_Shape aNewContShape = (*aResIter)->shape()->impl<TopoDS_Shape>();
949 if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
951 if (searchNewContext(theDoc, aNewContShape, *aResIter, aNewValSh,
952 theAccessLabel, aNewRes, aNewUpdatedVal))
954 // appeand new results instead of the current ones
955 std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
956 TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
957 for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
958 theResults.push_back(*aNewIter);
959 theValShapes.Append(aNewUpdVal.Value());
961 } else { // the current result is good
962 theResults.push_back(*aResIter);
963 theValShapes.Append(aNewValSh);
968 return true; // theResults must be empty: everything is deleted
971 void Model_AttributeSelection::updateInHistory()
973 ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
974 // only bodies and parts may be modified later in the history, don't do anything otherwise
975 if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
976 aContext->groupName() != ModelAPI_ResultPart::group()))
978 std::shared_ptr<Model_Document> aDoc =
979 std::dynamic_pointer_cast<Model_Document>(aContext->document());
980 std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
981 if (!aContData.get() || !aContData->isValid())
983 TDF_Label aContLab = aContData->label(); // named shape where the selected context is located
984 Handle(TNaming_NamedShape) aContNS;
985 if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
986 bool aFoundNewContext = true;
987 ResultPtr aNewContext = aContext;
988 while(aFoundNewContext) {
989 aFoundNewContext = false;
990 // parts have no shape in result, so, trace references using the Part info
991 if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
992 ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
993 if (aPartContext.get()) { // searching for the up to date references to the referenced cont
994 const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
995 std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
996 for(; aRef != aRefs.end(); aRef++) {
997 // to avoid detection of part changes by local selection only
998 AttributeSelectionPtr aSel =
999 std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1000 if (aSel.get() && !aSel->value()->isSame(aSel->context()->shape()))
1003 FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1004 if (aRefFeat.get() && aRefFeat != owner()) {
1005 FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1006 if (aDoc->objects()->isLater(aThisFeature, aRefFeat)) { // found better feature
1007 aFoundNewContext = true;
1008 aNewContext = aRefFeat->firstResult();
1015 if (aNewContext != aContext) {
1016 setValue(aNewContext, value());
1020 FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1021 FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1022 // iterate the context shape modifications in order to find a feature that is upper in history
1023 // that this one and is really modifies the referenced result to refer to it
1024 ResultPtr aModifierResFound;
1025 TNaming_Iterator aPairIter(aContNS);
1026 if (!aPairIter.More())
1028 TopoDS_Shape aNewCShape = aPairIter.NewShape();
1029 bool anIterate = true;
1030 // trying to update also the sub-shape selected
1031 GeomShapePtr aSubShape = value();
1032 if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1034 TopoDS_Shape aValShape;
1035 if (aSubShape.get()) {
1036 aValShape = aSubShape->impl<TopoDS_Shape>();
1039 std::list<ResultPtr> aNewContexts;
1040 TopTools_ListOfShape aValShapes;
1041 if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1043 // update scope to reset to a new one
1046 std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1047 TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1048 if (aNewCont == aNewContexts.end()) { // all results were deleted
1049 ResultPtr anEmptyContext;
1050 std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1051 setValue(anEmptyContext, anEmptyShape); // nullify the selection
1055 GeomShapePtr aValueShape;
1056 if (!aNewValues.Value().IsNull()) {
1057 aValueShape = std::make_shared<GeomAPI_Shape>();
1058 aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1060 setValue(*aNewCont, aValueShape);
1061 // if there are more than one result, put them by "append" into "parent" list
1063 for(aNewCont++, aNewValues.Next(); aNewCont != aNewContexts.end();
1064 aNewCont++, aNewValues.Next()) {
1065 GeomShapePtr aValueShape;
1066 if (!aNewValues.Value().IsNull()) {
1067 aValueShape = std::make_shared<GeomAPI_Shape>();
1068 aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1070 myParent->append(*aNewCont, aValueShape);
1076 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1078 myParent = theParent;