Salome HOME
Issue #2622: Weak naming
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
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.
7 //
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.
12 //
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
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
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_ResultBody.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 <ModelAPI_Validator.h>
39 #include <ModelGeomAlgo_Shape.h>
40 #include <Events_InfoMessage.h>
41 #include <GeomAPI_Edge.h>
42 #include <GeomAPI_Pnt.h>
43 #include <GeomAPI_Vertex.h>
44 #include <GeomAlgoAPI_CompoundBuilder.h>
45 #include <GeomAlgoAPI_NExplode.h>
46
47 #include <TNaming_Selector.hxx>
48 #include <TNaming_NamedShape.hxx>
49 #include <TNaming_Tool.hxx>
50 #include <TNaming_Builder.hxx>
51 #include <TNaming_SameShapeIterator.hxx>
52 #include <TNaming_Iterator.hxx>
53 #include <TDataStd_Integer.hxx>
54 #include <TDataStd_UAttribute.hxx>
55 #include <TDataStd_Name.hxx>
56 #include <TopTools_ListOfShape.hxx>
57 #include <TopTools_DataMapOfShapeShape.hxx>
58 #include <TopTools_MapOfShape.hxx>
59 #include <TopExp_Explorer.hxx>
60 #include <BRep_Tool.hxx>
61 #include <TopoDS.hxx>
62 #include <TopExp.hxx>
63 #include <TDF_ChildIterator.hxx>
64 #include <TDF_ChildIDIterator.hxx>
65 #include <TopoDS_Iterator.hxx>
66 #include <TDF_ChildIDIterator.hxx>
67 #include <Geom_Circle.hxx>
68 #include <Geom_Ellipse.hxx>
69 #include <BRep_Builder.hxx>
70
71 //#define DEB_NAMING 1
72 #ifdef DEB_NAMING
73 #include <BRepTools.hxx>
74 #endif
75 /// added to the index in the packed map to signalize that the vertex of edge is selected
76 /// (multiplied by the index of the edge)
77 static const int kSTART_VERTEX_DELTA = 1000000;
78 // identifier that there is simple reference: selection equals to context
79 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
80 // reference to Part sub-object
81 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
82 // selection is invalid after recomputation
83 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
84
85 // identifier of the selection of the center of circle on edge
86 Standard_GUID kCIRCLE_CENTER("d0d0e0f1-217a-4b95-8fbb-0c4132f23718");
87 // identifier of the selection of the first focus point of ellipse on edge
88 Standard_GUID kELLIPSE_CENTER1("f70df04c-3168-4dc9-87a4-f1f840c1275d");
89 // identifier of the selection of the second focus point of ellipse on edge
90 Standard_GUID kELLIPSE_CENTER2("1395ae73-8e02-4cf8-b204-06ff35873a32");
91
92 // prefix for the whole feature context identification
93 const static std::string kWHOLE_FEATURE = "all-in-";
94
95 // on this label is stored:
96 // TNaming_NamedShape - selected shape
97 // TNaming_Naming - topological selection information (for the body)
98 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
99 // TDataStd_Integer - type of the selected shape (for construction)
100 // TDF_Reference - from ReferenceAttribute, the context
101 bool Model_AttributeSelection::setValue(const ObjectPtr& theContext,
102   const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
103 {
104   if (theTemporarily &&
105       (!theContext.get() || theContext->groupName() != ModelAPI_Feature::group())) {
106     // just keep the stored without DF update
107     myTmpContext = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
108     myTmpSubShape = theSubShape;
109     owner()->data()->sendAttributeUpdated(this);
110     return true;
111   } else {
112     myTmpContext.reset();
113     myTmpSubShape.reset();
114     myTmpCenterType = NOT_CENTER;
115   }
116
117   CenterType aType;
118   const std::shared_ptr<GeomAPI_Shape>& anOldShape = internalValue(aType);
119   bool isOldContext = theContext == myRef.value();
120   bool isOldShape = isOldContext &&
121     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
122   if (isOldShape) return false; // shape is the same, so context is also unchanged
123   bool aToUnblock = false;
124   // update the referenced object if needed
125   if (!isOldContext) {
126     aToUnblock = !owner()->data()->blockSendAttributeUpdated(true);
127     myRef.setValue(theContext);
128   }
129
130   // do noth use naming if selected shape is result shape itself, but not sub-shape
131   TDF_Label aSelLab = selectionLabel();
132   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
133   aSelLab.ForgetAttribute(kINVALID_SELECTION);
134   aSelLab.ForgetAttribute(kCIRCLE_CENTER);
135   aSelLab.ForgetAttribute(kELLIPSE_CENTER1);
136   aSelLab.ForgetAttribute(kELLIPSE_CENTER2);
137
138   bool isDegeneratedEdge = false;
139   // do not use the degenerated edge as a shape, a null context and shape is used in the case
140   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
141     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
142     if (aSubShape.ShapeType() == TopAbs_EDGE)
143       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
144   }
145   if (!theContext.get() || isDegeneratedEdge) {
146     // to keep the reference attribute label
147     TDF_Label aRefLab = myRef.myRef->Label();
148     aSelLab.ForgetAllAttributes(true);
149     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
150     if (aToUnblock)
151       owner()->data()->blockSendAttributeUpdated(false);
152     return false;
153   }
154   if (theContext->groupName() == ModelAPI_ResultBody::group()) {
155     ResultBodyPtr aContextBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theContext);
156     // do not select the whole shape for body:it is already must be in the data framework
157     // equal and null selected objects mean the same: object is equal to context,
158     if (aContextBody->shape().get() &&
159         (aContextBody->shape()->isEqual(theSubShape) || !theSubShape.get())) {
160       aSelLab.ForgetAllAttributes(true);
161       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
162     } else {
163       selectBody(aContextBody, theSubShape);
164     }
165   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
166     ResultConstructionPtr aContextConstruction =
167       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
168     aSelLab.ForgetAllAttributes(true); // to remove old selection data
169     std::shared_ptr<Model_ResultConstruction> aConstruction =
170       std::dynamic_pointer_cast<Model_ResultConstruction>(theContext);
171     std::shared_ptr<GeomAPI_Shape> aSubShape;
172     if (theSubShape.get() && !aContextConstruction->shape()->isEqual(theSubShape))
173       aSubShape = theSubShape; // the whole context
174     if (aConstruction->isInfinite()) {
175       // For correct naming selection, put the shape into the naming structure.
176       // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
177       TNaming_Builder aBuilder(aSelLab);
178       aBuilder.Generated(aContextConstruction->shape()->impl<TopoDS_Shape>());
179     }
180     int anIndex = aConstruction->select(theSubShape, owner()->document());
181     TDataStd_Integer::Set(aSelLab, anIndex);
182   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
183     aSelLab.ForgetAllAttributes(true);
184     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
185     selectPart(std::dynamic_pointer_cast<ModelAPI_Result>(theContext), theSubShape);
186   } else { // check the feature context: parent-Part of this feature should not be used
187     FeaturePtr aFeatureContext = std::dynamic_pointer_cast<ModelAPI_Feature>(theContext);
188     if (aFeatureContext.get()) {
189       if (owner()->document() != aFeatureContext->document()) {
190         aSelLab.ForgetAllAttributes(true);
191         myRef.setValue(ObjectPtr());
192         if (aToUnblock)
193           owner()->data()->blockSendAttributeUpdated(false);
194         return false;
195       }
196     }
197   }
198
199   owner()->data()->sendAttributeUpdated(this);
200
201   if (aToUnblock)
202     owner()->data()->blockSendAttributeUpdated(false);
203
204   return true;
205 }
206
207 void Model_AttributeSelection::setValueCenter(
208     const ObjectPtr& theContext, const std::shared_ptr<GeomAPI_Edge>& theEdge,
209     const CenterType theCenterType, const bool theTemporarily)
210 {
211   bool anUpdated = setValue(theContext, theEdge, theTemporarily);
212   if (theTemporarily) {
213     myTmpCenterType = theCenterType;
214   } else { // store in the data structure
215     TDF_Label aSelLab = selectionLabel();
216     switch(theCenterType) {
217     case CIRCLE_CENTER:
218       if (!anUpdated)
219         anUpdated = !aSelLab.IsAttribute(kCIRCLE_CENTER);
220       TDataStd_UAttribute::Set(aSelLab, kCIRCLE_CENTER);
221       break;
222     case ELLIPSE_FIRST_FOCUS:
223       if (!anUpdated)
224         anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER1);
225       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER1);
226       break;
227     case ELLIPSE_SECOND_FOCUS:
228       if (!anUpdated)
229         anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER2);
230       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER2);
231       break;
232     }
233     if (anUpdated)
234       owner()->data()->sendAttributeUpdated(this);
235   }
236 }
237
238 void Model_AttributeSelection::selectValue(
239     const std::shared_ptr<ModelAPI_AttributeSelection>& theSource)
240 {
241   CenterType aType;
242   std::shared_ptr<GeomAPI_Shape> aValue =
243     std::dynamic_pointer_cast<Model_AttributeSelection>(theSource)->internalValue(aType);
244   if (!aValue.get() || aType == NOT_CENTER) {
245     setValue(theSource->context(), aValue);
246   } else {
247     std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge);
248     anEdge->setImpl(new TopoDS_Shape(aValue->impl<TopoDS_Shape>()));
249     setValueCenter(theSource->context(), anEdge, aType);
250   }
251 }
252
253 void Model_AttributeSelection::removeTemporaryValues()
254 {
255   if (myTmpContext.get() || myTmpSubShape.get()) {
256     myTmpContext.reset();
257     myTmpSubShape.reset();
258   }
259 }
260
261 // returns the center of the edge: circular or elliptical
262 GeomShapePtr centerByEdge(GeomShapePtr theEdge, ModelAPI_AttributeSelection::CenterType theType)
263 {
264   if (theType != ModelAPI_AttributeSelection::NOT_CENTER && theEdge.get() != NULL) {
265     TopoDS_Shape aShape = theEdge->impl<TopoDS_Shape>();
266     if (!aShape.IsNull() && aShape.ShapeType() == TopAbs_EDGE) {
267       TopoDS_Edge anEdge = TopoDS::Edge(aShape);
268       double aFirst, aLast;
269       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
270       if (!aCurve.IsNull()) {
271         TopoDS_Vertex aVertex;
272         BRep_Builder aBuilder;
273         if (theType == ModelAPI_AttributeSelection::CIRCLE_CENTER) {
274           Handle(Geom_Circle) aCirc = Handle(Geom_Circle)::DownCast(aCurve);
275           if (!aCirc.IsNull()) {
276             aBuilder.MakeVertex(aVertex, aCirc->Location(), Precision::Confusion());
277           }
278         } else { // ellipse
279           Handle(Geom_Ellipse) anEll = Handle(Geom_Ellipse)::DownCast(aCurve);
280           if (!anEll.IsNull()) {
281             aBuilder.MakeVertex(aVertex,
282               theType == ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS ?
283               anEll->Focus1() : anEll->Focus2(), Precision::Confusion());
284           }
285         }
286         if (!aVertex.IsNull()) {
287           std::shared_ptr<GeomAPI_Vertex> aResult(new GeomAPI_Vertex);
288           aResult->setImpl(new TopoDS_Vertex(aVertex));
289           return aResult;
290         }
291       }
292     }
293   }
294   return theEdge; // no vertex, so, return the initial edge
295 }
296
297 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
298 {
299   if (!ModelAPI_AttributeSelection::isInitialized() && !myTmpContext.get() && !myTmpSubShape.get())
300     return std::shared_ptr<GeomAPI_Shape>();
301   CenterType aType = NOT_CENTER;
302   std::shared_ptr<GeomAPI_Shape> aResult = internalValue(aType);
303   return centerByEdge(aResult, aType);
304 }
305
306 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::internalValue(CenterType& theType)
307 {
308   theType = NOT_CENTER;
309   GeomShapePtr aResult;
310   if (myTmpContext.get() || myTmpSubShape.get()) {
311     theType = myTmpCenterType;
312     ResultConstructionPtr aResulConstruction =
313       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myTmpContext);
314     if(aResulConstruction.get()) {
315       // it is just reference to construction.
316       return myTmpSubShape;
317     }
318     return myTmpSubShape.get() ? myTmpSubShape : myTmpContext->shape();
319   }
320
321   TDF_Label aSelLab = selectionLabel();
322   if (aSelLab.IsAttribute(kINVALID_SELECTION))
323     return aResult;
324
325   if (aSelLab.IsAttribute(kCIRCLE_CENTER))
326     theType = CIRCLE_CENTER;
327   else if (aSelLab.IsAttribute(kELLIPSE_CENTER1))
328     theType = ELLIPSE_FIRST_FOCUS;
329   else if (aSelLab.IsAttribute(kELLIPSE_CENTER2))
330     theType = ELLIPSE_SECOND_FOCUS;
331
332
333   if (myRef.isInitialized()) {
334     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
335       ResultPtr aContext = context();
336       if (!aContext.get())
337         return aResult; // empty result
338       return aContext->shape();
339     }
340     if (aSelLab.IsAttribute(kPART_REF_ID)) {
341       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
342       if (!aPart.get() || !aPart->isActivated())
343         return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
344       Handle(TDataStd_Integer) anIndex;
345       if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
346         if (anIndex->Get()) { // special selection attribute was created, use it
347           return aPart->selectionValue(anIndex->Get());
348         } else { // face with name is already in the data model, so try to take it by name
349           Handle(TDataStd_Name) aName;
350           if (aSelLab.FindAttribute(TDataStd_Name::GetID(), aName)) {
351             std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
352             std::size_t aPartEnd = aSubShapeName.find('/');
353             if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
354               std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
355               int anIndex;
356               std::string aType; // to reuse already existing selection the type is not needed
357               return aPart->shapeInPart(aNameInPart, aType, anIndex);
358             }
359           }
360         }
361       }
362     }
363
364     std::shared_ptr<Model_ResultConstruction> aConstr =
365       std::dynamic_pointer_cast<Model_ResultConstruction>(context());
366     if (aConstr) {
367       if (aConstr->isInfinite())
368         return aResult; // empty result
369     }
370     if (!aConstr.get()) { // for construction context, return empty result as usual even
371       // the whole feature is selected
372       FeaturePtr aFeature = contextFeature();
373       if (aFeature.get()) {
374         std::list<GeomShapePtr> allShapes;
375         std::list<ResultPtr>::const_iterator aRes = aFeature->results().cbegin();
376         for (; aRes != aFeature->results().cend(); aRes++) {
377           if (aRes->get() && !(*aRes)->isDisabled()) {
378             GeomShapePtr aShape = (*aRes)->shape();
379             if (aShape.get() && !aShape->isNull()) {
380               allShapes.push_back(aShape);
381             }
382           }
383         }
384         return GeomAlgoAPI_CompoundBuilder::compound(allShapes);
385       }
386     }
387
388     Handle(TNaming_NamedShape) aSelection;
389     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
390       TopoDS_Shape aSelShape = aSelection->Get();
391       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
392       aResult->setImpl(new TopoDS_Shape(aSelShape));
393     } else if (aConstr) { // simple construction element: just shape of this construction element
394       Handle(TDataStd_Integer) anIndex;
395       if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
396         if (anIndex->Get() == 0) // it is just reference to construction, nothing is in value
397           return aResult;
398         return aConstr->shape(anIndex->Get(), owner()->document());
399       }
400     }
401   }
402   return aResult;
403 }
404
405 bool Model_AttributeSelection::isInvalid()
406 {
407   return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
408 }
409
410 bool Model_AttributeSelection::isInitialized()
411 {
412   if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
413     std::shared_ptr<GeomAPI_Shape> aResult;
414     if (myRef.isInitialized()) {
415       TDF_Label aSelLab = selectionLabel();
416       if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
417         ResultPtr aContext = context();
418         return aContext.get() != NULL;
419       }
420       Handle(TNaming_NamedShape) aSelection;
421       if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
422         return !aSelection->Get().IsNull();
423       } else { // for simple construction element: just shape of this construction element
424         std::shared_ptr<Model_ResultConstruction> aConstr =
425           std::dynamic_pointer_cast<Model_ResultConstruction>(context());
426         if (aConstr.get()) {
427           Handle(TDataStd_Integer) anIndex;
428           if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
429             // for the whole shape it may return null, so, if index exists, returns true
430             return true;
431           }
432         }
433         // for the whole feature, a feature object
434         FeaturePtr aFeat = contextFeature();
435         if (aFeat.get())
436           return true;
437       }
438     }
439   }
440   return false;
441 }
442
443 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
444   : myRef(theLabel)
445 {
446   myIsInitialized = myRef.isInitialized();
447   myParent = NULL;
448 }
449
450 void Model_AttributeSelection::setID(const std::string theID)
451 {
452   myRef.setID(theID);
453   ModelAPI_AttributeSelection::setID(theID);
454 }
455
456 ResultPtr Model_AttributeSelection::context()
457 {
458   if (!ModelAPI_AttributeSelection::isInitialized() && !myTmpContext.get() && !myTmpSubShape.get())
459     return ResultPtr();
460
461   if (myTmpContext.get() || myTmpSubShape.get()) {
462     return myTmpContext;
463   }
464
465   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
466   // for parts there could be same-data result, so take the last enabled
467   if (aResult.get()) {
468     if(aResult->groupName() == ModelAPI_ResultPart::group()) {
469       int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
470       for(int a = aSize - 1; a >= 0; a--) {
471         ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
472         if(aPart.get() && aPart->data() == aResult->data()) {
473           ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
474           FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
475           // check that this result is not this-feature result (it is forbidden t oselect itself)
476           if(anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
477             return aPartResult;
478           }
479         }
480       }
481     }
482   } else { // if feature - construction is selected, it has only one result, return this result
483     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
484     if (aFeature.get() && aFeature->results().size() == 1 &&
485         aFeature->firstResult()->groupName() == ModelAPI_ResultConstruction::group())
486       return aFeature->firstResult();
487   }
488   return aResult;
489 }
490
491 FeaturePtr Model_AttributeSelection::contextFeature() {
492   if (myTmpContext.get() || myTmpSubShape.get()) {
493     return FeaturePtr(); // feature can not be selected temporarily
494   }
495   return std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
496 }
497 ObjectPtr Model_AttributeSelection::contextObject() {
498   FeaturePtr aRes = contextFeature();
499   if (aRes.get())
500     return aRes;
501   return context();
502 }
503
504
505 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
506 {
507   ModelAPI_AttributeSelection::setObject(theObject);
508   myRef.setObject(theObject);
509 }
510
511 TDF_LabelMap& Model_AttributeSelection::scope()
512 {
513   if (myScope.IsEmpty()) { // create a new scope if not yet done
514     // gets all features with named shapes that are before this feature label (before in history)
515     DocumentPtr aMyDoc = owner()->document();
516     std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
517     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
518     bool aMePassed = false;
519     CompositeFeaturePtr aComposite =
520       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
521     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
522     CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
523     if (aFeature.get()) {
524       aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
525       if (aCompositeOwner.get()) {
526          aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
527       }
528     }
529     // for group Scope is not limitet: this is always up to date objects
530     // this causes problem in galeries.py
531     //bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
532     for(; aFIter != allFeatures.end(); aFIter++) {
533       if (*aFIter == owner()) {  // the left features are created later (except subs of composite)
534         aMePassed = true;
535         continue;
536       }
537       //if (isGroup) aMePassed = false;
538       bool isInScope = !aMePassed;
539       if (!isInScope && aComposite.get()) {
540         // try to add sub-elements of composite if this is composite
541         if (aComposite->isSub(*aFIter))
542           isInScope = true;
543       }
544       // remove the composite-owner of this feature (sketch in extrusion-cut)
545       if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
546         isInScope = false;
547
548       if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
549         TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
550           (*aFIter)->data())->label().Father();
551         TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), true);
552         for(; aNSIter.More(); aNSIter.Next()) {
553           Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
554           if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
555             myScope.Add(aNS->Label());
556           }
557         }
558       }
559     }
560     // also add all naming labels created for external constructions
561     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(aMyDoc);
562     TDF_Label anExtDocLab = aDoc->extConstructionsLabel();
563     TDF_ChildIDIterator aNSIter(anExtDocLab, TNaming_NamedShape::GetID(), true);
564     for(; aNSIter.More(); aNSIter.Next()) {
565       Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
566       if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
567         myScope.Add(aNS->Label());
568       }
569     }
570   }
571   return myScope;
572 }
573
574 /// Sets the invalid flag if flag is false, or removes it if "true"
575 /// Returns theFlag
576 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
577   if (theFlag) {
578     theLab.ForgetAttribute(kINVALID_SELECTION);
579   } else {
580     TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
581   }
582   return theFlag;
583 }
584
585 void Model_AttributeSelection::split(
586   ResultPtr theContext, TopoDS_Shape theNewShape, TopAbs_ShapeEnum theType)
587 {
588   TopTools_ListOfShape aSubs;
589   for(TopoDS_Iterator anExplorer(theNewShape); anExplorer.More(); anExplorer.Next()) {
590     if (!anExplorer.Value().IsNull() &&
591       anExplorer.Value().ShapeType() == theType) {
592         aSubs.Append(anExplorer.Value());
593     } else { // invalid case; bad result shape, so, impossible to split easily
594       aSubs.Clear();
595       break;
596     }
597   }
598   if (aSubs.Extent() > 1) { // ok to split
599     TopTools_ListIteratorOfListOfShape aSub(aSubs);
600     GeomShapePtr aSubSh(new GeomAPI_Shape);
601     aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
602     setValue(theContext, aSubSh);
603     for(aSub.Next(); aSub.More(); aSub.Next()) {
604       GeomShapePtr aSubSh(new GeomAPI_Shape);
605       aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
606       myParent->append(theContext, aSubSh);
607     }
608   }
609 }
610
611 bool Model_AttributeSelection::update()
612 {
613   FeaturePtr aContextFeature = contextFeature();
614   if (aContextFeature.get()) {
615     return true;
616   }
617   TDF_Label aSelLab = selectionLabel();
618   ResultPtr aContext = context();
619   if (!aContext.get())
620     return setInvalidIfFalse(aSelLab, false);
621   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
622     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
623   }
624
625   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
626     std::shared_ptr<GeomAPI_Shape> aNoSelection;
627     bool aResult = selectPart(aContext, aNoSelection, true);
628     aResult = setInvalidIfFalse(aSelLab, aResult);
629     if (aResult) {
630       owner()->data()->sendAttributeUpdated(this);
631     }
632     return aResult;
633   }
634
635   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
636     // body: just a named shape, use selection mechanism from OCCT
637     TNaming_Selector aSelector(aSelLab);
638     TopoDS_Shape anOldShape;
639     if (!aSelector.NamedShape().IsNull()) {
640       anOldShape = aSelector.NamedShape()->Get();
641     }
642     bool aResult = aSelector.Solve(scope()) == Standard_True;
643     // must be before sending of updated attribute (1556)
644     aResult = setInvalidIfFalse(aSelLab, aResult);
645     TopoDS_Shape aNewShape;
646     if (!aSelector.NamedShape().IsNull()) {
647       aNewShape = aSelector.NamedShape()->Get();
648     }
649     if (anOldShape.IsNull() || aNewShape.IsNull() ||
650         !anOldShape.IsEqual(aSelector.NamedShape()->Get())) {
651       // shape type shoud not not changed: if shape becomes compound of such shapes, then split
652       if (myParent && !anOldShape.IsNull() && !aNewShape.IsNull() &&
653           anOldShape.ShapeType() != aNewShape.ShapeType() &&
654           (aNewShape.ShapeType() == TopAbs_COMPOUND || aNewShape.ShapeType() == TopAbs_COMPSOLID))
655       {
656         split(aContext, aNewShape, anOldShape.ShapeType());
657       }
658       owner()->data()->sendAttributeUpdated(this);  // send updated if shape is changed
659     }
660     return aResult;
661   }
662
663   if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
664     Handle(TDataStd_Integer) anIndex;
665     if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
666       std::shared_ptr<Model_ResultConstruction> aConstructionContext =
667         std::dynamic_pointer_cast<Model_ResultConstruction>(aContext);
668       bool aModified = true;
669       bool aValid = aConstructionContext->update(anIndex->Get(), owner()->document(), aModified);
670       setInvalidIfFalse(aSelLab, aValid);
671       if (aConstructionContext->isInfinite()) {
672         // Update the selected shape.
673         TNaming_Builder aBuilder(aSelLab);
674         aBuilder.Generated(aConstructionContext->shape()->impl<TopoDS_Shape>());
675       }
676       if (aModified)
677         owner()->data()->sendAttributeUpdated(this);
678       return aValid;
679     }
680   }
681   return setInvalidIfFalse(aSelLab, false); // unknown case
682 }
683
684 void Model_AttributeSelection::selectBody(
685   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
686 {
687   // perform the selection
688   TNaming_Selector aSel(selectionLabel());
689   TopoDS_Shape aContext;
690
691   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theContext);//myRef.value()
692   if (aBody) {
693     aContext = aBody->shape()->impl<TopoDS_Shape>();
694   } else {
695     ResultPtr aResult =
696       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
697     if (aResult) {
698       aContext = aResult->shape()->impl<TopoDS_Shape>();
699     } else {
700       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
701       return;
702     }
703   }
704
705   // with "recover" feature the selected context may be not up to date (issue 1710)
706   Handle(TNaming_NamedShape) aResult;
707   TDF_Label aSelLab = selectionLabel();
708   TopoDS_Shape aNewContext = aContext;
709   bool isUpdated = true;
710   while(!aNewContext.IsNull() && isUpdated) {
711     // searching for the very last shape that was produced from this one
712     isUpdated = false;
713     if (!TNaming_Tool::HasLabel(aSelLab, aNewContext))
714       // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
715       break;
716     for(TNaming_SameShapeIterator anIter(aNewContext, aSelLab); anIter.More(); anIter.Next()) {
717       TDF_Label aNSLab = anIter.Label();
718       if (!scope().Contains(aNSLab))
719         continue;
720       Handle(TNaming_NamedShape) aNS;
721       if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
722         for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
723           if (aShapesIter.Evolution() == TNaming_SELECTED)
724             continue; // don't use the selection evolution
725           if (!aShapesIter.OldShape().IsNull() && aShapesIter.OldShape().IsSame(aNewContext)) {
726              // found the original shape
727             aNewContext = aShapesIter.NewShape(); // go to the newer shape
728             isUpdated = true;
729             break;
730           }
731         }
732       }
733     }
734   }
735   if (aNewContext.IsNull()) { // a context is already deleted
736     setInvalidIfFalse(aSelLab, false);
737     Events_InfoMessage("Model_AttributeSelection", "Failed to select shape already deleted").send();
738     return;
739   }
740
741   TopoDS_Shape aNewSub = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
742   if (!aNewSub.IsEqual(aContext)) { // searching for subshape in the new context
743     bool isFound = false;
744     TopExp_Explorer anExp(aNewContext, aNewSub.ShapeType());
745     for(; anExp.More(); anExp.Next()) {
746       if (anExp.Current().IsSame(aNewSub)) {
747         isFound = true;
748         break;
749       }
750     }
751     if (!isFound) { // sub-shape is not found in the up-to-date instance of the context shape
752       // if context is sub-result of compound/compsolid, selection of sub-shape better propagate to
753       // the main result (which is may be modified); the case is in 1799
754       ResultBodyPtr aMain = ModelAPI_Tools::bodyOwner(theContext);
755       while(ModelAPI_Tools::bodyOwner(aMain).get())
756         aMain = ModelAPI_Tools::bodyOwner(theContext);
757       if (aMain.get()) {
758         selectBody(aMain, theSubShape);
759         return;
760       }
761       setInvalidIfFalse(aSelLab, false);
762       Events_InfoMessage("Model_AttributeSelection",
763         "Failed to select sub-shape already modified").send();
764       return;
765     }
766   }
767
768   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
769   if (!aContext.IsNull()) {
770     FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
771     bool aEraseResults = false;
772     if (aFeatureOwner.get()) {
773       aEraseResults = !aFeatureOwner->results().empty();
774       if (aEraseResults) // erase results without flash deleted and redisplay: do it after Select
775         aFeatureOwner->removeResults(0, false, false);
776     }
777     aSel.Select(aNewSub, aNewContext);
778     // face may become divided after the model update, so, new labels may be added to the scope
779     myScope.Clear();
780
781     if (aEraseResults) { // flash after Select : in Groups it makes selection with shift working
782       static Events_Loop* aLoop = Events_Loop::loop();
783       static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
784       aLoop->flush(kDeletedEvent);
785     }
786   }
787 }
788
789 bool Model_AttributeSelection::selectPart(
790   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
791   const bool theUpdate)
792 {
793   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
794   if (!aPart.get() || !aPart->isActivated())
795     return true; // postponed naming
796   if (theUpdate) {
797     Handle(TDataStd_Integer) anIndex;
798     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
799       // by internal selection
800       if (anIndex->Get() > 0) {
801         // update the selection by index
802         return aPart->updateInPart(anIndex->Get());
803       } else {
804         return true; // nothing to do, referencing just by name
805       }
806     }
807     return true; // nothing to do, referencing just by name
808   }
809   // store the shape (in case part is not loaded it should be useful
810   TopoDS_Shape aShape;
811   std::string aName = theContext->data()->name();
812   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
813     aShape = theContext->shape()->impl<TopoDS_Shape>();
814   } else {
815     aShape = theSubShape->impl<TopoDS_Shape>();
816     int anIndex;
817     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
818     TDataStd_Integer::Set(selectionLabel(), anIndex);
819   }
820   TNaming_Builder aBuilder(selectionLabel());
821   aBuilder.Select(aShape, aShape);
822   // identify by name in the part
823   TDataStd_Name::Set(selectionLabel(), aName.c_str());
824   return !aName.empty();
825 }
826
827 TDF_Label Model_AttributeSelection::selectionLabel()
828 {
829   return myRef.myRef->Label().FindChild(1);
830 }
831
832 /// prefixes of the shape names with centers defined
833 static std::map<ModelAPI_AttributeSelection::CenterType, std::string> kCENTERS_PREFIX;
834
835 /// returns the map that contains all possible prefixes of the center-names
836 static std::map<ModelAPI_AttributeSelection::CenterType, std::string>& centersMap()
837 {
838   if (kCENTERS_PREFIX.empty()) { // fill map by initial values
839     kCENTERS_PREFIX[ModelAPI_AttributeSelection::CIRCLE_CENTER] = "__cc";
840     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS] = "__eff";
841     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_SECOND_FOCUS] = "__esf";
842   }
843   return kCENTERS_PREFIX;
844 }
845
846 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
847 {
848   std::string aName("");
849   if(!this->isInitialized())
850     return !theDefaultName.empty() ? theDefaultName : aName;
851
852   CenterType aCenterType = NOT_CENTER;
853   std::shared_ptr<GeomAPI_Shape> aSubSh = internalValue(aCenterType);
854   ResultPtr aCont = context();
855
856   if (!aCont.get() ||
857       (aCont->groupName() == ModelAPI_ResultConstruction::group() && contextFeature().get())) {
858     // selection of a full feature
859     FeaturePtr aFeatureCont = contextFeature();
860     if (aFeatureCont.get()) {
861       return kWHOLE_FEATURE + aFeatureCont->name();
862     }
863     // in case of selection of removed result
864     return "";
865   }
866
867   Model_SelectionNaming aSelNaming(selectionLabel());
868   std::string aResult = aSelNaming.namingName(
869     aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
870   if (aCenterType != NOT_CENTER) {
871     aResult += centersMap()[aCenterType];
872   }
873   return aResult;
874 }
875
876 // returns the center type and modifies the shape name if this name is center-name
877 static ModelAPI_AttributeSelection::CenterType centerTypeByName(std::string& theShapeName)
878 {
879   std::map<ModelAPI_AttributeSelection::CenterType, std::string>::iterator aPrefixIter =
880     centersMap().begin();
881   for(; aPrefixIter != centersMap().end(); aPrefixIter++) {
882     std::size_t aFound = theShapeName.find(aPrefixIter->second);
883     if (aFound != std::string::npos &&
884         aFound == theShapeName.size() - aPrefixIter->second.size()) {
885       theShapeName = theShapeName.substr(0, aFound);
886       return aPrefixIter->first;
887     }
888   }
889   return ModelAPI_AttributeSelection::NOT_CENTER;
890 }
891
892 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
893 void Model_AttributeSelection::selectSubShape(
894   const std::string& theType, const std::string& theSubShapeName)
895 {
896   if(theSubShapeName.empty() || theType.empty()) return;
897
898   std::string aSubShapeName = theSubShapeName;
899   CenterType aCenterType = theType[0] == 'v' || theType[0] == 'V' ? // only for vertex-type
900     centerTypeByName(aSubShapeName) : NOT_CENTER;
901   std::string aType = aCenterType == NOT_CENTER ? theType : "EDGE"; // search for edge now
902
903   // first iteration is selection by name without center prefix, second - in case of problem,
904   // try with initial name
905   for(int aUseCenter = 1; aUseCenter >= 0; aUseCenter--) {
906     if (aUseCenter == 0 && aCenterType != NOT_CENTER) {
907       aSubShapeName = theSubShapeName;
908       aCenterType = NOT_CENTER;
909       aType = theType;
910     } else if (aUseCenter != 1) continue;
911
912     // check this is Part-name: 2 delimiters in the name
913     std::size_t aPartEnd = aSubShapeName.find('/');
914     if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
915       std::string aPartName = aSubShapeName.substr(0, aPartEnd);
916       ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
917       if (aFound.get()) { // found such part, so asking it for the name
918         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
919         std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
920         int anIndex;
921         std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, aType, anIndex);
922         if (aSelected.get()) {
923           if (aCenterType != NOT_CENTER) {
924             if (!aSelected->isEdge())
925               continue;
926             std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aSelected));
927             setValueCenter(aPart, aSelectedEdge, aCenterType);
928           } else
929             setValue(aPart, aSelected);
930           TDataStd_Integer::Set(selectionLabel(), anIndex);
931           return;
932         }
933       }
934     }
935
936     std::shared_ptr<Model_Document> aDoc =
937       std::dynamic_pointer_cast<Model_Document>(owner()->document());
938     // check this is a whole feature context
939     if (aSubShapeName.size() > kWHOLE_FEATURE.size() &&
940       aSubShapeName.substr(0, kWHOLE_FEATURE.size()) == kWHOLE_FEATURE) {
941       std::string aFeatureName = aSubShapeName.substr(kWHOLE_FEATURE.size());
942       ObjectPtr anObj = aDoc->objectByName(ModelAPI_Feature::group(), aFeatureName);
943       if (anObj.get()) {
944         static const GeomShapePtr anEmptyShape;
945         setValue(anObj, anEmptyShape);
946         return;
947       }
948     }
949
950     Model_SelectionNaming aSelNaming(selectionLabel());
951     std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
952     ResultPtr aCont;
953     if (aSelNaming.selectSubShape(aType, aSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
954       // try to find the last context to find the up to date shape
955       if (aCont->shape().get() && !aCont->shape()->isNull() &&
956         aCont->groupName() == ModelAPI_ResultBody::group() && aDoc == owner()->document()) {
957         const TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
958         if (!aConShape.IsNull()) {
959           Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
960           if (!aNS.IsNull()) {
961             aNS = TNaming_Tool::CurrentNamedShape(aNS);
962             if (!aNS.IsNull() && scope().Contains(aNS->Label())) { // scope check is for 2228
963               TDF_Label aLab = aNS->Label();
964               if (aLab.Depth() % 2 == 0)
965                 aLab = aLab.Father();
966               ObjectPtr anObj = aDoc->objects()->object(aLab);
967               while(!anObj.get() && aLab.Depth() > 5) {
968                 aLab = aLab.Father().Father();
969                 anObj = aDoc->objects()->object(aLab);
970               }
971
972               if (anObj.get()) {
973                 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
974                 if (aRes)
975                   aCont = aRes;
976               }
977             }
978           }
979         }
980       }
981       // if compsolid is context, try to take sub-solid as context: like in GUI and scripts
982       if (aCont.get() && aShapeToBeSelected.get()) {
983         ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aCont);
984         if (aComp && aComp->numberOfSubs()) {
985           std::list<ResultPtr> allSubs;
986           ModelAPI_Tools::allSubs(aComp, allSubs);
987           std::list<ResultPtr>::iterator aS = allSubs.begin();
988           for(; aS != allSubs.end(); aS++) {
989             ResultBodyPtr aSub = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aS);
990             if (aSub && aSub->numberOfSubs() == 0 && aSub->shape().get() &&
991                 aSub->shape()->isSubShape(aShapeToBeSelected)) {
992               aCont = aSub;
993               break;
994             }
995           }
996         }
997       }
998       // try to find the latest active result that must be used instead of the selected
999       // to set the active context (like in GUI selection), not concealed one
1000       bool aFindNewContext = true;
1001       while(aFindNewContext && aCont.get()) {
1002         aFindNewContext = false;
1003         // take references to all results: root one, any sub
1004         ResultBodyPtr aCompContext = ModelAPI_Tools::bodyOwner(aCont, true);
1005         std::list<ResultPtr> allRes;
1006         if (aCompContext.get()) {
1007           ModelAPI_Tools::allSubs(aCompContext, allRes);
1008           allRes.push_back(aCompContext);
1009         } else {
1010           allRes.push_back(aCont);
1011         }
1012         for(std::list<ResultPtr>::iterator aSub = allRes.begin(); aSub != allRes.end(); aSub++) {
1013           ResultPtr aResCont = *aSub;
1014           ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResCont);
1015           // only lower and higher level subs are counted
1016           if (aResBody.get() && aResBody->numberOfSubs() > 0 && aResBody != aCompContext)
1017             continue;
1018           const std::set<AttributePtr>& aRefs = aResCont->data()->refsToMe();
1019           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1020           for(; !aFindNewContext && aRef != aRefs.end(); aRef++) {
1021             if (!aRef->get() || !(*aRef)->owner().get())
1022               continue;
1023             // concealed attribute only
1024             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1025             if (!ModelAPI_Session::get()->validators()->isConcealed(
1026               aRefFeat->getKind(), (*aRef)->id()))
1027               continue;
1028             // search the feature result that contains sub-shape selected
1029             std::list<std::shared_ptr<ModelAPI_Result> > aResults;
1030
1031             // take all sub-results or one result
1032             std::list<ResultPtr> aRefFeatResults;
1033             ModelAPI_Tools::allResults(aRefFeat, aRefFeatResults);
1034             std::list<ResultPtr>::iterator aRefResIter = aRefFeatResults.begin();
1035             for(; aRefResIter != aRefFeatResults.end(); aRefResIter++) {
1036               ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRefResIter);
1037               if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1038                 aResults.push_back(aBody);
1039             }
1040             std::list<std::shared_ptr<ModelAPI_Result> >::iterator aResIter = aResults.begin();
1041             for(; aResIter != aResults.end(); aResIter++) {
1042               if (!aResIter->get() || !(*aResIter)->data()->isValid() || (*aResIter)->isDisabled())
1043                 continue;
1044               GeomShapePtr aShape = (*aResIter)->shape();
1045               GeomShapePtr aSelectedShape =
1046                 aShapeToBeSelected.get() ? aShapeToBeSelected : aCont->shape();
1047               if (aShape.get() && aShape->isSubShape(aSelectedShape, false)) {
1048                 aCont = *aResIter; // found new context (produced from this) with same subshape
1049                 aFindNewContext = true; // continue searching futher
1050                 break;
1051               }
1052             }
1053           }
1054         }
1055       }
1056
1057       if (aCenterType != NOT_CENTER) {
1058         if (!aShapeToBeSelected->isEdge())
1059           continue;
1060         std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aShapeToBeSelected));
1061         setValueCenter(aCont, aSelectedEdge, aCenterType);
1062       } else
1063         setValue(aCont, aShapeToBeSelected);
1064       return;
1065     }
1066   }
1067
1068   TDF_Label aSelLab = selectionLabel();
1069   setInvalidIfFalse(aSelLab, false);
1070   reset();
1071 }
1072
1073 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1074                                               const GeomPointPtr& thePoint)
1075 {
1076   if (theType.empty() || !thePoint)
1077     return;
1078
1079   // list of parent features
1080   FeaturePtr anOwner = ModelAPI_Feature::feature(owner());
1081   std::set<FeaturePtr> aParents = ModelAPI_Tools::getParents(anOwner);
1082
1083   int aSelectionIndex = 0;
1084   GeomAPI_Shape::ShapeType aType = GeomAPI_Shape::shapeTypeByStr(theType);
1085   if (aType == GeomAPI_Shape::SHAPE) {
1086     // possibly, the string consists of the type and the index,
1087     // thus, try to separate them
1088     size_t aUndersporePos = theType.find_first_of('_');
1089     if (aUndersporePos != std::string::npos)
1090       aType = GeomAPI_Shape::shapeTypeByStr(theType.substr(0, aUndersporePos));
1091
1092     if (aType != GeomAPI_Shape::SHAPE) {
1093       for (std::string::const_iterator aChar = theType.begin() + aUndersporePos + 1;
1094            aChar != theType.end(); ++aChar) {
1095         if (std::isdigit(*aChar))
1096           aSelectionIndex = aSelectionIndex * 10 + (*aChar - '0');
1097         else {
1098           aSelectionIndex = 1;
1099           break;
1100         }
1101       }
1102       aSelectionIndex -= 1;
1103     }
1104   }
1105
1106   std::list<ModelGeomAlgo_Shape::SubshapeOfResult> anAppropriate;
1107
1108   // collect features from PartSet and the current part
1109   SessionPtr aSession = ModelAPI_Session::get();
1110   std::list<FeaturePtr> aFeatures = aSession->moduleDocument()->allFeatures();
1111   if (aSession->moduleDocument() != owner()->document()) {
1112     std::list<FeaturePtr> aPartFeatures = owner()->document()->allFeatures();
1113     aFeatures.insert(aFeatures.end(), aPartFeatures.begin(), aPartFeatures.end());
1114   }
1115   // Process results of all features from the last to the first
1116   // to find appropriate sub-shape
1117   for (std::list<FeaturePtr>::const_reverse_iterator anIt = aFeatures.rbegin();
1118        anIt != aFeatures.rend(); ++anIt) {
1119     // selection cannot be linked to the parent features
1120     if (aParents.find(*anIt) != aParents.end())
1121       continue;
1122     // check the feature is a part of composite feature (like sketch elements),
1123     // then do not process it, it will be processed in scope of composite feature
1124     bool isSubOfComposite = false;
1125     const std::set<AttributePtr>& aRefs = (*anIt)->data()->refsToMe();
1126     for (std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
1127          aRefIt != aRefs.end() && !isSubOfComposite; ++aRefIt) {
1128       FeaturePtr aFeature = ModelAPI_Feature::feature((*aRefIt)->owner());
1129       CompositeFeaturePtr aCompFeature =
1130           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
1131       isSubOfComposite = aCompFeature && aCompFeature->isSub(*anIt);
1132     }
1133     if (isSubOfComposite)
1134       continue;
1135
1136     // process results of the current feature to find appropriate sub-shape
1137     if (ModelGeomAlgo_Shape::findSubshapeByPoint(*anIt, thePoint, aType, anAppropriate)) {
1138       std::list<ModelGeomAlgo_Shape::SubshapeOfResult>::iterator anApIt = anAppropriate.begin();
1139       for (; aSelectionIndex > 0 && anApIt != anAppropriate.end(); --aSelectionIndex)
1140         ++anApIt; // skip this shape, because one of the previous is selected
1141
1142       if (anApIt != anAppropriate.end()) {
1143         if (anApIt->myCenterType == (int)ModelAPI_AttributeSelection::NOT_CENTER)
1144           setValue(anApIt->myResult, anApIt->mySubshape);
1145         else
1146           setValueCenter(anApIt->myResult, anApIt->mySubshape->edge(),
1147                          (ModelAPI_AttributeSelection::CenterType)anApIt->myCenterType);
1148         return;
1149       }
1150     }
1151   }
1152
1153   TDF_Label aSelLab = selectionLabel();
1154   setInvalidIfFalse(aSelLab, false);
1155   reset();
1156 }
1157
1158 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1159   const std::string& theContextName, const int theIndex)
1160 {
1161   // selection of context by name
1162   //std::string aNamingContextName = theContextName + "/";
1163   //selectSubShape(theType, aNamingContextName);
1164   std::shared_ptr<Model_Document> aDoc =
1165     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1166   if (aDoc.get()) {
1167     bool aUnique = true;
1168     std::string aContextName = theContextName;
1169     std::string anEmptySub = "";
1170     ResultPtr aContext = aDoc->findByName(aContextName, anEmptySub, aUnique);
1171     //ResultPtr aContext = context();
1172     if (aContext.get()) {
1173       GeomShapePtr aContShape = aContext->shape();
1174       if (aContShape.get()) {
1175         GeomAlgoAPI_NExplode aNExp(aContShape, GeomAPI_Shape::shapeTypeByStr(theType));
1176         GeomShapePtr aValue = aNExp.shape(theIndex);
1177         if (aValue.get())
1178           setValue(aContext, aValue);
1179       }
1180     }
1181   }
1182 }
1183
1184 int Model_AttributeSelection::Id()
1185 {
1186   int anID = 0;
1187   std::shared_ptr<GeomAPI_Shape> aSelection = value();
1188   ResultPtr aContextRes = context();
1189   // support for compsolids:
1190   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1191     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1192   }
1193   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1194
1195
1196   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1197   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1198   // searching for the latest main shape
1199   if (aSelection && !aSelection->isNull() && aContext && !aContext->isNull())
1200   {
1201     std::shared_ptr<Model_Document> aDoc =
1202       std::dynamic_pointer_cast<Model_Document>(context()->document());
1203     if (aDoc.get()) {
1204       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1205       if (!aNS.IsNull()) {
1206         aMainShape = TNaming_Tool::CurrentShape(aNS);
1207       }
1208     }
1209
1210     TopTools_IndexedMapOfShape aSubShapesMap;
1211     TopExp::MapShapes(aMainShape, aSubShapesMap);
1212     anID = aSubShapesMap.FindIndex(aSubShape);
1213   }
1214   return anID;
1215 }
1216
1217 void Model_AttributeSelection::setId(int theID)
1218 {
1219   std::shared_ptr<GeomAPI_Shape> aSelection;
1220
1221   ResultPtr aContextRes = context();
1222   // support for compsolids:
1223   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1224     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1225   }
1226   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1227
1228   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1229   // searching for the latest main shape
1230   if (theID > 0 && aContext && !aContext->isNull())
1231   {
1232     std::shared_ptr<Model_Document> aDoc =
1233       std::dynamic_pointer_cast<Model_Document>(aContextRes->document());
1234     if (aDoc.get()) {
1235       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1236       if (!aNS.IsNull()) {
1237         aMainShape = TNaming_Tool::CurrentShape(aNS);
1238       }
1239     }
1240
1241     TopTools_IndexedMapOfShape aSubShapesMap;
1242     TopExp::MapShapes(aMainShape, aSubShapesMap);
1243     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1244
1245     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1246     aResult->setImpl(new TopoDS_Shape(aSelShape));
1247
1248     aSelection = aResult;
1249   }
1250
1251   setValue(aContextRes, aSelection);
1252 }
1253
1254 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1255 {
1256   std::string aResult;
1257   if (owner()->document() != theContext->document()) {
1258     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1259       aResult = theContext->document()->kind() + "/";
1260     } else {
1261       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1262         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1263       if (aDocRes.get()) {
1264         aResult = aDocRes->data()->name() + "/";
1265       }
1266     }
1267   }
1268   aResult += theContext->data()->name();
1269   return aResult;
1270 }
1271
1272 void Model_AttributeSelection::computeValues(
1273   ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
1274   TopTools_ListOfShape& theShapes)
1275 {
1276   bool aWasWholeContext = theValShape.IsNull();
1277   if (aWasWholeContext) {
1278     //theShapes.Append(theValShape);
1279     //return;
1280     theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
1281   }
1282   //TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
1283   TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
1284   //if (anOldContShape.IsSame(theValShape)) { // full context shape substituted by new full context
1285     //theShapes.Append(aNewContShape);
1286     //return;
1287   //}
1288   // if a new value is unchanged in the new context, do nothing: value is correct
1289   TopExp_Explorer aSubExp(aNewContShape, theValShape.ShapeType());
1290   for(; aSubExp.More(); aSubExp.Next()) {
1291     if (aSubExp.Current().IsSame(theValShape)) {
1292       theShapes.Append(theValShape);
1293       return;
1294     }
1295   }
1296   // if new context becomes compsolid, the resulting sub may be in sub-solids
1297   std::list<ResultPtr> aNewToIterate;
1298   aNewToIterate.push_back(theNewContext);
1299   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theNewContext);
1300   if (aComp.get()) {
1301     std::list<ResultPtr> allNewContextSubs;
1302     ModelAPI_Tools::allSubs(aComp, allNewContextSubs);
1303     std::list<ResultPtr>::iterator aSub = allNewContextSubs.begin();
1304     for(; aSub != allNewContextSubs.end(); aSub++) {
1305       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aSub);
1306       if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1307         aNewToIterate.push_back(aBody);
1308     }
1309   }
1310
1311   // first iteration: searching for the whole shape appearance (like face of the box)
1312   // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
1313   int aToFindPart = 0;
1314   TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
1315   TopTools_MapOfShape anOlds; // to know how many olds produced new containers
1316   for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
1317     std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
1318     for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
1319       std::shared_ptr<Model_Data> aNewData =
1320         std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
1321       TDF_Label aNewLab = aNewData->label();
1322       // searching for produced sub-shape fully on some label
1323       TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID(), Standard_True);
1324       for(; aNSIter.More(); aNSIter.Next()) {
1325         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1326         for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
1327           if (aToFindPart == 0) { // search shape is fully inside
1328             if (aPairIter.OldShape().IsSame(theValShape)) {
1329               if (aPairIter.NewShape().IsNull()) {// value was removed
1330                 theShapes.Clear();
1331                 return;
1332               }
1333               theShapes.Append(aPairIter.NewShape());
1334             }
1335           } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
1336             TopExp_Explorer anExp(aPairIter.OldShape(), theValShape.ShapeType());
1337             for(; anExp.More(); anExp.Next()) {
1338               if (anExp.Current().IsSame(theValShape)) { // found a new container
1339                 if (aPairIter.NewShape().IsNull()) {// value was removed
1340                   theShapes.Clear();
1341                   return;
1342                 }
1343                 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
1344                 anOlds.Add(aPairIter.OldShape());
1345                 break;
1346               }
1347             }
1348           }
1349         }
1350       }
1351     }
1352   }
1353   if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
1354     // map of sub-shapes -> number of occurences of these shapes in containers
1355     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
1356     TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
1357     for(; aContIter.More(); aContIter.Next()) {
1358       TopExp_Explorer aSubExp(aContIter.Key(), theValShape.ShapeType());
1359       for(; aSubExp.More(); aSubExp.Next()) {
1360         if (!aSubs.IsBound(aSubExp.Current())) {
1361           aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
1362         }
1363         // store old to know how many olds produced this shape
1364         aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
1365       }
1366     }
1367     // if sub is appeared same times in containers as the number of old shapes that contain it
1368     int aCountInOld = anOlds.Size();
1369     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
1370       aSubsIter(aSubs);
1371     for(; aSubsIter.More(); aSubsIter.Next()) {
1372       if (aSubsIter.Value().Size() == aCountInOld) {
1373         theShapes.Append(aSubsIter.Key());
1374       }
1375     }
1376   }
1377   if (theShapes.IsEmpty()) { // nothing was changed
1378     theShapes.Append(aWasWholeContext ? TopoDS_Shape() : theValShape);
1379   }
1380 }
1381
1382 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
1383   const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
1384   TDF_Label theAccessLabel,
1385   std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
1386 {
1387   std::set<ResultPtr> aResults; // to avoid duplicates, new context, null if deleted
1388   TopTools_ListOfShape aResContShapes;
1389   // iterate context and shape, but also if it is sub-shape of main shape, check also it
1390   TopTools_ListOfShape aContextList;
1391   aContextList.Append(theContShape);
1392   if (theContext.get()) {
1393     ResultPtr aComposite = ModelAPI_Tools::bodyOwner(theContext);
1394     if (aComposite.get() && aComposite->shape().get() && !aComposite->shape()->isNull())
1395       aContextList.Append(aComposite->shape()->impl<TopoDS_Shape>());
1396   }
1397   for(TopTools_ListOfShape::Iterator aContIter(aContextList); aContIter.More(); aContIter.Next()) {
1398     TNaming_SameShapeIterator aModifIter(aContIter.ChangeValue(), theAccessLabel);
1399     for(; aModifIter.More(); aModifIter.Next()) {
1400       TDF_Label anObjLab = aModifIter.Label().Father();
1401       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1402         (theDoc->objects()->object(anObjLab));
1403       if (!aModifierObj.get()) {
1404         // #2241: shape may be sub-element of new object, not main (shell created from faces)
1405         if (!anObjLab.IsRoot())
1406           aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1407           (theDoc->objects()->object(anObjLab.Father()));
1408         if (!aModifierObj.get())
1409           continue;
1410       }
1411       FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
1412       if (!aModifierFeat.get())
1413         continue;
1414       FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1415       if (aModifierFeat == aThisFeature || theDoc->objects()->isLater(aModifierFeat, aThisFeature))
1416         continue; // the modifier feature is later than this, so, should not be used
1417       FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
1418       if (aCurrentModifierFeat == aModifierFeat ||
1419         theDoc->objects()->isLater(aCurrentModifierFeat, aModifierFeat))
1420         continue; // the current modifier is later than the found, so, useless
1421       Handle(TNaming_NamedShape) aNewNS;
1422       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1423       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1424         aResults.insert(aModifierObj);
1425         //TNaming_Iterator aPairIter(aNewNS);
1426         //aResContShapes.Append(aPairIter.NewShape());
1427         aResContShapes.Append(aModifierObj->shape()->impl<TopoDS_Shape>());
1428       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
1429         aResults.insert(ResultPtr());
1430       } else { // not-precessed modification => don't support it
1431         continue;
1432       }
1433     }
1434   }
1435   if (aResults.empty())
1436     return false; // no modifications found, must stay the same
1437   // iterate all results to find futher modifications
1438   std::set<ResultPtr>::iterator aResIter = aResults.begin();
1439   for(; aResIter != aResults.end(); aResIter++) {
1440     if (aResIter->get() != NULL) {
1441       // compute new values by two contextes: the old and the new
1442       TopTools_ListOfShape aValShapes;
1443       computeValues(theContext, *aResIter, theValShape, aValShapes);
1444
1445       TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
1446       for(; aNewVal.More(); aNewVal.Next()) {
1447         std::list<ResultPtr> aNewRes;
1448         TopTools_ListOfShape aNewUpdatedVal;
1449         TopoDS_Shape aNewValSh = aNewVal.Value();
1450         TopoDS_Shape aNewContShape = (*aResIter)->shape()->impl<TopoDS_Shape>();
1451         if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
1452           aNewValSh.Nullify();
1453         if (searchNewContext(theDoc, aNewContShape, *aResIter, aNewValSh,
1454                              theAccessLabel, aNewRes, aNewUpdatedVal))
1455         {
1456           // appeand new results instead of the current ones
1457           std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1458           TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1459           for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1460             theResults.push_back(*aNewIter);
1461             theValShapes.Append(aNewUpdVal.Value());
1462           }
1463         } else { // the current result is good
1464           theResults.push_back(*aResIter);
1465           theValShapes.Append(aNewValSh);
1466         }
1467       }
1468     }
1469   }
1470   return true; // theResults must be empty: everything is deleted
1471 }
1472
1473 void Model_AttributeSelection::updateInHistory()
1474 {
1475   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1476   // only bodies and parts may be modified later in the history, don't do anything otherwise
1477   if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
1478       aContext->groupName() != ModelAPI_ResultPart::group()))
1479     return;
1480   std::shared_ptr<Model_Document> aDoc =
1481     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1482   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1483   if (!aContData.get() || !aContData->isValid())
1484     return;
1485   TDF_Label aContLab = aContData->label(); // named shape where the selected context is located
1486   Handle(TNaming_NamedShape) aContNS;
1487   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
1488     bool aFoundNewContext = true;
1489     ResultPtr aNewContext = aContext;
1490     while(aFoundNewContext) {
1491       aFoundNewContext = false;
1492       // parts have no shape in result, so, trace references using the Part info
1493       if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
1494         ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
1495         if (aPartContext.get()) { // searching for the up to date references to the referenced cont
1496           const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
1497           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1498           for(; aRef != aRefs.end(); aRef++) {
1499             // to avoid detection of part changes by local selection only
1500             AttributeSelectionPtr aSel =
1501               std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1502             if (aSel.get() && !aSel->value()->isSame(aSel->context()->shape()))
1503               continue;
1504
1505             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1506             if (aRefFeat.get() && aRefFeat != owner()) {
1507               FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1508               if (aDoc->objects()->isLater(aThisFeature, aRefFeat)) { // found better feature
1509                 aFoundNewContext = true;
1510                 aNewContext = aRefFeat->firstResult();
1511               }
1512             }
1513           }
1514         }
1515       }
1516     }
1517     if (aNewContext != aContext) {
1518       setValue(aNewContext, value());
1519     }
1520     return;
1521   }
1522   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1523   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1524   // iterate the context shape modifications in order to find a feature that is upper in history
1525   // that this one and is really modifies the referenced result to refer to it
1526   ResultPtr aModifierResFound;
1527   TNaming_Iterator aPairIter(aContNS);
1528   if (!aPairIter.More())
1529     return;
1530   TopoDS_Shape aNewCShape = aPairIter.NewShape();
1531   bool anIterate = true;
1532   // trying to update also the sub-shape selected
1533   GeomShapePtr aSubShape = value();
1534   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1535     aSubShape.reset();
1536   TopoDS_Shape aValShape;
1537   if (aSubShape.get()) {
1538     aValShape = aSubShape->impl<TopoDS_Shape>();
1539   }
1540
1541   std::list<ResultPtr> aNewContexts;
1542   TopTools_ListOfShape aValShapes;
1543   if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1544   {
1545     // update scope to reset to a new one
1546     myScope.Clear();
1547
1548     std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1549     TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1550     if (aNewCont == aNewContexts.end()) { // all results were deleted
1551       ResultPtr anEmptyContext;
1552       std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1553       setValue(anEmptyContext, anEmptyShape); // nullify the selection
1554       return;
1555     }
1556
1557     GeomShapePtr aValueShape;
1558     if (!aNewValues.Value().IsNull()) {
1559       aValueShape = std::make_shared<GeomAPI_Shape>();
1560       aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1561     }
1562     setValue(*aNewCont, aValueShape);
1563     // if there are more than one result, put them by "append" into "parent" list
1564     if (myParent) {
1565       for(aNewCont++, aNewValues.Next(); aNewCont != aNewContexts.end();
1566           aNewCont++, aNewValues.Next()) {
1567         GeomShapePtr aValueShape;
1568         if (!aNewValues.Value().IsNull()) {
1569           aValueShape = std::make_shared<GeomAPI_Shape>();
1570           aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1571         }
1572
1573         // Check that list has the same type of shape selection before adding.
1574         GeomAPI_Shape::ShapeType aListShapeType = GeomAPI_Shape::SHAPE;
1575         if (myParent->selectionType() == "VERTEX") aListShapeType = GeomAPI_Shape::VERTEX;
1576         else if (myParent->selectionType() == "EDGE") aListShapeType = GeomAPI_Shape::EDGE;
1577         else if (myParent->selectionType() == "FACE") aListShapeType = GeomAPI_Shape::FACE;
1578
1579         GeomAPI_Shape::ShapeType aShapeShapeType = GeomAPI_Shape::SHAPE;
1580         if (aValueShape.get()) {
1581           aShapeShapeType = aValueShape->shapeType();
1582         } else {
1583           (*aNewCont)->shape()->shapeType();
1584         }
1585
1586         if (aListShapeType != GeomAPI_Shape::SHAPE && aListShapeType != aShapeShapeType) {
1587           continue;
1588         }
1589
1590         myParent->append(*aNewCont, aValueShape);
1591       }
1592     }
1593   }
1594 }
1595
1596 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1597 {
1598   myParent = theParent;
1599 }