]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
Fix for the issue #3076 previous commit regression
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // Copyright (C) 2014-2019  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 email : webmaster.salome@opencascade.com
18 //
19
20 #include "Model_AttributeSelection.h"
21 #include "Model_Application.h"
22 #include "Model_Events.h"
23 #include "Model_Data.h"
24 #include "Model_Document.h"
25 #include <Model_Objects.h>
26 #include <Model_AttributeSelectionList.h>
27 #include <Model_ResultConstruction.h>
28 #include <ModelAPI_Feature.h>
29 #include <ModelAPI_ResultBody.h>
30 #include <ModelAPI_ResultBody.h>
31 #include <ModelAPI_ResultConstruction.h>
32 #include <ModelAPI_ResultGroup.h>
33 #include <ModelAPI_ResultPart.h>
34 #include <ModelAPI_CompositeFeature.h>
35 #include <ModelAPI_Tools.h>
36 #include <ModelAPI_Session.h>
37 #include <ModelAPI_Validator.h>
38 #include <ModelGeomAlgo_Shape.h>
39 #include <Events_InfoMessage.h>
40 #include <GeomAPI_Edge.h>
41 #include <GeomAPI_Pnt.h>
42 #include <GeomAPI_ShapeIterator.h>
43 #include <GeomAPI_Vertex.h>
44 #include <GeomAPI_ShapeExplorer.h>
45 #include <GeomAlgoAPI_CompoundBuilder.h>
46 #include <GeomAlgoAPI_NExplode.h>
47 #include <Selector_Selector.h>
48
49 #include <TNaming_NamedShape.hxx>
50 #include <TNaming_Tool.hxx>
51 #include <TNaming_Builder.hxx>
52 #include <TNaming_SameShapeIterator.hxx>
53 #include <TNaming_NewShapeIterator.hxx>
54 #include <TNaming_Iterator.hxx>
55 #include <TDataStd_Integer.hxx>
56 #include <TDataStd_UAttribute.hxx>
57 #include <TDataStd_Name.hxx>
58 #include <TopTools_ListOfShape.hxx>
59 #include <TopTools_DataMapOfShapeShape.hxx>
60 #include <TopTools_MapOfShape.hxx>
61 #include <TopExp_Explorer.hxx>
62 #include <BRep_Tool.hxx>
63 #include <TopoDS.hxx>
64 #include <TopoDS_Edge.hxx>
65 #include <TopExp.hxx>
66 #include <TDF_ChildIterator.hxx>
67 #include <TDF_ChildIDIterator.hxx>
68 #include <TopoDS_Iterator.hxx>
69 #include <TDF_ChildIDIterator.hxx>
70 #include <Geom_Circle.hxx>
71 #include <Geom_Ellipse.hxx>
72 #include <Geom_TrimmedCurve.hxx>
73 #include <BRep_Builder.hxx>
74
75 //#define DEB_NAMING 1
76 #ifdef DEB_NAMING
77 #include <BRepTools.hxx>
78 #endif
79 /// added to the index in the packed map to signalize that the vertex of edge is selected
80 /// (multiplied by the index of the edge)
81 static const int kSTART_VERTEX_DELTA = 1000000;
82 // identifier that there is simple reference: selection equals to context
83 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
84 // reference to Part sub-object
85 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
86 // selection is invalid after recomputation
87 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
88
89 // identifier of the selection of the center of circle on edge
90 Standard_GUID kCIRCLE_CENTER("d0d0e0f1-217a-4b95-8fbb-0c4132f23718");
91 // identifier of the selection of the first focus point of ellipse on edge
92 Standard_GUID kELLIPSE_CENTER1("f70df04c-3168-4dc9-87a4-f1f840c1275d");
93 // identifier of the selection of the second focus point of ellipse on edge
94 Standard_GUID kELLIPSE_CENTER2("1395ae73-8e02-4cf8-b204-06ff35873a32");
95
96 // prefix for the whole feature context identification
97 const static std::string kWHOLE_FEATURE = "all-in-";
98
99 // on this label is stored:
100 // TNaming_NamedShape - selected shape
101 // TNaming_Naming - topological selection information (for the body)
102 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
103 // TDataStd_Integer - type of the selected shape (for construction)
104 // TDF_Reference - from ReferenceAttribute, the context
105 bool Model_AttributeSelection::setValue(const ObjectPtr& theContext,
106   const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
107 {
108   if (theTemporarily) {
109     // just keep the stored without DF update
110     myTmpContext = theContext;
111     myTmpSubShape = theSubShape;
112     owner()->data()->sendAttributeUpdated(this);
113     return true;
114   } else {
115     myTmpContext.reset();
116     myTmpSubShape.reset();
117     myTmpCenterType = NOT_CENTER;
118   }
119
120   CenterType aType;
121   const std::shared_ptr<GeomAPI_Shape>& anOldShape = internalValue(aType);
122   bool isOldContext = theContext == myRef.value();
123   bool isOldShape = isOldContext &&
124     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
125   if (isOldShape) return false; // shape is the same, so context is also unchanged
126   bool aToUnblock = false;
127   // update the referenced object if needed
128   if (!isOldContext) {
129     aToUnblock = !owner()->data()->blockSendAttributeUpdated(true);
130     myRef.setValue(theContext);
131   }
132
133   // do not use naming if selected shape is result shape itself, but not sub-shape
134   TDF_Label aSelLab = selectionLabel();
135   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
136   aSelLab.ForgetAttribute(kINVALID_SELECTION);
137   aSelLab.ForgetAttribute(kCIRCLE_CENTER);
138   aSelLab.ForgetAttribute(kELLIPSE_CENTER1);
139   aSelLab.ForgetAttribute(kELLIPSE_CENTER2);
140
141   bool isDegeneratedEdge = false;
142   // do not use the degenerated edge as a shape, a null context and shape is used in the case
143   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
144     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
145     if (aSubShape.ShapeType() == TopAbs_EDGE)
146       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
147   }
148   if (!theContext.get() || isDegeneratedEdge) {
149     // to keep the reference attribute label
150     TDF_Label aRefLab = myRef.myRef->Label();
151     aSelLab.ForgetAllAttributes(true);
152     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
153     if (aToUnblock)
154       owner()->data()->blockSendAttributeUpdated(false);
155     return false;
156   }
157   bool isSelectBody = theContext->groupName() == ModelAPI_ResultBody::group();
158   if (!isSelectBody) {
159     ResultConstructionPtr aContextConstruction =
160       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
161     isSelectBody = aContextConstruction.get() && !aContextConstruction->isInfinite();
162   }
163   if (isSelectBody) {
164     ResultPtr aContextResult = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
165     GeomShapePtr aContextShape = aContextResult->shape();
166     // do not select the whole shape for body:it is already must be in the data framework
167     // equal and null selected objects mean the same: object is equal to context,
168     if (aContextShape.get() && (aContextShape->isEqual(theSubShape) || !theSubShape.get())) {
169       aSelLab.ForgetAllAttributes(true);
170       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
171     } else {
172       selectBody(aContextResult, theSubShape);
173     }
174   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
175     aSelLab.ForgetAllAttributes(true); // to remove old selection data
176     std::shared_ptr<Model_ResultConstruction> aConstruction =
177       std::dynamic_pointer_cast<Model_ResultConstruction>(theContext);
178     std::shared_ptr<GeomAPI_Shape> aSubShape;
179     if (theSubShape.get() && !aConstruction->shape()->isEqual(theSubShape))
180       aSubShape = theSubShape; // the whole context
181   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
182     aSelLab.ForgetAllAttributes(true);
183     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
184     selectPart(std::dynamic_pointer_cast<ModelAPI_Result>(theContext), theSubShape);
185   } else if (theContext->groupName() == ModelAPI_ResultGroup::group()) {
186     aSelLab.ForgetAllAttributes(true);
187     TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
188   } else { // check the feature context: parent-Part of this feature should not be used
189     FeaturePtr aFeatureContext = std::dynamic_pointer_cast<ModelAPI_Feature>(theContext);
190     if (aFeatureContext.get()) {
191       if (owner()->document() != aFeatureContext->document()) {
192         aSelLab.ForgetAllAttributes(true);
193         myRef.setValue(ObjectPtr());
194         if (aToUnblock)
195           owner()->data()->blockSendAttributeUpdated(false);
196         return false;
197       }
198     }
199   }
200
201   owner()->data()->sendAttributeUpdated(this);
202
203   if (aToUnblock)
204     owner()->data()->blockSendAttributeUpdated(false);
205
206   return true;
207 }
208
209 void Model_AttributeSelection::setValueCenter(
210     const ObjectPtr& theContext, const std::shared_ptr<GeomAPI_Edge>& theEdge,
211     const CenterType theCenterType, const bool theTemporarily)
212 {
213   bool anUpdated = setValue(theContext, theEdge, theTemporarily);
214   if (theTemporarily) {
215     myTmpCenterType = theCenterType;
216   } else { // store in the data structure
217     TDF_Label aSelLab = selectionLabel();
218     switch(theCenterType) {
219     case CIRCLE_CENTER:
220       if (!anUpdated)
221         anUpdated = !aSelLab.IsAttribute(kCIRCLE_CENTER);
222       TDataStd_UAttribute::Set(aSelLab, kCIRCLE_CENTER);
223       break;
224     case ELLIPSE_FIRST_FOCUS:
225       if (!anUpdated)
226         anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER1);
227       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER1);
228       break;
229     case ELLIPSE_SECOND_FOCUS:
230       if (!anUpdated)
231         anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER2);
232       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER2);
233       break;
234     }
235     if (anUpdated)
236       owner()->data()->sendAttributeUpdated(this);
237   }
238 }
239
240 void Model_AttributeSelection::selectValue(
241     const std::shared_ptr<ModelAPI_AttributeSelection>& theSource)
242 {
243   CenterType aType;
244   std::shared_ptr<GeomAPI_Shape> aValue =
245     std::dynamic_pointer_cast<Model_AttributeSelection>(theSource)->internalValue(aType);
246   if (!aValue.get() || aType == NOT_CENTER) {
247     setValue(theSource->context(), aValue);
248   } else {
249     std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge);
250     anEdge->setImpl(new TopoDS_Shape(aValue->impl<TopoDS_Shape>()));
251     setValueCenter(theSource->context(), anEdge, aType);
252   }
253 }
254
255 void Model_AttributeSelection::removeTemporaryValues()
256 {
257   if (myTmpContext.get() || myTmpSubShape.get()) {
258     myTmpContext.reset();
259     myTmpSubShape.reset();
260   }
261 }
262
263 // returns the center of the edge: circular or elliptic
264 GeomShapePtr centerByEdge(GeomShapePtr theEdge, ModelAPI_AttributeSelection::CenterType theType)
265 {
266   if (theType != ModelAPI_AttributeSelection::NOT_CENTER && theEdge.get() != NULL) {
267     TopoDS_Shape aShape = theEdge->impl<TopoDS_Shape>();
268     if (!aShape.IsNull() && aShape.ShapeType() == TopAbs_EDGE) {
269       TopoDS_Edge anEdge = TopoDS::Edge(aShape);
270       double aFirst, aLast;
271       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
272       if (!aCurve.IsNull()) {
273         TopoDS_Vertex aVertex;
274         BRep_Builder aBuilder;
275         if (theType == ModelAPI_AttributeSelection::CIRCLE_CENTER) {
276           while(!aCurve.IsNull() && aCurve->DynamicType() == STANDARD_TYPE(Geom_TrimmedCurve))
277             aCurve = Handle(Geom_TrimmedCurve)::DownCast(aCurve)->BasisCurve();
278           Handle(Geom_Circle) aCirc = Handle(Geom_Circle)::DownCast(aCurve);
279           if (!aCirc.IsNull()) {
280             aBuilder.MakeVertex(aVertex, aCirc->Location(), Precision::Confusion());
281           }
282         } else { // ellipse
283           while(!aCurve.IsNull() && aCurve->DynamicType() == STANDARD_TYPE(Geom_TrimmedCurve))
284             aCurve = Handle(Geom_TrimmedCurve)::DownCast(aCurve)->BasisCurve();
285           Handle(Geom_Ellipse) anEll = Handle(Geom_Ellipse)::DownCast(aCurve);
286           if (!anEll.IsNull()) {
287             aBuilder.MakeVertex(aVertex,
288               theType == ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS ?
289               anEll->Focus1() : anEll->Focus2(), Precision::Confusion());
290           }
291         }
292         if (!aVertex.IsNull()) {
293           std::shared_ptr<GeomAPI_Vertex> aResult(new GeomAPI_Vertex);
294           aResult->setImpl(new TopoDS_Vertex(aVertex));
295           return aResult;
296         }
297       }
298     }
299   }
300   return theEdge; // no vertex, so, return the initial edge
301 }
302
303 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
304 {
305   if (!ModelAPI_AttributeSelection::isInitialized() && !myTmpContext.get() && !myTmpSubShape.get())
306     return std::shared_ptr<GeomAPI_Shape>();
307   CenterType aType = NOT_CENTER;
308   std::shared_ptr<GeomAPI_Shape> aResult = internalValue(aType);
309   return centerByEdge(aResult, aType);
310 }
311
312 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::internalValue(CenterType& theType)
313 {
314   theType = NOT_CENTER;
315   GeomShapePtr aResult;
316   if (myTmpContext.get() || myTmpSubShape.get()) {
317     theType = myTmpCenterType;
318     ResultConstructionPtr aResulConstruction =
319       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myTmpContext);
320     if(aResulConstruction.get()) {
321       // it is just reference to construction.
322       return myTmpSubShape;
323     }
324     FeaturePtr aFeature =
325       std::dynamic_pointer_cast<ModelAPI_Feature>(myTmpContext);
326     if (aFeature.get()) {
327       // it is just reference to construction.
328       return myTmpSubShape;
329     }
330     return myTmpSubShape.get() ? myTmpSubShape :
331       std::dynamic_pointer_cast<ModelAPI_Result>(myTmpContext)->shape();
332   }
333
334   TDF_Label aSelLab = selectionLabel();
335   if (aSelLab.IsAttribute(kINVALID_SELECTION))
336     return aResult;
337
338   if (aSelLab.IsAttribute(kCIRCLE_CENTER))
339     theType = CIRCLE_CENTER;
340   else if (aSelLab.IsAttribute(kELLIPSE_CENTER1))
341     theType = ELLIPSE_FIRST_FOCUS;
342   else if (aSelLab.IsAttribute(kELLIPSE_CENTER2))
343     theType = ELLIPSE_SECOND_FOCUS;
344
345
346   if (myRef.isInitialized()) {
347     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
348       ResultPtr aContext = context();
349       if (!aContext.get() || aContext->groupName() == ModelAPI_ResultConstruction::group())
350         return aResult; // empty result, for whole construction selection also
351       return aContext->shape();
352     }
353     if (aSelLab.IsAttribute(kPART_REF_ID)) {
354       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
355       if (!aPart.get() || !aPart->isActivated())
356         return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
357       Handle(TDataStd_Integer) anIndex;
358       if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
359         if (anIndex->Get()) { // special selection attribute was created, use it
360           return aPart->selectionValue(anIndex->Get());
361         } else { // face with name is already in the data model, so try to take it by name
362           Handle(TDataStd_Name) aName;
363           if (aSelLab.FindAttribute(TDataStd_Name::GetID(), aName)) {
364             std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
365             std::size_t aPartEnd = aSubShapeName.find('/');
366             if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
367               std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
368               int anIndex;
369               std::string aType; // to reuse already existing selection the type is not needed
370               return aPart->shapeInPart(aNameInPart, aType, anIndex);
371             }
372           }
373         }
374       }
375     }
376
377     std::shared_ptr<Model_ResultConstruction> aConstr =
378       std::dynamic_pointer_cast<Model_ResultConstruction>(context());
379     if (aConstr) {
380       if (aConstr->isInfinite())
381         return aResult; // empty result
382     }
383     if (!aConstr.get()) { // for construction context, return empty result as usual even
384       // the whole feature is selected
385       FeaturePtr aFeature = contextFeature();
386       if (aFeature.get()) {
387         std::list<GeomShapePtr> allShapes;
388         std::list<ResultPtr>::const_iterator aRes = aFeature->results().cbegin();
389         for (; aRes != aFeature->results().cend(); aRes++) {
390           if (aRes->get() && !(*aRes)->isDisabled()) {
391             GeomShapePtr aShape = (*aRes)->shape();
392             if (aShape.get() && !aShape->isNull()) {
393               allShapes.push_back(aShape);
394             }
395           }
396         }
397         return GeomAlgoAPI_CompoundBuilder::compound(allShapes);
398       }
399     } else {
400       if (contextFeature().get()) {
401         return aResult; // for the whole sketch feature selected return null => all faces
402       }
403     }
404
405     Handle(TNaming_NamedShape) aSelection;
406     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
407       TopoDS_Shape aSelShape = aSelection->Get();
408       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
409       aResult->setImpl(new TopoDS_Shape(aSelShape));
410     } else if (aConstr) { // simple construction element: just shape of this construction element
411       aResult = aConstr->shape();
412     }
413   }
414   return aResult;
415 }
416
417 bool Model_AttributeSelection::isInvalid()
418 {
419   return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
420 }
421
422 bool Model_AttributeSelection::isInitialized()
423 {
424   if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
425     std::shared_ptr<GeomAPI_Shape> aResult;
426     if (myRef.isInitialized()) {
427       TDF_Label aSelLab = selectionLabel();
428       // it is just reference to shape, not sub-shape
429       if (aSelLab.IsAttribute(kSIMPLE_REF_ID) || aSelLab.IsAttribute(kPART_REF_ID)) {
430         ResultPtr aContext = context();
431         return aContext.get() != NULL;
432       }
433       Handle(TNaming_NamedShape) aSelection;
434       if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
435         return !aSelection->Get().IsNull();
436       } else { // for simple construction element: just shape of this construction element
437         if (myRef.value().get())
438           return true;
439         // check that this is on open of document, so, results are not initialized yet
440         TDF_Label aRefLab = myRef.myRef->Get();
441         if (aRefLab.IsNull() || !owner().get())
442           return false;
443         std::shared_ptr<Model_Document> aMyDoc =
444           std::dynamic_pointer_cast<Model_Document>(owner()->document());
445         if (!aMyDoc.get())
446           return false;
447         // check at least the feature exists
448         return aMyDoc->featureByLab(aRefLab).get() != NULL;
449       }
450     }
451   }
452   return false;
453 }
454
455 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
456 : myRef(theLabel),
457   myIsGeometricalSelection(false)
458 {
459   myIsInitialized = myRef.isInitialized();
460   myParent = NULL;
461 }
462
463 void Model_AttributeSelection::setID(const std::string theID)
464 {
465   myRef.setID(theID);
466   ModelAPI_AttributeSelection::setID(theID);
467   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
468   if (myParent) {
469     // to be able to select as geometrical selection and then - split
470     myIsGeometricalSelection = true; // myParent->isGeometricalSelection();
471   } else {
472     myIsGeometricalSelection =
473       ModelAPI_Session::get()->validators()->isGeometricalSelection(aFeature->getKind(), id());
474   }
475 }
476
477 ResultPtr Model_AttributeSelection::context()
478 {
479   if (!ModelAPI_AttributeSelection::isInitialized() && !myTmpContext.get() && !myTmpSubShape.get())
480     return ResultPtr();
481
482   if (myTmpContext.get() || myTmpSubShape.get()) {
483     return std::dynamic_pointer_cast<ModelAPI_Result>(myTmpContext);
484   }
485
486   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
487   // for parts there could be same-data result, so take the last enabled
488   if (aResult.get()) {
489     if(aResult->groupName() == ModelAPI_ResultPart::group()) {
490       int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
491       for(int a = aSize - 1; a >= 0; a--) {
492         ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
493         if(aPart.get() && aPart->data() == aResult->data()) {
494           ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
495           FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
496           // check that this result is not this-feature result (it is forbidden to select itself)
497           if(anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
498             return aPartResult;
499           }
500         }
501       }
502     }
503   } else { // if feature - construction is selected, it has only one result, return this result
504     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
505     if (aFeature.get() && aFeature->results().size() == 1 &&
506         aFeature->firstResult()->groupName() == ModelAPI_ResultConstruction::group())
507       return aFeature->firstResult();
508   }
509   return aResult;
510 }
511
512 FeaturePtr Model_AttributeSelection::contextFeature() {
513   if (myTmpContext.get()) {
514     return std::dynamic_pointer_cast<ModelAPI_Feature>(myTmpContext);
515   }
516   return std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
517 }
518 ObjectPtr Model_AttributeSelection::contextObject() {
519   FeaturePtr aRes = contextFeature();
520   if (aRes.get())
521     return aRes;
522   return context();
523 }
524
525
526 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
527 {
528   ModelAPI_AttributeSelection::setObject(theObject);
529   myRef.setObject(theObject);
530 }
531
532 /// Sets the invalid flag if flag is false, or removes it if "true"
533 /// Returns theFlag
534 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
535   if (theFlag) {
536     theLab.ForgetAttribute(kINVALID_SELECTION);
537   } else {
538     TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
539   }
540   return theFlag;
541 }
542
543 void Model_AttributeSelection::split(
544   ResultPtr theContext, TopoDS_Shape theNewShape, TopAbs_ShapeEnum theType)
545 {
546   TopTools_ListOfShape aSubs;
547   for(TopoDS_Iterator anExplorer(theNewShape); anExplorer.More(); anExplorer.Next()) {
548     if (!anExplorer.Value().IsNull() &&
549       anExplorer.Value().ShapeType() == theType) {
550         aSubs.Append(anExplorer.Value());
551     } else { // invalid case; bad result shape, so, impossible to split easily
552       aSubs.Clear();
553       break;
554     }
555   }
556   if (aSubs.Extent() > 1) { // ok to split
557     TopTools_ListIteratorOfListOfShape aSub(aSubs);
558     GeomShapePtr aSubSh(new GeomAPI_Shape);
559     aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
560     setValue(theContext, aSubSh);
561     for(aSub.Next(); aSub.More(); aSub.Next()) {
562       GeomShapePtr aSubSh(new GeomAPI_Shape);
563       aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
564       myParent->append(theContext, aSubSh);
565     }
566   }
567 }
568
569 bool Model_AttributeSelection::update()
570 {
571   FeaturePtr aContextFeature = contextFeature();
572   if (aContextFeature.get()) {
573     owner()->data()->sendAttributeUpdated(this);  // send updated if "update" called in any way
574     return true;
575   }
576   TDF_Label aSelLab = selectionLabel();
577   ResultPtr aContext = context();
578   if (!aContext.get())
579     return setInvalidIfFalse(aSelLab, false);
580   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
581     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
582   }
583
584   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
585     std::shared_ptr<GeomAPI_Shape> aNoSelection;
586     bool aResult = selectPart(aContext, aNoSelection, true);
587     aResult = setInvalidIfFalse(aSelLab, aResult);
588     if (aResult) {
589       owner()->data()->sendAttributeUpdated(this);
590     }
591     return aResult;
592   }
593
594   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
595     // body: just a named shape, use topological selection mechanism
596     bool aResult = false;
597     TopoDS_Shape anOldShape;
598     Handle(TNaming_NamedShape) aNS;
599     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
600       anOldShape = aNS->Get();
601
602     TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
603     Selector_Selector aSelector(aSelLab, baseDocumentLab());
604     aResult = aSelector.restore(aContextShape);
605     bool aWasInvalid = aSelLab.IsAttribute(kINVALID_SELECTION);
606     setInvalidIfFalse(aSelLab, aResult);
607
608     TopoDS_Shape aNewShape;
609     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
610       aNewShape = aNS->Get();
611
612     if (anOldShape.IsNull() || aNewShape.IsNull() || !anOldShape.IsEqual(aNewShape) || aWasInvalid)
613     {
614       // shape type should not be changed: if shape becomes compound of such shapes, then split
615       if (myParent && !anOldShape.IsNull() && !aNewShape.IsNull() &&
616           anOldShape.ShapeType() != aNewShape.ShapeType() &&
617           aNewShape.ShapeType() == TopAbs_COMPOUND) {
618         split(aContext, aNewShape, anOldShape.ShapeType());
619       }
620       // for issue #3076 check that the new value belongs to the new context
621       if (!aNewShape.IsNull() && !aContextShape.IsNull() &&
622           (aNewShape.ShapeType() == TopAbs_VERTEX || aNewShape.ShapeType() == TopAbs_EDGE ||
623            aNewShape.ShapeType() == TopAbs_FACE)) {
624         TopExp_Explorer anExp(aContextShape, aNewShape.ShapeType());
625         for(; anExp.More(); anExp.Next()) {
626           if (anExp.Current().IsSame(aNewShape))
627             break;
628         }
629         aResult = setInvalidIfFalse(aSelLab, anExp.More());
630       }
631       owner()->data()->sendAttributeUpdated(this);  // send updated if shape is changed
632     }
633     return aResult;
634   }
635
636   if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
637     bool aResult = true;
638     std::shared_ptr<Model_ResultConstruction> aConstructionContext =
639       std::dynamic_pointer_cast<Model_ResultConstruction>(aContext);
640     if (!aConstructionContext->isInfinite()) {
641       TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
642       Selector_Selector aSelector(aSelLab, baseDocumentLab());
643       TopoDS_Shape anOldShape = aSelector.value();
644       aResult = aSelector.restore(aContextShape);
645       setInvalidIfFalse(aSelLab, aResult);
646       if (aResult && !anOldShape.IsEqual(aSelector.value()))
647         owner()->data()->sendAttributeUpdated(this);  // send updated if shape is changed
648     } else {
649       owner()->data()->sendAttributeUpdated(this);  // send updated if "update" called in any way
650     }
651     return aResult;
652   }
653   return setInvalidIfFalse(aSelLab, false); // unknown case
654 }
655
656 void Model_AttributeSelection::selectBody(
657   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
658 {
659   // perform the selection
660   TopoDS_Shape aContext;
661
662   ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
663   if (aBody) {
664     aContext = aBody->shape()->impl<TopoDS_Shape>();
665   } else {
666     ResultPtr aResult =
667       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
668     if (aResult) {
669       aContext = aResult->shape()->impl<TopoDS_Shape>();
670     } else {
671       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
672       return;
673     }
674   }
675
676   if (!aContext.IsNull()) {
677     TDF_Label aSelLab = selectionLabel();
678     TopoDS_Shape aNewSub = theSubShape->impl<TopoDS_Shape>();
679
680     bool aSelectorOk = true;
681     Selector_Selector aSelector(aSelLab, baseDocumentLab());
682     try {
683       aSelectorOk = aSelector.select(aContext, aNewSub, myIsGeometricalSelection);
684       if (aSelectorOk) {
685         aSelectorOk = aSelector.store(aContext);
686       }
687     } catch(...) {
688       aSelectorOk = false;
689     }
690     if (aSelectorOk) {
691       TopoDS_Shape aShape = aSelector.value();
692       aSelectorOk = !aShape.IsNull() && aShape.ShapeType() == aNewSub.ShapeType();
693     }
694     setInvalidIfFalse(aSelLab, aSelectorOk);
695   }
696 }
697
698 bool Model_AttributeSelection::selectPart(
699   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
700   const bool theUpdate)
701 {
702   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
703   if (!aPart.get() || !aPart->isActivated())
704     return true; // postponed naming
705   if (theUpdate) {
706     Handle(TDataStd_Integer) anIndex;
707     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
708       // by internal selection
709       if (anIndex->Get() > 0) {
710         // update the selection by index
711         return aPart->updateInPart(anIndex->Get());
712       } else {
713         return true; // nothing to do, referencing just by name
714       }
715     }
716     return true; // nothing to do, referencing just by name
717   }
718   // store the shape (in case part is not loaded it should be useful
719   TopoDS_Shape aShape;
720   std::string aName = theContext->data()->name();
721   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
722     aShape = theContext->shape()->impl<TopoDS_Shape>();
723   } else {
724     aShape = theSubShape->impl<TopoDS_Shape>();
725     int anIndex;
726     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
727     TDataStd_Integer::Set(selectionLabel(), anIndex);
728   }
729   TNaming_Builder aBuilder(selectionLabel());
730   aBuilder.Select(aShape, aShape);
731   // identify by name in the part
732   TDataStd_Name::Set(selectionLabel(), aName.c_str());
733   return !aName.empty();
734 }
735
736 TDF_Label Model_AttributeSelection::selectionLabel()
737 {
738   return myRef.myRef->Label().FindChild(1);
739 }
740
741 /// prefixes of the shape names with centers defined
742 static std::map<ModelAPI_AttributeSelection::CenterType, std::string> kCENTERS_PREFIX;
743
744 /// returns the map that contains all possible prefixes of the center-names
745 static std::map<ModelAPI_AttributeSelection::CenterType, std::string>& centersMap()
746 {
747   if (kCENTERS_PREFIX.empty()) { // fill map by initial values
748     kCENTERS_PREFIX[ModelAPI_AttributeSelection::CIRCLE_CENTER] = "__cc";
749     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS] = "__eff";
750     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_SECOND_FOCUS] = "__esf";
751   }
752   return kCENTERS_PREFIX;
753 }
754
755 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
756 {
757   std::string aName("");
758   if(!this->isInitialized())
759     return !theDefaultName.empty() ? theDefaultName : aName;
760
761   // not argument has not parametric name (filters)
762   if (!this->isArgument() || (myParent && !myParent->isArgument())) {
763     GeomShapePtr aShape = value();
764     if (!aShape.get() && context().get())
765       aShape = context()->shape();
766     std::string aName;
767     if (aShape.get()) {
768       aName = aShape->shapeTypeStr();
769       if (myParent) {
770         aName += std::string("_") +
771           TCollection_AsciiString(selectionLabel().Father().Tag()).ToCString();
772       }
773     }
774     return aName;
775   }
776
777   CenterType aCenterType = NOT_CENTER;
778   std::shared_ptr<GeomAPI_Shape> aSubSh = internalValue(aCenterType);
779   ResultPtr aCont = context();
780
781   if (!aCont.get() ||
782       (aCont->groupName() == ModelAPI_ResultConstruction::group() && contextFeature().get())) {
783     // selection of a full feature
784     FeaturePtr aFeatureCont = contextFeature();
785     if (aFeatureCont.get()) {
786       return kWHOLE_FEATURE + aFeatureCont->name();
787     }
788     // in case of selection of removed result
789     return "";
790   }
791
792   TDF_Label aSelLab = selectionLabel();
793   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // whole context, no value
794     return contextName(aCont);
795   }
796
797   // if it is in result of another part
798   if (aCont->groupName() == ModelAPI_ResultPart::group()) {
799     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aCont);
800     int anIndex;
801     std::string aResult = aSubSh.get() ?
802       aPart->data()->name() + "/" + aPart->nameInPart(aSubSh, anIndex) : aPart->data()->name();
803     if (aCenterType != NOT_CENTER)
804       aResult += centersMap()[aCenterType];
805     return aResult;
806   }
807
808   // whole infinitive construction
809   if (aCont->groupName() == ModelAPI_ResultConstruction::group()) {
810     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<Model_ResultConstruction>(aCont);
811     if (aConstr->isInfinite()) {
812       return contextName(aCont);
813     }
814   }
815
816   Selector_Selector aSelector(aSelLab, baseDocumentLab());
817   std::string aResult;
818   if (aCont->shape().get() && aSelector.restore(aCont->shape()->impl<TopoDS_Shape>()))
819     aResult = aSelector.name(this);
820   if (aCenterType != NOT_CENTER) {
821     aResult += centersMap()[aCenterType];
822   }
823   return aResult;
824 }
825
826 // returns the center type and modifies the shape name if this name is center-name
827 static ModelAPI_AttributeSelection::CenterType centerTypeByName(std::string& theShapeName)
828 {
829   std::map<ModelAPI_AttributeSelection::CenterType, std::string>::iterator aPrefixIter =
830     centersMap().begin();
831   for(; aPrefixIter != centersMap().end(); aPrefixIter++) {
832     std::size_t aFound = theShapeName.find(aPrefixIter->second);
833     if (aFound != std::string::npos &&
834         aFound == theShapeName.size() - aPrefixIter->second.size()) {
835       theShapeName = theShapeName.substr(0, aFound);
836       return aPrefixIter->first;
837     }
838   }
839   return ModelAPI_AttributeSelection::NOT_CENTER;
840 }
841
842 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
843 void Model_AttributeSelection::selectSubShape(
844   const std::string& theType, const std::string& theSubShapeName)
845 {
846   if(theSubShapeName.empty() || theType.empty()) return;
847
848   std::string aSubShapeName = theSubShapeName;
849   CenterType aCenterType = theType[0] == 'v' || theType[0] == 'V' ? // only for vertex-type
850     centerTypeByName(aSubShapeName) : NOT_CENTER;
851   std::string aType = aCenterType == NOT_CENTER ? theType : "EDGE"; // search for edge now
852   static const GeomShapePtr anEmptyShape;
853
854   // first iteration is selection by name without center prefix, second - in case of problem,
855   // try with initial name
856   for(int aUseCenter = 1; aUseCenter >= 0; aUseCenter--)  {
857     if (aUseCenter == 0 && aCenterType != NOT_CENTER) {
858       aSubShapeName = theSubShapeName;
859       aCenterType = NOT_CENTER;
860       aType = theType;
861     } else if (aUseCenter != 1) continue;
862     TopAbs_ShapeEnum aShapeType =  TopAbs_ShapeEnum(GeomAPI_Shape::shapeTypeByStr(aType));
863
864     std::shared_ptr<Model_Document> aDoc =
865       std::dynamic_pointer_cast<Model_Document>(owner()->document());
866     // check this is Part-name: 2 delimiters in the name
867     std::size_t aPartEnd = aSubShapeName.find('/');
868     if (aPartEnd != std::string::npos) {
869       std::string aPartName = aSubShapeName.substr(0, aPartEnd);
870       DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
871       if (aPartName == aRootDoc->kind()) {
872         aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
873         aSubShapeName = aSubShapeName.substr(aPartEnd + 1);
874       } else {
875         ObjectPtr aFound =
876           owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
877         if (aFound.get()) { // found such part, so asking it for the name
878           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
879           std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
880           if (aNameInPart.empty()) { // whole part
881             setValue(aPart, anEmptyShape);
882             return;
883           }
884           int anIndex;
885           std::shared_ptr<GeomAPI_Shape> aSelected =
886             aPart->shapeInPart(aNameInPart, aType, anIndex);
887           if (aSelected.get()) {
888             if (aCenterType != NOT_CENTER) {
889               if (!aSelected->isEdge())
890                 continue;
891               std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aSelected));
892               setValueCenter(aPart, aSelectedEdge, aCenterType);
893             } else
894               setValue(aPart, aSelected);
895             TDataStd_Integer::Set(selectionLabel(), anIndex);
896             return;
897           }
898         }
899       }
900     }
901
902     // check this is a whole feature context
903     if (aSubShapeName.size() > kWHOLE_FEATURE.size() &&
904       aSubShapeName.substr(0, kWHOLE_FEATURE.size()) == kWHOLE_FEATURE) {
905       std::string aFeatureName = aSubShapeName.substr(kWHOLE_FEATURE.size());
906       ObjectPtr anObj = aDoc->objectByName(ModelAPI_Feature::group(), aFeatureName);
907       if (anObj.get()) {
908         setValue(anObj, anEmptyShape);
909         return;
910       }
911     }
912
913     // the whole result selection check
914     if (aSubShapeName.find('/') == std::string::npos) {
915       ObjectPtr aRes = aDoc->objectByName(ModelAPI_ResultConstruction::group(), aSubShapeName);
916       if (!aRes.get()) {
917         aRes = aDoc->objectByName(ModelAPI_ResultBody::group(), aSubShapeName);
918         if (!aRes.get())
919           aRes = aDoc->objectByName(ModelAPI_ResultGroup::group(), aSubShapeName);
920       }
921       if (aRes.get()) {
922         setValue(aRes, anEmptyShape);
923         return;
924       }
925     }
926
927     Selector_Selector aSelector(selectionLabel(), baseDocumentLab());
928     myRestoreDocument = aDoc;
929     TDF_Label aContextLabel = aSelector.restoreByName(
930       aSubShapeName, aShapeType, this, myIsGeometricalSelection);
931     myRestoreDocument.reset();
932     if (!aContextLabel.IsNull()) {
933       ResultPtr aContext = aDoc->resultByLab(aContextLabel); // any label for document access
934       if (aContext.get() && aContext->shape().get()) {
935         TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
936         if (aSelector.solve(aContextShape)) {
937           TopoDS_Shape aSelectorShape = aSelector.value();
938           GeomShapePtr aShapeToBeSelected(new GeomAPI_Shape);
939           aShapeToBeSelected->setImpl<TopoDS_Shape>(new TopoDS_Shape(aSelectorShape));
940           // make the context result the latest existing
941           aContext = newestContext(aContext, aShapeToBeSelected);
942           if (myIsGeometricalSelection || aCenterType == NOT_CENTER) {
943             // store the currently generated name
944             selectionLabel().ForgetAllAttributes(true);
945             bool aToUnblock = false;
946             aToUnblock = !owner()->data()->blockSendAttributeUpdated(true);
947             myRef.setValue(aContext);
948             aSelector.store(aContextShape);
949             owner()->data()->sendAttributeUpdated(this);
950             if (aToUnblock)
951               owner()->data()->blockSendAttributeUpdated(false);
952             return;
953           } else { // re-select center of circle/arc by context and value
954             if (!aShapeToBeSelected->isEdge())
955               continue;
956             std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aShapeToBeSelected));
957             setValueCenter(aContext, aSelectedEdge, aCenterType);
958           }
959           return;
960         }
961       }
962     }
963   }
964   // invalid
965   TDF_Label aSelLab = selectionLabel();
966   setInvalidIfFalse(aSelLab, false);
967   reset();
968 }
969
970 void Model_AttributeSelection::selectSubShape(const std::string& theType,
971                                               const GeomPointPtr& thePoint)
972 {
973   if (theType.empty() || !thePoint)
974     return;
975
976   // list of parent features
977   FeaturePtr anOwner = ModelAPI_Feature::feature(owner());
978   std::set<FeaturePtr> aParents = ModelAPI_Tools::getParents(anOwner);
979
980   int aSelectionIndex = 0;
981   GeomAPI_Shape::ShapeType aType = GeomAPI_Shape::shapeTypeByStr(theType);
982   if (aType == GeomAPI_Shape::SHAPE) {
983     // possibly, the string consists of the type and the index,
984     // thus, try to separate them
985     size_t aUndersporePos = theType.find_first_of('_');
986     if (aUndersporePos != std::string::npos)
987       aType = GeomAPI_Shape::shapeTypeByStr(theType.substr(0, aUndersporePos));
988
989     if (aType != GeomAPI_Shape::SHAPE) {
990       for (std::string::const_iterator aChar = theType.begin() + aUndersporePos + 1;
991            aChar != theType.end(); ++aChar) {
992         if (std::isdigit(*aChar))
993           aSelectionIndex = aSelectionIndex * 10 + (*aChar - '0');
994         else {
995           aSelectionIndex = 1;
996           break;
997         }
998       }
999       aSelectionIndex -= 1;
1000     }
1001   }
1002
1003   std::list<ModelGeomAlgo_Shape::SubshapeOfResult> anAppropriate;
1004
1005   // collect features from PartSet and the current part
1006   SessionPtr aSession = ModelAPI_Session::get();
1007   std::list<FeaturePtr> aFeatures = aSession->moduleDocument()->allFeatures();
1008   if (aSession->moduleDocument() != owner()->document()) {
1009     std::list<FeaturePtr> aPartFeatures = owner()->document()->allFeatures();
1010     aFeatures.insert(aFeatures.end(), aPartFeatures.begin(), aPartFeatures.end());
1011   }
1012   // Process results of all features from the last to the first
1013   // to find appropriate sub-shape
1014   for (std::list<FeaturePtr>::const_reverse_iterator anIt = aFeatures.rbegin();
1015        anIt != aFeatures.rend(); ++anIt) {
1016     // selection cannot be linked to the parent features
1017     if (aParents.find(*anIt) != aParents.end())
1018       continue;
1019     // check the feature is a part of composite feature (like sketch elements),
1020     // then do not process it, it will be processed in scope of composite feature
1021     bool isSubOfComposite = false;
1022     const std::set<AttributePtr>& aRefs = (*anIt)->data()->refsToMe();
1023     for (std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
1024          aRefIt != aRefs.end() && !isSubOfComposite; ++aRefIt) {
1025       FeaturePtr aFeature = ModelAPI_Feature::feature((*aRefIt)->owner());
1026       CompositeFeaturePtr aCompFeature =
1027           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
1028       isSubOfComposite = aCompFeature && aCompFeature->isSub(*anIt);
1029     }
1030     if (isSubOfComposite)
1031       continue;
1032
1033     // process results of the current feature to find appropriate sub-shape
1034     if (ModelGeomAlgo_Shape::findSubshapeByPoint(*anIt, thePoint, aType, anAppropriate)) {
1035       std::list<ModelGeomAlgo_Shape::SubshapeOfResult>::iterator anApIt = anAppropriate.begin();
1036       for (; aSelectionIndex > 0 && anApIt != anAppropriate.end(); --aSelectionIndex)
1037         ++anApIt; // skip this shape, because one of the previous is selected
1038
1039       if (anApIt != anAppropriate.end()) {
1040         if (anApIt->myCenterType == (int)ModelAPI_AttributeSelection::NOT_CENTER)
1041           setValue(anApIt->myResult, anApIt->mySubshape);
1042         else
1043           setValueCenter(anApIt->myResult, anApIt->mySubshape->edge(),
1044                          (ModelAPI_AttributeSelection::CenterType)anApIt->myCenterType);
1045         return;
1046       }
1047     }
1048   }
1049
1050   TDF_Label aSelLab = selectionLabel();
1051   setInvalidIfFalse(aSelLab, false);
1052   reset();
1053 }
1054
1055 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1056   const std::string& theContextName, const int theIndex)
1057 {
1058   // selection of context by name
1059   selectSubShape(theType, theContextName);
1060   ResultPtr aContext = context();
1061   if (aContext.get()) {
1062     GeomShapePtr aContShape = aContext->shape();
1063     if (aContShape.get()) {
1064       GeomAlgoAPI_NExplode aNExp(aContShape, GeomAPI_Shape::shapeTypeByStr(theType));
1065       GeomShapePtr aValue = aNExp.shape(theIndex);
1066       if (aValue.get())
1067         setValue(aContext, aValue);
1068     }
1069   }
1070 }
1071
1072 void Model_AttributeSelection::setId(int theID)
1073 {
1074   std::shared_ptr<GeomAPI_Shape> aSelection;
1075
1076   ResultPtr aContextRes = context();
1077   // support for compsolids:
1078   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1079     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1080   }
1081   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1082
1083   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1084   // searching for the latest main shape
1085   if (theID > 0 && aContext && !aContext->isNull())
1086   {
1087     std::shared_ptr<Model_Document> aDoc =
1088       std::dynamic_pointer_cast<Model_Document>(aContextRes->document());
1089     if (aDoc.get()) {
1090       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1091       if (!aNS.IsNull()) {
1092         aMainShape = TNaming_Tool::CurrentShape(aNS);
1093       }
1094     }
1095
1096     TopTools_IndexedMapOfShape aSubShapesMap;
1097     TopExp::MapShapes(aMainShape, aSubShapesMap);
1098     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1099
1100     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1101     aResult->setImpl(new TopoDS_Shape(aSelShape));
1102
1103     aSelection = aResult;
1104   }
1105
1106   setValue(aContextRes, aSelection);
1107 }
1108
1109 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1110 {
1111   std::string aResult;
1112   if (owner()->document() != theContext->document()) {
1113     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1114       aResult = theContext->document()->kind() + "/";
1115     } else {
1116       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1117         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1118       if (aDocRes.get()) {
1119         aResult = aDocRes->data()->name() + "/";
1120       }
1121     }
1122   }
1123   aResult += theContext->data()->name();
1124   return aResult;
1125 }
1126
1127 void Model_AttributeSelection::computeValues(
1128   ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
1129   TopTools_ListOfShape& theShapes)
1130 {
1131   bool aWasWholeContext = theValShape.IsNull();
1132   if (aWasWholeContext) {
1133     theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
1134   }
1135   TopAbs_ShapeEnum aValType = theValShape.ShapeType();
1136   TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
1137   // if a new value is unchanged in the new context, do nothing: value is correct
1138   TopExp_Explorer aSubExp(aNewContShape, aValType);
1139   for(; aSubExp.More(); aSubExp.Next()) {
1140     if (aSubExp.Current().IsSame(theValShape)) {
1141       theShapes.Append(theValShape);
1142       return;
1143     }
1144   }
1145   // if new context becomes compsolid, the resulting sub may be in sub-solids
1146   std::list<ResultPtr> aNewToIterate;
1147   aNewToIterate.push_back(theNewContext);
1148   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theNewContext);
1149   if (aComp.get()) {
1150     std::list<ResultPtr> allNewContextSubs;
1151     ModelAPI_Tools::allSubs(aComp, allNewContextSubs);
1152     std::list<ResultPtr>::iterator aSub = allNewContextSubs.begin();
1153     for(; aSub != allNewContextSubs.end(); aSub++) {
1154       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aSub);
1155       if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1156         aNewToIterate.push_back(aBody);
1157     }
1158   }
1159
1160   // first iteration: searching for the whole shape appearance (like face of the box)
1161   // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
1162   int aToFindPart = 0;
1163   TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
1164   TopTools_MapOfShape anOlds; // to know how many olds produced new containers
1165   for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
1166     std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
1167     for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
1168       std::shared_ptr<Model_Data> aNewData =
1169         std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
1170       TDF_Label aNewLab = aNewData->shapeLab();
1171       // searching for produced sub-shape fully on some label
1172       TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID());
1173       for(; aNSIter.More(); aNSIter.Next()) {
1174         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1175         for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
1176           if (aToFindPart == 0) { // search shape is fully inside
1177             if (aPairIter.OldShape().IsSame(theValShape)) {
1178               if (aPairIter.NewShape().IsNull()) {// value was removed
1179                 theShapes.Clear();
1180                 return;
1181               }
1182               // don't add edges generated from faces
1183               if (aPairIter.NewShape().ShapeType() <= aValType)
1184                 theShapes.Append(aPairIter.NewShape());
1185             }
1186           } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
1187             TopExp_Explorer anExp(aPairIter.OldShape(), aValType);
1188             for(; anExp.More(); anExp.Next()) {
1189               if (anExp.Current().IsSame(theValShape)) { // found a new container
1190                 if (aPairIter.NewShape().IsNull()) // skip removed high-level shape
1191                   continue;
1192                 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
1193                 anOlds.Add(aPairIter.OldShape());
1194                 break;
1195               }
1196             }
1197           }
1198         }
1199       }
1200     }
1201   }
1202   if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
1203     // also iterate the whole old shape to find not-modified shapes that contain this old
1204     TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
1205     NCollection_Map<TopAbs_ShapeEnum> aNewTypes; // types of shapes to iterate
1206     TopTools_DataMapOfShapeShape::Iterator aNewTypeIter(aNewToOld);
1207     for(; aNewTypeIter.More(); aNewTypeIter.Next()) {
1208       if (aNewTypeIter.Key().ShapeType() != aValType)
1209         aNewTypes.Add(aNewTypeIter.Key().ShapeType());
1210     }
1211     NCollection_Map<TopAbs_ShapeEnum>::Iterator aTypeIter(aNewTypes);
1212     for(; aTypeIter.More(); aTypeIter.Next()) {
1213       for(TopExp_Explorer anExp(anOldContShape, aTypeIter.Value()); anExp.More(); anExp.Next()) {
1214         TopoDS_Shape anOld = anExp.Current();
1215         if (aNewToOld.IsBound(anOld) || anOlds.Contains(anOld)) // this was modified
1216           continue;
1217         TopExp_Explorer aValExp(anOld, aValType);
1218         for(; aValExp.More(); aValExp.Next()) {
1219           const TopoDS_Shape& anUnchanged = aValExp.Current();
1220           if (anUnchanged.IsSame(theValShape)) {
1221             aNewToOld.Bind(anOld, anOld);
1222             anOlds.Add(anOld);
1223             break;
1224           }
1225         }
1226       }
1227     }
1228
1229     // map of sub-shapes -> number of occurrences of these shapes in containers
1230     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
1231     TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
1232     for(; aContIter.More(); aContIter.Next()) {
1233       TopExp_Explorer aSubExp(aContIter.Key(), aValType);
1234       for(; aSubExp.More(); aSubExp.Next()) {
1235         if (!aSubs.IsBound(aSubExp.Current())) {
1236           aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
1237         }
1238         // store old to know how many olds produced this shape
1239         aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
1240       }
1241     }
1242     // if sub is appeared same times in containers as the number of old shapes that contain it
1243     int aCountInOld = anOlds.Size();
1244     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
1245       aSubsIter(aSubs);
1246     for(; aSubsIter.More(); aSubsIter.Next()) {
1247       if (aSubsIter.Value().Size() == aCountInOld) {
1248         TopoDS_Shape anOld = aSubsIter.Key();
1249         // check this exists in the new shape
1250         TopExp_Explorer aNew(aNewContShape, anOld.ShapeType());
1251         for (; aNew.More(); aNew.Next()) {
1252           if (aNew.Current().IsSame(anOld))
1253             break;
1254         }
1255         if (aNew.More())
1256           theShapes.Append(anOld);
1257       }
1258     }
1259   }
1260   if (theShapes.IsEmpty()) { // nothing was changed
1261     if (aWasWholeContext)
1262       theShapes.Append(TopoDS_Shape());
1263     else { // if theValShape exists in new context, add it without changes, otherwise - nothing
1264       for (TopExp_Explorer aNew(aNewContShape, aValType); aNew.More(); aNew.Next()){
1265         if (aNew.Current().IsSame(theValShape)) {
1266           theShapes.Append(theValShape);
1267           break;
1268         }
1269       }
1270     }
1271   } else if (theShapes.Size() > 1) {
1272     // check it is possible to remove extra sub-shapes:
1273     // keep only shapes with the same number of containers if possible
1274     TopAbs_ShapeEnum anAncType = TopAbs_FACE;
1275     if (aValType == TopAbs_VERTEX)
1276       anAncType = TopAbs_EDGE;
1277     TopoDS_Shape anOldContext = theOldContext->shape()->impl<TopoDS_Shape>();
1278     TopTools_IndexedDataMapOfShapeListOfShape anOldMap;
1279     TopExp::MapShapesAndUniqueAncestors(anOldContext, aValType,  anAncType, anOldMap);
1280     if (anOldMap.Contains(theValShape)) {
1281       int aNumInOld = anOldMap.FindFromKey(theValShape).Extent();
1282       TopTools_IndexedDataMapOfShapeListOfShape aNewMap;
1283       TopExp::MapShapesAndUniqueAncestors(aNewContShape, aValType,  anAncType, aNewMap);
1284       TopTools_ListOfShape aNewResults;
1285       for(TopTools_ListOfShape::Iterator aNewSubs(theShapes); aNewSubs.More(); aNewSubs.Next()) {
1286         TopoDS_Shape aCand = aNewSubs.Value();
1287         if (aNewMap.Contains(aCand) && aNewMap.FindFromKey(aCand).Extent() == aNumInOld)
1288           aNewResults.Append(aCand);
1289       }
1290       if (!aNewResults.IsEmpty() && aNewResults.Size() < theShapes.Size())
1291         theShapes = aNewResults;
1292     }
1293   }
1294 }
1295
1296
1297 void Model_AttributeSelection::concealedFeature(
1298   const FeaturePtr theFeature, const FeaturePtr theStop, std::list<FeaturePtr>& theConcealers,
1299   const ResultPtr theResultOfFeature)
1300 {
1301   std::set<FeaturePtr> alreadyProcessed;
1302   alreadyProcessed.insert(theFeature);
1303   if (theStop.get())
1304     alreadyProcessed.insert(theStop);
1305   /// iterate all results to find the concealment-attribute
1306   std::list<ResultPtr> aRootRes;
1307   if (theResultOfFeature.get()) {
1308     ResultPtr aRoot = ModelAPI_Tools::bodyOwner(theResultOfFeature, true);
1309     aRootRes.push_back(aRoot ? aRoot : theResultOfFeature);
1310   } else { // all results of a feature
1311    aRootRes = theFeature->results();
1312   }
1313   std::list<ResultPtr>::const_iterator aRootIter = aRootRes.cbegin();
1314   for(; aRootIter != aRootRes.cend(); aRootIter++) {
1315     std::list<ResultPtr> allRes;
1316     allRes.push_back(*aRootIter);
1317     ResultBodyPtr aRootBody = ModelAPI_Tools::bodyOwner(*aRootIter, true);
1318     if (!aRootBody.get())
1319       aRootBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRootIter);
1320     if (aRootBody.get()) {
1321       ModelAPI_Tools::allSubs(aRootBody, allRes);
1322     }
1323     for(std::list<ResultPtr>::iterator aRIter = allRes.begin(); aRIter != allRes.end(); aRIter++) {
1324       const std::set<AttributePtr>& aRefs = (*aRIter)->data()->refsToMe();
1325       std::set<AttributePtr>::const_iterator aRef = aRefs.cbegin();
1326       for (; aRef != aRefs.cend(); aRef++) {
1327         if (!aRef->get() || !(*aRef)->owner().get())
1328           continue;
1329         // concealed attribute only
1330         FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1331         if (alreadyProcessed.find(aRefFeat) != alreadyProcessed.end()) // optimization
1332           continue;
1333         alreadyProcessed.insert(aRefFeat);
1334         if (ModelAPI_Session::get()->validators()->isConcealed(aRefFeat->getKind(), (*aRef)->id()))
1335         {
1336           // for extrusion cut in python script the nested sketch reference may be concealed before
1337           // it is nested, so, check this composite feature is valid
1338           static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
1339           // need to be validated to update the "Apply" state if not previewed
1340           if (aFactory->validate(aRefFeat)) {
1341             if (theStop.get()) {
1342               std::shared_ptr<Model_Document> aDoc =
1343                 std::dynamic_pointer_cast<Model_Document>(theStop->document());
1344               if (!aDoc->isLaterByDep(theStop, aRefFeat)) // skip feature later than stop
1345                 continue;
1346             }
1347             theConcealers.push_back(aRefFeat);
1348           }
1349         }
1350       }
1351     }
1352   }
1353 }
1354
1355 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
1356   const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
1357   TDF_Label theAccessLabel,
1358   std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
1359 {
1360   std::set<ResultPtr> aResults; // to avoid duplicates, new context, null if deleted
1361   // iterate context and shape, but also if it is sub-shape of main shape, check also it
1362   TopTools_ListOfShape aContextList;
1363   aContextList.Append(theContShape);
1364   if (theContext.get()) {
1365     ResultPtr aComposite = ModelAPI_Tools::bodyOwner(theContext);
1366     if (aComposite.get() && aComposite->shape().get() && !aComposite->shape()->isNull())
1367       aContextList.Append(aComposite->shape()->impl<TopoDS_Shape>());
1368   }
1369   for(TopTools_ListOfShape::Iterator aContIter(aContextList); aContIter.More(); aContIter.Next()) {
1370     TNaming_SameShapeIterator aModifIter(aContIter.ChangeValue(), theAccessLabel);
1371     for(; aModifIter.More(); aModifIter.Next()) {
1372       TDF_Label anObjLab = aModifIter.Label().Father();
1373       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1374         (theDoc->objects()->object(anObjLab));
1375       if (!aModifierObj.get()) {
1376         // #2241: shape may be sub-element of new object, not main (shell created from faces)
1377         if (!anObjLab.IsRoot())
1378           aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1379           (theDoc->objects()->object(anObjLab.Father()));
1380         if (!aModifierObj.get())
1381           continue;
1382       }
1383       FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
1384       if (!aModifierFeat.get())
1385         continue;
1386       FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1387       if (aModifierFeat == aThisFeature || !theDoc->isLaterByDep(aThisFeature, aModifierFeat))
1388         continue; // the modifier feature is later than this, so, should not be used
1389       FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
1390       if (aCurrentModifierFeat == aModifierFeat ||
1391         !theDoc->isLaterByDep(aModifierFeat, aCurrentModifierFeat))
1392         continue; // the current modifier is later than the found, so, useless
1393       Handle(TNaming_NamedShape) aNewNS;
1394       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1395       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1396         aResults.insert(aModifierObj);
1397       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
1398         aResults.insert(ResultPtr());
1399       } else { // not-processed modification => don't support it
1400         continue;
1401       }
1402     }
1403   }
1404   // if there exist context composite and sub-result(s), leave only sub(s)
1405   for(std::set<ResultPtr>::iterator aResIter = aResults.begin(); aResIter != aResults.end();) {
1406     ResultPtr aParent = ModelAPI_Tools::bodyOwner(*aResIter);
1407     for(; aParent.get(); aParent = ModelAPI_Tools::bodyOwner(aParent))
1408       if (aResults.count(aParent))
1409         break;
1410     if (aParent.get()) { // erase from set, so, restart iteration
1411       aResults.erase(aParent);
1412       aResIter = aResults.begin();
1413     } else aResIter++;
1414   }
1415
1416   if (aResults.empty()) {
1417     // check the context become concealed by operation which is earlier than this selection
1418     FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1419     FeaturePtr aContextOwner = theDoc->feature(theContext);
1420     std::list<FeaturePtr> aConcealers;
1421     concealedFeature(aContextOwner, aThisFeature, aConcealers, theContext);
1422     std::list<FeaturePtr>::iterator aConcealer = aConcealers.begin();
1423     for(; aConcealer != aConcealers.end(); aConcealer++) {
1424       std::list<ResultPtr> aRefResults;
1425       ModelAPI_Tools::allResults(*aConcealer, aRefResults);
1426       std::list<ResultPtr>::iterator aRefIter = aRefResults.begin();
1427       for(; aRefIter != aRefResults.end(); aRefIter++) {
1428         ResultBodyPtr aRefBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRefIter);
1429         if (!aRefBody.get() || aRefBody->numberOfSubs() != 0) // iterate only leafs
1430           continue;
1431         GeomShapePtr aRefShape = aRefBody->shape();
1432         if (!aRefShape.get() || aRefShape->isNull())
1433           continue;
1434         if (aRefShape->impl<TopoDS_Shape>().IsSame(theContShape)) {
1435           // add the new context result with the same shape
1436           aResults.insert(aRefBody);
1437         }
1438       }
1439       if (aResults.empty())
1440         return true; // feature conceals result, return true, so the context will be removed
1441     }
1442     if (aResults.empty())
1443       return false; // no modifications found, must stay the same
1444   }
1445   // iterate all results to find further modifications
1446   std::set<ResultPtr>::iterator aResIter = aResults.begin();
1447   for(; aResIter != aResults.end(); aResIter++) {
1448     if (aResIter->get() != NULL) {
1449       // compute new values by two contexts: the old and the new
1450       TopTools_ListOfShape aValShapes;
1451       computeValues(theContext, *aResIter, theValShape, aValShapes);
1452
1453       TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
1454       for(; aNewVal.More(); aNewVal.Next()) {
1455         std::list<ResultPtr> aNewRes;
1456         TopTools_ListOfShape aNewUpdatedVal;
1457         TopoDS_Shape aNewValSh = aNewVal.Value();
1458         TopoDS_Shape aNewContShape = (*aResIter)->shape()->impl<TopoDS_Shape>();
1459         if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
1460           aNewValSh.Nullify();
1461         if (searchNewContext(theDoc, aNewContShape, *aResIter, aNewValSh,
1462                              theAccessLabel, aNewRes, aNewUpdatedVal))
1463         {
1464           // append new results instead of the current ones
1465           std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1466           TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1467           for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1468             theResults.push_back(*aNewIter);
1469             theValShapes.Append(aNewUpdVal.Value());
1470           }
1471         } else { // the current result is good
1472           theResults.push_back(*aResIter);
1473           theValShapes.Append(aNewValSh);
1474         }
1475       }
1476     }
1477   }
1478   return true; // theResults must be empty: everything is deleted
1479 }
1480
1481 void Model_AttributeSelection::updateInHistory(bool& theRemove)
1482 {
1483   static std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1484
1485   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1486   if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
1487       aContext->groupName() != ModelAPI_ResultPart::group())) {
1488     // but check the case the whole results are allowed: whole features may be selected
1489     if (myParent && myParent->isWholeResultAllowed()) {
1490       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
1491       if (aFeature.get()) {
1492         FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1493         std::list<FeaturePtr> aConcealers;
1494         concealedFeature(aFeature, aThisFeature, aConcealers, ResultPtr());
1495         if (aConcealers.empty())
1496           return;
1497         bool aChanged = false;
1498         std::list<FeaturePtr>::iterator aConcealer = aConcealers.begin();
1499         for(; aConcealer != aConcealers.end(); aConcealer++)
1500           if (!myParent->isInList(*aConcealer, anEmptyShape)) {// avoid addition of duplicates
1501             setValue(*aConcealer, anEmptyShape);
1502             aChanged = true;
1503           }
1504         if (aConcealer == aConcealers.end()) {
1505           if (!aChanged) // remove this
1506             theRemove = true;
1507         } else { // append new
1508           for(aConcealer++; aConcealer != aConcealers.end(); aConcealer++)
1509             if (!myParent->isInList(*aConcealer, anEmptyShape)) // avoid addition of duplicates
1510               myParent->append(*aConcealer, anEmptyShape);
1511         }
1512         if (aChanged) // searching for the further modifications
1513           updateInHistory(theRemove);
1514       }
1515     }
1516     return;// only bodies and parts may be modified later in the history, skip otherwise
1517   }
1518
1519   std::shared_ptr<Model_Document> aDoc =
1520     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1521   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1522   if (!aContData.get() || !aContData->isValid())
1523     return;
1524   TDF_Label aContLab = aContData->shapeLab(); // named shape where the selected context is located
1525
1526   // checking this may be just a reference to another context (same shape), so use that label
1527   Handle(TNaming_NamedShape) aContNS;
1528   Handle(TDF_Reference) aRefAttr;
1529   while(!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS) &&
1530         aContLab.FindAttribute(TDF_Reference::GetID(), aRefAttr))
1531     aContLab = aRefAttr->Get();
1532
1533   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
1534     bool aFoundNewContext = true;
1535     ResultPtr aNewContext = aContext;
1536     while(aFoundNewContext) {
1537       aFoundNewContext = false;
1538       // parts have no shape in result, so, trace references using the Part info
1539       if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
1540         ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
1541         if (aPartContext.get()) { // searching for the up to date references to the referenced cont
1542           const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
1543           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1544           for(; aRef != aRefs.end(); aRef++) {
1545             // to avoid detection of part changes by local selection only
1546             AttributeSelectionPtr aSel =
1547               std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1548             if (aSel.get() && aSel->value().get() &&
1549                 !aSel->value()->isSame(aSel->context()->shape()))
1550               continue;
1551
1552             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1553
1554             if (aRefFeat.get() && aRefFeat != owner() && aRefFeat->firstResult().get()) {
1555               // check the reference is concealed: #2900
1556               ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
1557               if (!aValidators->isConcealed(aRefFeat->getKind(), (*aRef)->id()))
1558                 continue;
1559               FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1560               if (!aDoc->isLaterByDep(aRefFeat, aThisFeature)) { // found better feature
1561                 aFoundNewContext = true;
1562                 aNewContext = aRefFeat->firstResult();
1563               }
1564             }
1565           }
1566         }
1567       }
1568     }
1569     if (aNewContext != aContext) {
1570       setValue(aNewContext, value());
1571     }
1572     return;
1573   }
1574   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1575   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1576   // iterate the context shape modifications in order to find a feature that is upper in history
1577   // that this one and is really modifies the referenced result to refer to it
1578   ResultPtr aModifierResFound;
1579   TNaming_Iterator aPairIter(aContNS);
1580   if (!aPairIter.More())
1581     return;
1582   TopoDS_Shape aNewCShape = aPairIter.NewShape();
1583   bool anIterate = true;
1584   // trying to update also the sub-shape selected
1585   GeomShapePtr aSubShape = value();
1586   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1587     aSubShape.reset();
1588   TopoDS_Shape aValShape;
1589   if (aSubShape.get()) {
1590     aValShape = aSubShape->impl<TopoDS_Shape>();
1591   }
1592
1593   std::list<ResultPtr> aNewContexts;
1594   TopTools_ListOfShape aValShapes;
1595   if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1596   {
1597     std::set<ResultPtr> allContexts, aSkippedContext;
1598     std::list<ResultPtr>::iterator aNewContext = aNewContexts.begin();
1599     for(; aNewContext != aNewContexts.end(); aNewContext++)
1600       allContexts.insert(*aNewContext);
1601
1602     // if there exist context composite and sub-result(s), leave only sub(s)
1603     std::set<ResultPtr>::iterator aResIter = allContexts.begin();
1604     for(; aResIter != allContexts.end(); aResIter++) {
1605       ResultPtr aParent = ModelAPI_Tools::bodyOwner(*aResIter);
1606       for(; aParent.get(); aParent = ModelAPI_Tools::bodyOwner(aParent))
1607         if (allContexts.count(aParent))
1608           aSkippedContext.insert(aParent);
1609     }
1610
1611     GeomAPI_Shape::ShapeType aListShapeType = GeomAPI_Shape::SHAPE;
1612     if (myParent) {
1613       if (myParent->selectionType() == "VERTEX" || myParent->selectionType() == "Vertices")
1614         aListShapeType = GeomAPI_Shape::VERTEX;
1615       else if (myParent->selectionType() == "EDGE" || myParent->selectionType() == "Edges")
1616         aListShapeType = GeomAPI_Shape::EDGE;
1617       else if (myParent->selectionType() == "FACE" || myParent->selectionType() == "Faces")
1618         aListShapeType = GeomAPI_Shape::FACE;
1619     }
1620
1621     // issue #3031: skip topology if there is more convenient shape type presents in the
1622     // same context as a result of this
1623     bool isWholeResult = myParent && myParent->isWholeResultAllowed() && !aSubShape.get();
1624     GeomAPI_Shape::ShapeType allowedType = GeomAPI_Shape::SHAPE;
1625     if (isWholeResult) {
1626       std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1627       TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1628       for(; aNewCont != aNewContexts.end(); aNewCont++, aNewValues.Next()) {
1629         if (aNewValues.Value().IsNull()) { // only for the whole context
1630           GeomAPI_Shape::ShapeType aShapeType = (*aNewCont)->shape()->shapeType();
1631           if (allowedType == GeomAPI_Shape::SHAPE) { // just set this one
1632             allowedType = aShapeType;
1633           } else {
1634             GeomAPI_Shape::ShapeType anAllowed = allowedType;
1635             if (anAllowed != aShapeType) { // select the best, nearest to the origin
1636               GeomAPI_Shape::ShapeType anOldShapeType = aContext->shape()->shapeType();
1637               GeomAPI_Shape::ShapeType aDeltaAllowed =
1638                 (GeomAPI_Shape::ShapeType)(anOldShapeType - anAllowed);
1639               if (aDeltaAllowed < 0)
1640                 aDeltaAllowed = (GeomAPI_Shape::ShapeType)(-aDeltaAllowed);
1641               GeomAPI_Shape::ShapeType aDeltaThis =
1642                 (GeomAPI_Shape::ShapeType)(anOldShapeType - aShapeType);
1643               if (aDeltaThis < 0)
1644                 aDeltaThis = (GeomAPI_Shape::ShapeType)(-aDeltaThis);
1645               if (aDeltaThis == aDeltaAllowed) { // equal distance to context, select complicated
1646                 if (anOldShapeType < anAllowed)
1647                   allowedType = aShapeType;
1648               } else if (aDeltaAllowed > aDeltaThis) { // this wins
1649                 allowedType = aShapeType;
1650               }
1651             }
1652           }
1653         }
1654       }
1655     }
1656
1657     std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1658     TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1659     bool aFirst = true; // first is set to this, next are appended to parent
1660     for(; aNewCont != aNewContexts.end(); aNewCont++, aNewValues.Next()) {
1661       if (aSkippedContext.count(*aNewCont))
1662         continue;
1663
1664       if (isWholeResult && aNewValues.Value().IsNull())
1665         if (allowedType != GeomAPI_Shape::SHAPE &&
1666             (*aNewCont)->shape()->shapeType() != allowedType)
1667           continue; // there is better result exists with the better shape type (issue #3031)
1668
1669       GeomShapePtr aValueShape;
1670       if (!aNewValues.Value().IsNull()) {
1671         aValueShape = std::make_shared<GeomAPI_Shape>();
1672         aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1673       }
1674       // Check that list has the same type of shape selection before adding.
1675       GeomAPI_Shape::ShapeType aShapeShapeType = GeomAPI_Shape::SHAPE;
1676       if (aValueShape.get()) {
1677         aShapeShapeType = aValueShape->shapeType();
1678       } else {
1679         aShapeShapeType = (*aNewCont)->shape()->shapeType();
1680       }
1681       if (aListShapeType != GeomAPI_Shape::SHAPE && aListShapeType != aShapeShapeType) {
1682         // exception is for whole results selected
1683         if (!isWholeResult) {
1684           continue;
1685         }
1686       }
1687
1688       ResultPtr aNewContext = *aNewCont;
1689       if (aValueShape.get()) { // #2892 if context is higher level result, search this sub in lower
1690         ResultBodyPtr aBodyContext = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aNewContext);
1691         if (aBodyContext.get() && aBodyContext->numberOfSubs() != 0) {
1692           std::list<ResultPtr> aLower;
1693           ModelAPI_Tools::allSubs(aBodyContext, aLower, true);
1694           for(std::list<ResultPtr>::iterator aL = aLower.begin(); aL != aLower.end(); aL++) {
1695             GeomShapePtr aLShape = (*aL)->shape();
1696             if (aLShape.get() && !aLShape->isNull()) {
1697               if (aLShape->isSubShape(aValueShape, false)) {
1698                 aNewContext = *aL;
1699                 break;
1700               }
1701             }
1702           }
1703         }
1704       }
1705
1706       if (aFirst) {
1707         if (!myParent || !myParent->isInList(aNewContext, aValueShape)) { // avoid duplicates
1708           setValue(aNewContext, aValueShape);
1709           aFirst = false;
1710         }
1711       } else if (myParent) {
1712         if (!myParent->isInList(aNewContext, aValueShape)) // avoid addition of duplicates
1713           myParent->append(aNewContext, aValueShape);
1714       }
1715     }
1716     if (aFirst) { // nothing was added, all results were deleted
1717       if (myParent) {
1718         theRemove = true;
1719       } else {
1720         static ResultPtr anEmptyContext;
1721         setValue(anEmptyContext, anEmptyShape); // nullify the selection
1722         return;
1723       }
1724     }
1725   }
1726 }
1727
1728 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1729 {
1730   myParent = theParent;
1731 }
1732
1733 std::string Model_AttributeSelection::contextName(const TDF_Label theSelectionLab)
1734 {
1735   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1736     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1737   FeaturePtr aFeatureOwner = aDoc->featureByLab(theSelectionLab);
1738   bool aBaseDocumnetUsed = false;
1739   if (!aFeatureOwner.get()) { // use module document
1740     aDoc = std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument());
1741     aFeatureOwner = aDoc->featureByLab(theSelectionLab);
1742     aBaseDocumnetUsed = true;
1743   }
1744   if (aFeatureOwner.get()) {
1745     // if it is sub-element of the sketch, the context name is the name of the sketch
1746     // searching also for result - real context
1747     ResultPtr aResult;
1748     FeaturePtr aComposite = ModelAPI_Tools::compositeOwner(aFeatureOwner);
1749     if (aComposite.get() && aComposite->results().size() == 1 &&
1750         aComposite->firstResult()->groupName() == ModelAPI_ResultConstruction::group()) {
1751       aFeatureOwner = aComposite;
1752       aResult = aFeatureOwner->firstResult();
1753     } else {
1754       aResult = aDoc->resultByLab(theSelectionLab);
1755     }
1756     if (aResult.get()) {
1757       // this is to avoid duplicated names of results problem
1758       std::string aContextName = aResult->data()->name();
1759       // myLab corresponds to the current time
1760       TDF_Label aCurrentLab = selectionLabel();
1761       while(aCurrentLab.Depth() > 3)
1762         aCurrentLab = aCurrentLab.Father();
1763
1764       int aNumInHistoryNames =
1765         aDoc->numberOfNameInHistory(aResult, aCurrentLab);
1766       while(aNumInHistoryNames > 1) { // add "_" before name the needed number of times
1767         aContextName = "_" + aContextName;
1768         aNumInHistoryNames--;
1769       }
1770       if (aBaseDocumnetUsed)
1771         aContextName = aDoc->kind() + "/" + aContextName;
1772       return aContextName;
1773     }
1774   }
1775   return ""; // invalid case
1776 }
1777
1778 /// This method restores by the context and value name the context label and
1779 /// sub-label where the value is. Returns true if it is valid.
1780 bool Model_AttributeSelection::restoreContext(std::string theName,
1781   TDF_Label& theContext, TDF_Label& theValue)
1782 {
1783   static const GeomShapePtr anEmptyShape; // to store context only
1784   std::string aName = theName;
1785   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1786     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1787
1788   // remove the sub-value part if exists
1789   std::string aSubShapeName = aName;
1790   std::string::size_type n = aName.find('/');
1791   if (n != std::string::npos) {
1792     aName = aName.substr(0, n);
1793   }
1794
1795   if (aName.empty()) return false;
1796   bool anUniqueContext = false;
1797   ResultPtr aCont = aDoc->findByName(aName, aSubShapeName, anUniqueContext);
1798   if (!aCont.get() || !aCont->shape().get() || aCont->shape()->isNull()) {
1799     // name in PartSet?
1800     aDoc = std::dynamic_pointer_cast<Model_Document>(
1801       ModelAPI_Session::get()->moduleDocument());
1802     if (theName.find(aDoc->kind()) == 0) { // remove the document identifier from name if exists
1803       aSubShapeName = theName.substr(aDoc->kind().size() + 1);
1804       aName = aSubShapeName;
1805       std::string::size_type n = aName.find('/');
1806       if (n != std::string::npos) {
1807         aName = aName.substr(0, n);
1808       }
1809     }
1810     aCont = aDoc->findByName(aName, aSubShapeName, anUniqueContext);
1811     if (!aCont.get() || !aCont->shape().get() || aCont->shape()->isNull())
1812       return false;
1813   }
1814
1815   // searching the sub-shape
1816   static const ResultPtr anEmpty;
1817   theValue = aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
1818
1819   // sketch sub-component shape and name is located in separated feature label, try the sub-name
1820   if (theValue.IsNull() && aCont->groupName() == ModelAPI_ResultConstruction::group()) {
1821     std::string::size_type aSlash = aSubShapeName.rfind('/');
1822     if (aSlash != std::string::npos) {
1823       std::string aCompName = aSubShapeName.substr(aSlash + 1);
1824       CompositeFeaturePtr aComposite =
1825         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aCont));
1826       if (aComposite.get() && aComposite->numberOfSubs()) {
1827         const int aSubNum = aComposite->numberOfSubs();
1828         for (int a = 0; a < aSubNum && theValue.IsNull(); a++) {
1829           FeaturePtr aSub = aComposite->subFeature(a);
1830           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
1831           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
1832           for (; aRes != aResults.cend() && theValue.IsNull(); aRes++) {
1833             if ((*aRes)->data()->name() == aCompName) {
1834               theValue = std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->shapeLab();
1835               break;
1836             } else { // any sub-label because the sketch line may be renamed, but not sub-vertices
1837               TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->shapeLab();
1838               TDF_ChildIDIterator aSubNames(aLab, TDataStd_Name::GetID());
1839               for(; aSubNames.More(); aSubNames.Next()) {
1840                 if (Handle(TDataStd_Name)::DownCast(aSubNames.Value())->Get().
1841                   IsEqual(aCompName.c_str())) {
1842                   theValue = aSubNames.Value()->Label();
1843                   break;
1844                 }
1845               }
1846             }
1847           }
1848         }
1849       }
1850     }
1851   }
1852
1853   if (aCont.get()) {
1854     theContext = std::dynamic_pointer_cast<Model_Data>(aCont->data())->label();
1855   }
1856   return true;
1857 }
1858
1859 bool Model_AttributeSelection::isLater(
1860   const TDF_Label theResult1, const TDF_Label theResult2) const
1861 {
1862   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1863     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1864   FeaturePtr aFeat1 = aDoc->featureByLab(theResult1);
1865   if (!aFeat1.get())
1866     return false;
1867   FeaturePtr aFeat2 = aDoc->featureByLab(theResult2);
1868   if (!aFeat2.get())
1869     return false;
1870   return aDoc->isLaterByDep(aFeat1, aFeat2);
1871 }
1872
1873 ResultPtr Model_AttributeSelection::newestContext(
1874   const ResultPtr theCurrent, const GeomShapePtr theValue)
1875 {
1876   ResultPtr aResult = theCurrent;
1877   GeomShapePtr aSelectedShape = theValue.get() ? theValue : theCurrent->shape();
1878   std::shared_ptr<Model_Document> aDoc =
1879     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1880   bool aFindNewContext = true;
1881   while (aFindNewContext && aResult.get()) {
1882     aFindNewContext = false;
1883     // try to find the last context to find the up to date shape
1884     TopoDS_Shape aConShape = aResult->shape()->impl<TopoDS_Shape>();
1885     if (TNaming_Tool::HasLabel(selectionLabel(), aConShape)) {
1886       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
1887       if (!aNS.IsNull()) {
1888         aNS = TNaming_Tool::CurrentNamedShape(aNS);
1889         if (!aNS.IsNull()
1890             && isLater(selectionLabel(), aNS->Label())
1891             && isLater(aNS->Label(),
1892                        std::dynamic_pointer_cast<Model_Data>(aResult->data())->label()))
1893         {
1894           TDF_Label aLab = aNS->Label();
1895           ResultPtr aRes = aDoc->resultByLab(aLab);
1896           if (aRes.get()) {
1897             if (aRes->shape()->isSubShape(aSelectedShape)) {
1898               aResult = aRes;
1899               aFindNewContext = true;
1900               continue;
1901             }
1902           }
1903         }
1904       }
1905     }
1906
1907     // TestFillWireVertex.py - sketch constructions for wire may participate too
1908     //if (aResult->groupName() == ModelAPI_ResultBody::group()) {
1909       // try to search newer context by the concealment references
1910       // take references to all results: root one, any sub
1911     std::list<ResultPtr> allRes;
1912     ResultPtr aCompContext;
1913     ResultBodyPtr aCompBody = ModelAPI_Tools::bodyOwner(aResult, true);
1914     if (aCompBody.get()) {
1915       ModelAPI_Tools::allSubs(aCompBody, allRes);
1916       allRes.push_back(aCompBody);
1917       aCompContext = aCompBody;
1918     }
1919     if (allRes.empty())
1920       allRes.push_back(aResult);
1921
1922     for (std::list<ResultPtr>::iterator aSub = allRes.begin(); aSub != allRes.end(); aSub++) {
1923       ResultPtr aResCont = *aSub;
1924       ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResCont);
1925       if (aResBody.get() && aResBody->numberOfSubs() > 0 && aResBody != aCompContext)
1926         continue; // only lower and higher level subs are counted
1927       const std::set<AttributePtr>& aRefs = aResCont->data()->refsToMe();
1928       std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1929       for (; !aFindNewContext && aRef != aRefs.end(); aRef++) {
1930         if (!aRef->get() || !(*aRef)->owner().get())
1931           continue;
1932         // concealed attribute only
1933         FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1934         if (!ModelAPI_Session::get()->validators()->isConcealed(
1935           aRefFeat->getKind(), (*aRef)->id()))
1936           continue;
1937         // search the feature result that contains sub-shape selected
1938         std::list<std::shared_ptr<ModelAPI_Result> > aResults;
1939
1940         // take all sub-results or one result
1941         std::list<ResultPtr> aRefFeatResults;
1942         ModelAPI_Tools::allResults(aRefFeat, aRefFeatResults);
1943         std::list<ResultPtr>::iterator aRefResIter = aRefFeatResults.begin();
1944         for (; aRefResIter != aRefFeatResults.end(); aRefResIter++) {
1945           ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRefResIter);
1946           if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1947             aResults.push_back(aBody);
1948         }
1949         std::list<std::shared_ptr<ModelAPI_Result> >::iterator aResIter = aResults.begin();
1950
1951         // searching by sub-shape
1952         for (; aResIter != aResults.end(); aResIter++) {
1953           if (!aResIter->get() || !(*aResIter)->data()->isValid() || (*aResIter)->isDisabled())
1954             continue;
1955           GeomShapePtr aShape = (*aResIter)->shape();
1956           if (aShape.get() && aShape->isSubShape(aSelectedShape, false)) {
1957             aResult = *aResIter; // found new context (produced from this) with same subshape
1958             aFindNewContext = true; // continue searching further
1959             break;
1960           }
1961         }
1962       }
1963     }
1964   }
1965   // if compsolid is context, try to take sub-solid as context: like in GUI and scripts
1966   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
1967   if (aComp && aComp->numberOfSubs()) {
1968     std::list<ResultPtr> allSubs;
1969     ModelAPI_Tools::allSubs(aComp, allSubs);
1970     std::list<ResultPtr>::iterator aS = allSubs.begin();
1971     for (; aS != allSubs.end(); aS++) {
1972       ResultBodyPtr aSub = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aS);
1973       if (aSub && aSub->numberOfSubs() == 0 && aSub->shape().get() &&
1974           aSub->shape()->isSubShape(aSelectedShape)) {
1975         aResult = aSub;
1976         break;
1977       }
1978     }
1979   }
1980   // in case sketch line was selected for wire, but wire was concealed and not such line anymore,
1981   // so, actually, the sketch element was selected (which is never concealed)
1982   if (aResult != theCurrent && aResult->isConcealed())
1983     aResult = theCurrent;
1984   return aResult;
1985 }
1986
1987 void Model_AttributeSelection::combineGeometrical()
1988 {
1989   if (myTmpContext.get() || myTmpSubShape.get())
1990     return;
1991   TDF_Label aSelLab = selectionLabel();
1992   if (aSelLab.IsAttribute(kINVALID_SELECTION) || !myRef.isInitialized())
1993     return;
1994
1995   if (aSelLab.IsAttribute(kCIRCLE_CENTER) || aSelLab.IsAttribute(kELLIPSE_CENTER1) ||
1996       aSelLab.IsAttribute(kELLIPSE_CENTER2) || aSelLab.IsAttribute(kSIMPLE_REF_ID))
1997     return;
1998
1999   if (aSelLab.IsAttribute(kPART_REF_ID)) {
2000     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
2001     if (!aPart.get() || !aPart->isActivated())
2002       return; // postponed naming needed
2003     Handle(TDataStd_Integer) anIndex;
2004     if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
2005       if (anIndex->Get()) { // special selection attribute was created, use it
2006         std::string aNewName;
2007         aPart->combineGeometrical(anIndex->Get(), aNewName);
2008         TDataStd_Name::Set(aSelLab, aNewName.c_str());
2009       }
2010     }
2011     return;
2012   }
2013
2014   std::shared_ptr<Model_ResultConstruction> aConstr =
2015     std::dynamic_pointer_cast<Model_ResultConstruction>(context());
2016   if (aConstr.get())
2017     return;
2018   FeaturePtr aFeature = contextFeature();
2019   if (aFeature.get())
2020     return;
2021
2022   Selector_Selector aSelector(aSelLab, baseDocumentLab());
2023   TopoDS_Shape aContextShape = context()->shape()->impl<TopoDS_Shape>();
2024   if (aSelector.restore(aContextShape)) {
2025     aSelector.combineGeometrical(aContextShape);
2026   }
2027 }
2028
2029 TDF_Label Model_AttributeSelection::baseDocumentLab()
2030 {
2031   if (ModelAPI_Session::get()->moduleDocument() != owner()->document())
2032     return std::dynamic_pointer_cast<Model_Document>
2033       (ModelAPI_Session::get()->moduleDocument())->extConstructionsLabel();
2034   static TDF_Label anEmpty;
2035   return anEmpty;
2036 }