]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
Multiple fixes (issue #1757 , issue #1799 , issue #1842 , etc):
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_AttributeSelection.cpp
4 // Created:     2 Oct 2014
5 // Author:      Mikhail PONIKAROV
6
7 #include "Model_AttributeSelection.h"
8 #include "Model_Application.h"
9 #include "Model_Events.h"
10 #include "Model_Data.h"
11 #include "Model_Document.h"
12 #include "Model_SelectionNaming.h"
13 #include <Model_Objects.h>
14 #include <ModelAPI_Feature.h>
15 #include <ModelAPI_ResultBody.h>
16 #include <ModelAPI_ResultConstruction.h>
17 #include <ModelAPI_ResultPart.h>
18 #include <ModelAPI_CompositeFeature.h>
19 #include <ModelAPI_Tools.h>
20 #include <GeomAPI_Shape.h>
21 #include <ModelAPI_Session.h>
22 #include <GeomAPI_PlanarEdges.h>
23 #include <Events_InfoMessage.h>
24
25 #include <TNaming_Selector.hxx>
26 #include <TNaming_NamedShape.hxx>
27 #include <TNaming_Tool.hxx>
28 #include <TNaming_Builder.hxx>
29 #include <TNaming_Localizer.hxx>
30 #include <TNaming_SameShapeIterator.hxx>
31 #include <TNaming_Iterator.hxx>
32 #include <TNaming_NewShapeIterator.hxx>
33 #include <TopoDS_Shape.hxx>
34 #include <TopoDS_Compound.hxx>
35 #include <TDataStd_IntPackedMap.hxx>
36 #include <TDataStd_Integer.hxx>
37 #include <TDataStd_UAttribute.hxx>
38 #include <TDataStd_Name.hxx>
39 #include <TopTools_MapOfShape.hxx>
40 #include <TopTools_IndexedMapOfShape.hxx>
41 #include <TopTools_MapIteratorOfMapOfShape.hxx>
42 #include <TopTools_ListOfShape.hxx>
43 #include <NCollection_DataMap.hxx>
44 #include <TopExp_Explorer.hxx>
45 #include <TDF_LabelMap.hxx>
46 #include <BRep_Tool.hxx>
47 #include <BRep_Builder.hxx>
48 #include <TopoDS_Edge.hxx>
49 #include <TopoDS.hxx>
50 #include <TopExp.hxx>
51 #include <TColStd_MapOfTransient.hxx>
52 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
53 #include <TopTools_ListIteratorOfListOfShape.hxx>
54 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
55 #include <gp_Pnt.hxx>
56 #include <Precision.hxx>
57 #include <TDF_ChildIterator.hxx>
58 #include <TDF_ChildIDIterator.hxx>
59 #include <TDataStd_Name.hxx>
60 #include <TopAbs_ShapeEnum.hxx>
61 #include <TopoDS_Iterator.hxx>
62 #include <BRep_Builder.hxx>
63
64 using namespace std;
65 //#define DEB_NAMING 1
66 #ifdef DEB_NAMING
67 #include <BRepTools.hxx>
68 #endif
69 /// added to the index in the packed map to signalize that the vertex of edge is selected
70 /// (multiplied by the index of the edge)
71 static const int kSTART_VERTEX_DELTA = 1000000;
72 // identifier that there is simple reference: selection equals to context
73 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
74 // simple reference in the construction
75 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
76 // reference to Part sub-object
77 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
78 // selection is invalid after recomputation
79 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
80
81 // on this label is stored:
82 // TNaming_NamedShape - selected shape
83 // TNaming_Naming - topological selection information (for the body)
84 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
85 // TDataStd_Integer - type of the selected shape (for construction)
86 // TDF_Reference - from ReferenceAttribute, the context
87 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
88   const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
89 {
90   if (theTemporarily) { // just keep the stored without DF update
91     myTmpContext = theContext;
92     myTmpSubShape = theSubShape;
93     owner()->data()->sendAttributeUpdated(this);
94     return;
95   } else {
96     myTmpContext.reset();
97     myTmpSubShape.reset();
98   }
99
100   const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
101   bool isOldContext = theContext == myRef.value();
102   bool isOldShape = isOldContext &&
103     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
104   if (isOldShape) return; // shape is the same, so context is also unchanged
105   // update the referenced object if needed
106   if (!isOldContext) {
107       myRef.setValue(theContext);
108   }
109
110   // do noth use naming if selected shape is result shape itself, but not sub-shape
111   TDF_Label aSelLab = selectionLabel();
112   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
113   aSelLab.ForgetAttribute(kCONSTUCTION_SIMPLE_REF_ID);
114   aSelLab.ForgetAttribute(kINVALID_SELECTION);
115
116   bool isDegeneratedEdge = false;
117   // do not use the degenerated edge as a shape, a null context and shape is used in the case
118   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
119     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
120     if (aSubShape.ShapeType() == TopAbs_EDGE)
121       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
122   }
123   if (!theContext.get() || isDegeneratedEdge) {
124     // to keep the reference attribute label
125     TDF_Label aRefLab = myRef.myRef->Label();
126     aSelLab.ForgetAllAttributes(true);
127     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
128     return;
129   }
130   if (theContext->groupName() == ModelAPI_ResultBody::group()) {
131     // do not select the whole shape for body:it is already must be in the data framework
132     // equal and null selected objects mean the same: object is equal to context,
133     if (theContext->shape().get() && 
134         (theContext->shape()->isEqual(theSubShape) || !theSubShape.get())) {
135       aSelLab.ForgetAllAttributes(true);
136       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
137     } else {
138       selectBody(theContext, theSubShape);
139     }
140   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
141     if (!theSubShape.get()) {
142       // to sub, so the whole result is selected
143       aSelLab.ForgetAllAttributes(true);
144       TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
145       ResultConstructionPtr aConstruction = 
146         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
147       if (aConstruction->isInfinite()) {
148         // For correct naming selection, put the shape into the naming structure.
149         // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
150         TNaming_Builder aBuilder(aSelLab);
151         aBuilder.Generated(theContext->shape()->impl<TopoDS_Shape>());
152         std::shared_ptr<Model_Document> aMyDoc = 
153           std::dynamic_pointer_cast<Model_Document>(owner()->document());
154         //std::string aName = contextName(theContext);
155         // for selection in different document, add the document name
156         //aMyDoc->addNamingName(aSelLab, aName);
157         //TDataStd_Name::Set(aSelLab, aName.c_str());
158       } else {  // for sketch the naming is needed in DS
159         BRep_Builder aCompoundBuilder;
160         TopoDS_Compound aComp;
161         aCompoundBuilder.MakeCompound(aComp);
162         for(int a = 0; a < aConstruction->facesNum(); a++) {
163           TopoDS_Shape aFace = aConstruction->face(a)->impl<TopoDS_Shape>();
164           aCompoundBuilder.Add(aComp, aFace);
165         }
166         std::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
167         aShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aComp));
168         selectConstruction(theContext, aShape);
169       }
170     } else {
171       selectConstruction(theContext, theSubShape);
172     }
173   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
174     aSelLab.ForgetAllAttributes(true);
175     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
176     selectPart(theContext, theSubShape);
177   }
178   //the attribute initialized state should be changed by sendAttributeUpdated only
179   //myIsInitialized = true;
180
181   owner()->data()->sendAttributeUpdated(this);
182 }
183
184 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
185 {
186   GeomShapePtr aResult;
187   if (myTmpContext.get() || myTmpSubShape.get()) {
188     ResultConstructionPtr aResulConstruction = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myTmpContext);
189     if(aResulConstruction.get()) {
190       // it is just reference to construction.
191       return myTmpSubShape;
192     }
193     return myTmpSubShape.get() ? myTmpSubShape : myTmpContext->shape();
194   }
195
196   TDF_Label aSelLab = selectionLabel();
197   if (aSelLab.IsAttribute(kINVALID_SELECTION))
198     return aResult;
199
200   if (myRef.isInitialized()) {
201     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
202       ResultPtr aContext = context();
203       if (!aContext.get()) 
204         return aResult; // empty result
205       return aContext->shape();
206     }
207     if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
208         return aResult; // empty result
209     }
210     if (aSelLab.IsAttribute(kPART_REF_ID)) {
211       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
212       if (!aPart.get() || !aPart->isActivated())
213         return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
214       Handle(TDataStd_Integer) anIndex;
215       if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
216         if (anIndex->Get()) { // special selection attribute was created, use it
217           return aPart->selectionValue(anIndex->Get());
218         } else { // face with name is already in the data model, so try to take it by name
219           Handle(TDataStd_Name) aName;
220           if (selectionLabel().FindAttribute(TDataStd_Name::GetID(), aName)) {
221             std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
222             std::size_t aPartEnd = aSubShapeName.find('/');
223             if (aPartEnd != string::npos && aPartEnd != aSubShapeName.rfind('/')) {
224               string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
225               int anIndex;
226               std::string aType; // to reuse already existing selection the type is not needed
227               return aPart->shapeInPart(aNameInPart, aType, anIndex);
228             }
229           }
230         }
231       }
232     }
233
234     Handle(TNaming_NamedShape) aSelection;
235     if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
236       TopoDS_Shape aSelShape = aSelection->Get();
237       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
238       aResult->setImpl(new TopoDS_Shape(aSelShape));
239     } else { // for simple construction element: just shape of this construction element
240       ResultConstructionPtr aConstr = 
241         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
242       if (aConstr) {
243         return aConstr->shape();
244       }
245     }
246   }
247   return aResult;
248 }
249
250 bool Model_AttributeSelection::isInvalid()
251 {
252   return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
253 }
254
255 bool Model_AttributeSelection::isInitialized()
256 {
257   if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
258     std::shared_ptr<GeomAPI_Shape> aResult;
259     if (myRef.isInitialized()) {
260       TDF_Label aSelLab = selectionLabel();
261       if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
262         ResultPtr aContext = context();
263         return aContext.get() != NULL;
264       }
265       if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
266           return true;
267       }
268
269       Handle(TNaming_NamedShape) aSelection;
270       if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
271         return !aSelection->Get().IsNull();
272       } else { // for simple construction element: just shape of this construction element
273         ResultConstructionPtr aConstr = 
274           std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
275         if (aConstr.get()) {
276           return aConstr->shape().get() != NULL;
277         }
278       }
279     }
280   }
281   return false;
282 }
283
284 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
285   : myRef(theLabel)
286 {
287   myIsInitialized = myRef.isInitialized();
288 }
289
290 void Model_AttributeSelection::setID(const std::string theID)
291 {
292   myRef.setID(theID);
293   ModelAPI_AttributeSelection::setID(theID);
294 }
295
296 ResultPtr Model_AttributeSelection::context() {
297   if (myTmpContext.get() || myTmpSubShape.get()) {
298     return myTmpContext;
299   }
300
301   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
302   // for parts there could be same-data result, so take the last enabled
303   if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
304     int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
305     for(int a = aSize - 1; a >= 0; a--) {
306       ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
307       if (aPart.get() && aPart->data() == aResult->data()) {
308         ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
309         FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
310         // check that this result is not this-feature result (it is forbidden t oselect itself)
311         if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
312           return aPartResult;
313         }
314       }
315     }
316   }
317   return aResult;
318 }
319
320
321 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
322 {
323   ModelAPI_AttributeSelection::setObject(theObject);
324   myRef.setObject(theObject);
325 }
326
327 TDF_LabelMap& Model_AttributeSelection::scope()
328 {
329   if (myScope.IsEmpty()) { // create a new scope if not yet done
330     // gets all features with named shapes that are before this feature label (before in history)
331     DocumentPtr aMyDoc = owner()->document();
332     std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
333     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
334     bool aMePassed = false;
335     CompositeFeaturePtr aComposite = 
336       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
337     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
338     CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
339     if (aFeature.get()) {
340       aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
341       if (aCompositeOwner.get()) {
342          aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
343       }
344     }
345     // for group Scope is not limitet: this is always up to date objects
346     bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
347     for(; aFIter != allFeatures.end(); aFIter++) {
348       if (*aFIter == owner()) {  // the left features are created later (except subs of composite)
349         aMePassed = true;
350         continue;
351       }
352       if (isGroup) aMePassed = false;
353       bool isInScope = !aMePassed;
354       if (!isInScope && aComposite.get()) { // try to add sub-elements of composite if this is composite
355         if (aComposite->isSub(*aFIter))
356           isInScope = true;
357       }
358       // remove the composite-owner of this feature (sketch in extrusion-cut)
359       if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
360         isInScope = false;
361
362       if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
363         TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
364           (*aFIter)->data())->label().Father();
365         TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), 1);
366         for(; aNSIter.More(); aNSIter.Next()) {
367           Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
368           if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
369             myScope.Add(aNS->Label());
370           }
371         }
372       }
373     }
374   }
375   return myScope;
376 }
377
378 /// Sets the invalid flag if flag is false, or removes it if "true"
379 /// Returns theFlag
380 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
381   if (theFlag) {
382     theLab.ForgetAttribute(kINVALID_SELECTION);
383   } else {
384     TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
385   }
386   return theFlag;
387 }
388
389 bool Model_AttributeSelection::update()
390 {
391   TDF_Label aSelLab = selectionLabel();
392   ResultPtr aContext = context();
393   if (!aContext.get()) 
394     return setInvalidIfFalse(aSelLab, false);
395   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
396     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
397   }
398   if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
399     // if there is a sketch, the sketch-naming must be updated
400     ResultConstructionPtr aConstruction = 
401       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
402     if (!aConstruction->isInfinite()) {
403       BRep_Builder aCompoundBuilder;
404       TopoDS_Compound aComp;
405       aCompoundBuilder.MakeCompound(aComp);
406       for(int a = 0; a < aConstruction->facesNum(); a++) {
407         TopoDS_Shape aFace = aConstruction->face(a)->impl<TopoDS_Shape>();
408         aCompoundBuilder.Add(aComp, aFace);
409       }
410       std::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
411       aShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aComp));
412       selectConstruction(aContext, aShape);
413     } else {
414       // For correct naming selection, put the shape into the naming structure.
415       // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
416       TNaming_Builder aBuilder(aSelLab);
417       aBuilder.Generated(aContext->shape()->impl<TopoDS_Shape>());
418       std::shared_ptr<Model_Document> aMyDoc = 
419         std::dynamic_pointer_cast<Model_Document>(owner()->document());
420       //std::string aName = contextName(aContext);
421       //aMyDoc->addNamingName(aSelLab, aName);
422       //TDataStd_Name::Set(aSelLab, aName.c_str());
423     }
424     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
425   }
426
427   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
428     std::shared_ptr<GeomAPI_Shape> aNoSelection;
429     bool aResult = selectPart(aContext, aNoSelection, true);
430     aResult = setInvalidIfFalse(aSelLab, aResult);
431     if (aResult) {
432       owner()->data()->sendAttributeUpdated(this);
433     }
434     return aResult;
435   }
436
437   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
438     // body: just a named shape, use selection mechanism from OCCT
439     TNaming_Selector aSelector(aSelLab);
440     TopoDS_Shape anOldShape;
441     if (!aSelector.NamedShape().IsNull()) {
442       anOldShape = aSelector.NamedShape()->Get();
443     }
444     bool aResult = aSelector.Solve(scope()) == Standard_True;
445     aResult = setInvalidIfFalse(aSelLab, aResult); // must be before sending of updated attribute (1556)
446     TopoDS_Shape aNewShape;
447     if (!aSelector.NamedShape().IsNull()) {
448       aNewShape = aSelector.NamedShape()->Get();
449     }
450     if (anOldShape.IsNull() || aNewShape.IsNull() ||
451         !anOldShape.IsEqual(aSelector.NamedShape()->Get())) // send updated if shape is changed
452       owner()->data()->sendAttributeUpdated(this);
453     return aResult;
454   } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
455     // construction: identification by the results indexes, recompute faces and
456     // take the face that more close by the indexes
457     ResultConstructionPtr aConstructionContext = 
458       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
459     FeaturePtr aContextFeature = aContext->document()->feature(aContext);
460     // sketch sub-element
461     if (aConstructionContext && 
462         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
463     {
464       TDF_Label aLab = myRef.myRef->Label();
465       // getting a type of selected shape
466       Handle(TDataStd_Integer) aTypeAttr;
467       if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
468         return setInvalidIfFalse(aSelLab, false);
469       }
470       TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
471       // selected indexes will be needed in each "if"
472       Handle(TDataStd_IntPackedMap) aSubIds;
473       std::shared_ptr<GeomAPI_Shape> aNewSelected;
474       bool aNoIndexes = 
475         !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
476       // for now working only with composite features
477       CompositeFeaturePtr aComposite = 
478         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
479       if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
480         return setInvalidIfFalse(aSelLab, false);
481       }
482
483       if (aShapeType == TopAbs_FACE || aShapeType == TopAbs_WIRE) { // compound is for the whole sketch selection
484         // If this is a wire with plane defined then it is a sketch-like object
485         if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
486           return setInvalidIfFalse(aSelLab, false);
487         // if there is no edges indexes, any face can be used: take the first
488         std::shared_ptr<GeomAPI_Shape> aNewSelected;
489         if (aNoIndexes) {
490           aNewSelected = aConstructionContext->face(0);
491         } else { // searching for most looks-like initial face by the indexes
492           // prepare edges of the current result for the fast searching
493           NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
494           const int aSubNum = aComposite->numberOfSubs();
495           for(int a = 0; a < aSubNum; a++) {
496             int aSubID = aComposite->subFeatureId(a);
497             if (aSubIds->Contains(aSubID)) {
498               FeaturePtr aSub = aComposite->subFeature(a);
499               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
500               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
501               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
502                 ResultConstructionPtr aConstr = 
503                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
504                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
505                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
506                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
507                   if (!anEdge.IsNull()) {
508                     Standard_Real aFirst, aLast;
509                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
510                     // searching for orientation information
511                     int anOrient = 0;
512                     Handle(TDataStd_Integer) anInt;
513                     if (aSelLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)){
514                       anOrient = anInt->Get();
515                     }
516                     allCurves.Bind(aCurve, anOrient);
517                   }
518                 }
519               }
520             }
521           }
522           aNewSelected = Model_SelectionNaming::findAppropriateFace(
523             aContext, allCurves, aShapeType == TopAbs_WIRE);
524         }
525         if (aNewSelected) { // store this new selection
526           selectConstruction(aContext, aNewSelected);
527           setInvalidIfFalse(aSelLab, true);
528           owner()->data()->sendAttributeUpdated(this);
529           return true;
530         } else { // if the selection is not found, put the empty shape: it's better to have disappeared shape, than the old, the lost one
531           TNaming_Builder anEmptyBuilder(selectionLabel());
532           return setInvalidIfFalse(aSelLab, false);
533         }
534       } else if (aShapeType == TopAbs_EDGE) {
535         // just reselect the edge by the id
536         const int aSubNum = aComposite->numberOfSubs();
537         for(int a = 0; a < aSubNum; a++) {
538           // if aSubIds take any, the first appropriate
539           if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
540             // found the appropriate feature
541             FeaturePtr aFeature = aComposite->subFeature(a);
542             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
543               aFeature->results().cbegin();
544             for(;aResIter != aFeature->results().cend(); aResIter++) {
545               ResultConstructionPtr aRes = 
546                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
547               if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
548                 selectConstruction(aContext, aRes->shape());
549                 setInvalidIfFalse(aSelLab, true);
550                 owner()->data()->sendAttributeUpdated(this);
551                 return true;
552               }
553             }
554           }
555         }
556       } else if (aShapeType == TopAbs_VERTEX) {
557         // just reselect the vertex by the id of edge
558         const int aSubNum = aComposite->numberOfSubs();
559         for(int a = 0; a < aSubNum; a++) {
560           // if aSubIds take any, the first appropriate
561           int aFeatureID = aComposite->subFeatureId(a);
562           if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
563             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
564             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
565               // searching for deltas
566               int aVertexNum = 0;
567               if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
568               else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
569               // found the feature with appropriate edge
570               FeaturePtr aFeature = aComposite->subFeature(a);
571               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
572                 aFeature->results().cbegin();
573               for(;aResIter != aFeature->results().cend(); aResIter++) {
574                 ResultConstructionPtr aRes = 
575                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
576                 if (aRes && aRes->shape()) {
577                   if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
578                     selectConstruction(aContext, aRes->shape());
579                     setInvalidIfFalse(aSelLab, true);
580                     owner()->data()->sendAttributeUpdated(this);
581                     return true;
582                   } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
583                     const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
584                     int aVIndex = 1;
585                     for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
586                       if (aVIndex == aVertexNum) { // found!
587                         std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
588                         aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
589                         selectConstruction(aContext, aVertex);
590                         setInvalidIfFalse(aSelLab, true);
591                         owner()->data()->sendAttributeUpdated(this);
592                         return true;
593                       }
594                       aVIndex++;
595                     }
596                   }
597                 }
598               }
599           }
600         }
601       }
602     } else { // simple construction element: the selected is that needed
603       selectConstruction(aContext, aContext->shape());
604       setInvalidIfFalse(aSelLab, true);
605       owner()->data()->sendAttributeUpdated(this);
606       return true;
607     }
608   }
609   return setInvalidIfFalse(aSelLab, false); // unknown case
610 }
611
612 void Model_AttributeSelection::selectBody(
613   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
614 {
615   // perform the selection
616   TNaming_Selector aSel(selectionLabel());
617   TopoDS_Shape aContext;
618
619   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
620   if (aBody) {
621     aContext = aBody->shape()->impl<TopoDS_Shape>();
622   } else {
623     ResultPtr aResult = 
624       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
625     if (aResult) {
626       aContext = aResult->shape()->impl<TopoDS_Shape>();
627     } else {
628       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
629       return;
630     }
631   }
632
633   // with "recover" feature the selected context may be not up to date (issue 1710)
634   Handle(TNaming_NamedShape) aResult;
635   TDF_Label aSelLab = selectionLabel();
636   TopoDS_Shape aNewContext = aContext;
637   bool isUpdated = true;
638   while(!aNewContext.IsNull() && isUpdated) { // searching for the very last shape that was produced from this one
639     isUpdated = false;
640     if (!TNaming_Tool::HasLabel(aSelLab, aNewContext)) // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
641       break;
642     for(TNaming_SameShapeIterator anIter(aNewContext, aSelLab); anIter.More(); anIter.Next()) {
643       TDF_Label aNSLab = anIter.Label();
644       if (!scope().Contains(aNSLab))
645         continue;
646       Handle(TNaming_NamedShape) aNS;
647       if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
648         for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
649           if (aShapesIter.Evolution() == TNaming_SELECTED)
650             continue; // don't use the selection evolution
651           if (!aShapesIter.OldShape().IsNull() && aShapesIter.OldShape().IsSame(aNewContext)) {
652              // found the original shape
653             aNewContext = aShapesIter.NewShape(); // go to the newer shape
654             isUpdated = true;
655             break;
656           }
657         }
658       }
659     }
660   }
661   if (aNewContext.IsNull()) { // a context is already deleted
662     setInvalidIfFalse(aSelLab, false);
663     Events_InfoMessage("Model_AttributeSelection", "Failed to select shape already deleted").send();
664     return;
665   }
666
667   TopoDS_Shape aNewSub = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
668   if (!aNewSub.IsEqual(aContext)) { // searching for subshape in the new context
669     bool isFound = false;
670     TopExp_Explorer anExp(aNewContext, aNewSub.ShapeType());
671     for(; anExp.More(); anExp.Next()) {
672       if (anExp.Current().IsEqual(aNewSub)) {
673         isFound = true;
674         break;
675       }
676     }
677     if (!isFound) { // sub-shape is not found in the up-to-date instance of the context shape
678       setInvalidIfFalse(aSelLab, false);
679       Events_InfoMessage("Model_AttributeSelection", "Failed to select sub-shape already modified").send();
680       return;
681     }
682   }
683
684
685   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
686   FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
687   if (aFeatureOwner.get())
688     aFeatureOwner->eraseResults();
689   if (!aContext.IsNull()) {
690     aSel.Select(aNewSub, aNewContext); 
691   }
692 }
693
694 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
695 /// if theID is zero, 
696 /// theOrientation is additional information about the positioning of edge relatively to face
697 ///    it is stored in the integer attribute of the edge sub-label: 
698 ///    -1 is out, 1 is in, 0 is not needed
699 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
700   const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
701   std::map<int, int>& theOrientations,
702   std::map<int, std::string>& theSubNames, // name of sub-elements by ID to be exported instead of indexes
703   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)(),
704   const int theOrientation = 0)
705 {
706   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
707   if (theOrientation != 0) { // store the orientation of edge relatively to face if needed
708     TDataStd_Integer::Set(aLab, theOrientation);
709   }
710   TNaming_Builder aBuilder(aLab);
711   aBuilder.Generated(theShape);
712   std::stringstream aName;
713   // #1839 : do not store name of the feature in the tree, since this name could be changed
714   //aName<<theContextFeature->name();
715   if (theShape.ShapeType() != TopAbs_COMPOUND) { // compound means the whole result for construction
716     //aName<<"/";
717     if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
718     else if (theShape.ShapeType() == TopAbs_WIRE) aName<<"Wire";
719     else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
720     else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
721
722     if (theRefs.IsNull()) {
723       aName<<theID;
724       if (theOrientation == 1)
725         aName<<"f";
726       else if (theOrientation == -1)
727         aName<<"r";
728     } else { // make a composite name from all sub-elements indexes: "1_2_3_4"
729       TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
730       for(; aRef.More(); aRef.Next()) {
731         aName<<"-"<<theSubNames[aRef.Key()];
732         if (theOrientations.find(aRef.Key()) != theOrientations.end()) {
733           if (theOrientations[aRef.Key()] == 1)
734             aName<<"f";
735           else if (theOrientations[aRef.Key()] == -1)
736             aName<<"r";
737         }
738       }
739     }
740   }
741
742   theDoc->addNamingName(aLab, aName.str());
743   TDataStd_Name::Set(aLab, aName.str().c_str());
744 }
745
746 void Model_AttributeSelection::selectConstruction(
747   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
748 {
749   std::shared_ptr<Model_Document> aMyDoc = 
750     std::dynamic_pointer_cast<Model_Document>(owner()->document());
751   FeaturePtr aContextFeature = theContext->document()->feature(theContext);
752   CompositeFeaturePtr aComposite = 
753     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
754   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
755   if (!aComposite || aComposite->numberOfSubs() == 0) {
756     // saving of context is enough: result construction contains exactly the needed shape
757     TNaming_Builder aBuilder(selectionLabel());
758     aBuilder.Generated(aSubShape);
759     //std::string aName = contextName(theContext);
760     //aMyDoc->addNamingName(selectionLabel(), aName);
761     //TDataStd_Name::Set(selectionLabel(), aName.c_str());
762     return;
763   }
764   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
765   TDF_Label aLab = myRef.myRef->Label();
766   // identify the results of sub-object of the composite by edges
767   // save type of the selected shape in integer attribute
768   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
769   TDataStd_Integer::Set(aLab, (int)aShapeType);
770   gp_Pnt aVertexPos;
771   TColStd_MapOfTransient allCurves;
772   if (aShapeType == TopAbs_VERTEX) { // compare positions
773     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
774   } else { 
775     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
776       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
777       Standard_Real aFirst, aLast;
778       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
779       allCurves.Add(aCurve);
780     }
781   }
782   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
783   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
784   std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
785   std::map<int, std::string> aSubNames; //map from edges IDs to names of edges
786   aRefs->Clear();
787   const int aSubNum = aComposite->numberOfSubs();
788   for(int a = 0; a < aSubNum; a++) {
789     FeaturePtr aSub = aComposite->subFeature(a);
790     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
791     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
792     // there may be many shapes (circle and center): register if at least one is in selection
793     for(; aRes != aResults.cend(); aRes++) {
794       ResultConstructionPtr aConstr = 
795         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
796       if (!aConstr->shape()) {
797         continue;
798       }
799       if (aShapeType == TopAbs_VERTEX) {
800         if (aConstr->shape()->isVertex()) { // compare vertices positions
801           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
802           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
803           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
804             aRefs->Add(aComposite->subFeatureId(a));
805             aSubNames[aComposite->subFeatureId(a)] = Model_SelectionNaming::shortName(aConstr);
806           }
807         } else { // get first or last vertex of the edge: last is stored with additional delta
808           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
809           int aDelta = kSTART_VERTEX_DELTA;
810           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
811             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
812             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
813               aRefs->Add(aDelta + aComposite->subFeatureId(a));
814               aSubNames[aDelta + aComposite->subFeatureId(a)] =
815                 Model_SelectionNaming::shortName(aConstr, aDelta / kSTART_VERTEX_DELTA);
816               break;
817             }
818             aDelta += kSTART_VERTEX_DELTA;
819           }
820         }
821       } else {
822         if (aConstr->shape()->isEdge()) {
823           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
824           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
825           if (!anEdge.IsNull()) {
826             Standard_Real aFirst, aLast;
827             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
828             if (allCurves.Contains(aCurve)) {
829               int anID = aComposite->subFeatureId(a);
830               aRefs->Add(anID);
831               aSubNames[anID] = Model_SelectionNaming::shortName(aConstr);
832               if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
833                 // add edges to sub-label to support naming for edges selection
834                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
835                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
836                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
837                   Standard_Real aFirst, aLast;
838                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
839                   if (aFaceCurve == aCurve) {
840                     int anOrient = Model_SelectionNaming::edgeOrientation(aSubShape, anEdge);
841                     anOrientations[anID] = anOrient;
842                     registerSubShape(
843                       selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, anOrientations,
844                       aSubNames, Handle(TDataStd_IntPackedMap)(), anOrient);
845                   }
846                 }
847               } else { // put vertices of the selected edge to sub-labels
848                 // add edges to sub-label to support naming for edges selection
849                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
850                 int aTagIndex = anID + kSTART_VERTEX_DELTA;
851                 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
852                   TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
853
854                   std::stringstream anAdditionalName; 
855                   registerSubShape(
856                     selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc, anOrientations,
857                     aSubNames);
858                 }
859               }
860             }
861           }
862         }
863       }
864     }
865   }
866   // store the selected as primitive
867   TNaming_Builder aBuilder(selectionLabel());
868   aBuilder.Generated(aSubShape);
869     registerSubShape(
870       selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, anOrientations, aSubNames, aRefs); 
871 }
872
873 bool Model_AttributeSelection::selectPart(
874   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
875   const bool theUpdate)
876 {
877   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
878   if (!aPart.get() || !aPart->isActivated())
879     return true; // postponed naming
880   if (theUpdate) {
881     Handle(TDataStd_Integer) anIndex;
882     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) { // by internal selection
883       if (anIndex->Get() > 0) {
884         // update the selection by index
885         return aPart->updateInPart(anIndex->Get());
886       } else {
887         return true; // nothing to do, referencing just by name
888       }
889     }
890     return true; // nothing to do, referencing just by name
891   }
892   // store the shape (in case part is not loaded it should be useful
893   TopoDS_Shape aShape;
894   std::string aName = theContext->data()->name();
895   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
896     aShape = theContext->shape()->impl<TopoDS_Shape>();
897   } else {
898     aShape = theSubShape->impl<TopoDS_Shape>();
899     int anIndex;
900     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
901     TDataStd_Integer::Set(selectionLabel(), anIndex);
902   }
903   TNaming_Builder aBuilder(selectionLabel());
904   aBuilder.Select(aShape, aShape);
905   // identify by name in the part
906   TDataStd_Name::Set(selectionLabel(), aName.c_str());
907   return !aName.empty();
908 }
909
910 TDF_Label Model_AttributeSelection::selectionLabel()
911 {
912   return myRef.myRef->Label().FindChild(1);
913 }
914
915 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
916 {
917   std::string aName("");
918   if(!this->isInitialized())
919     return !theDefaultName.empty() ? theDefaultName : aName;
920
921   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
922   ResultPtr aCont = context();
923
924   Model_SelectionNaming aSelNaming(selectionLabel());
925   return aSelNaming.namingName(
926     aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
927 }
928
929 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
930 void Model_AttributeSelection::selectSubShape(
931   const std::string& theType, const std::string& theSubShapeName)
932 {
933   if(theSubShapeName.empty() || theType.empty()) return;
934
935   // check this is Part-name: 2 delimiters in the name
936   std::size_t aPartEnd = theSubShapeName.find('/');
937   if (aPartEnd != string::npos && aPartEnd != theSubShapeName.rfind('/')) {
938     std::string aPartName = theSubShapeName.substr(0, aPartEnd);
939     ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
940     if (aFound.get()) { // found such part, so asking it for the name
941       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
942       string aNameInPart = theSubShapeName.substr(aPartEnd + 1);
943       int anIndex;
944       std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, theType, anIndex);
945       if (aSelected.get()) {
946         setValue(aPart, aSelected);
947         TDataStd_Integer::Set(selectionLabel(), anIndex);
948         return;
949       }
950     }
951   }
952
953   Model_SelectionNaming aSelNaming(selectionLabel());
954   std::shared_ptr<Model_Document> aDoc = 
955     std::dynamic_pointer_cast<Model_Document>(owner()->document());
956   std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
957   ResultPtr aCont;
958   if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
959     // try to find the last context to find the up to dat shape
960     if (aCont->shape().get() && !aCont->shape()->isNull() &&
961       aCont->groupName() == ModelAPI_ResultBody::group() && aDoc == owner()->document()) {
962       const TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
963       if (!aConShape.IsNull()) {
964         Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
965         if (!aNS.IsNull()) {
966           aNS = TNaming_Tool::CurrentNamedShape(aNS);
967           if (!aNS.IsNull()) {
968             TDF_Label aLab = aNS->Label();
969             while(aLab.Depth() != 7 && aLab.Depth() > 5)
970               aLab = aLab.Father();
971             ObjectPtr anObj = aDoc->objects()->object(aLab);
972             if (anObj.get()) {
973               ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
974               if (aRes)
975                 aCont = aRes;
976             }
977           }
978         }
979       }
980     }
981     setValue(aCont, aShapeToBeSelected);
982   }
983 }
984
985 int Model_AttributeSelection::Id()
986 {
987   int anID = 0;
988   std::shared_ptr<GeomAPI_Shape> aSelection = value();
989   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
990   // support for compsolids:
991   if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
992     aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
993
994
995   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
996   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
997   // searching for the latest main shape
998   if (aSelection && !aSelection->isNull() &&
999     aContext   && !aContext->isNull())
1000   {
1001     std::shared_ptr<Model_Document> aDoc =
1002       std::dynamic_pointer_cast<Model_Document>(context()->document());
1003     if (aDoc.get()) {
1004       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1005       if (!aNS.IsNull()) {
1006         aMainShape = TNaming_Tool::CurrentShape(aNS);
1007       }
1008     }
1009
1010     TopTools_IndexedMapOfShape aSubShapesMap;
1011     TopExp::MapShapes(aMainShape, aSubShapesMap);
1012     anID = aSubShapesMap.FindIndex(aSubShape);
1013   }
1014   return anID;
1015 }
1016
1017 void Model_AttributeSelection::setId(int theID)
1018 {
1019   const ResultPtr& aContext = context();
1020   std::shared_ptr<GeomAPI_Shape> aSelection;
1021
1022   std::shared_ptr<GeomAPI_Shape> aContextShape = aContext->shape();
1023   // support for compsolids:
1024   if (aContext.get() && ModelAPI_Tools::compSolidOwner(aContext).get())
1025     aContextShape = ModelAPI_Tools::compSolidOwner(aContext)->shape();
1026
1027   TopoDS_Shape aMainShape = aContextShape->impl<TopoDS_Shape>();
1028   // searching for the latest main shape
1029   if (theID > 0 &&
1030       aContextShape && !aContextShape->isNull())
1031   {
1032     std::shared_ptr<Model_Document> aDoc =
1033       std::dynamic_pointer_cast<Model_Document>(aContext->document());
1034     if (aDoc.get()) {
1035       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1036       if (!aNS.IsNull()) {
1037         aMainShape = TNaming_Tool::CurrentShape(aNS);
1038       }
1039     }
1040
1041     TopTools_IndexedMapOfShape aSubShapesMap;
1042     TopExp::MapShapes(aMainShape, aSubShapesMap);
1043     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1044
1045     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1046     aResult->setImpl(new TopoDS_Shape(aSelShape));
1047
1048     aSelection = aResult;
1049   }
1050
1051   setValue(aContext, aSelection);
1052 }
1053
1054 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1055 {
1056   std::string aResult;
1057   if (owner()->document() != theContext->document()) {
1058     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1059       aResult = theContext->document()->kind() + "/";
1060     } else {
1061       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1062         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1063       if (aDocRes.get()) {
1064         aResult = aDocRes->data()->name() + "/";
1065       }
1066     }
1067   }
1068   aResult += theContext->data()->name();
1069   return aResult;
1070 }
1071
1072 void Model_AttributeSelection::updateInHistory()
1073 {
1074   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1075   // only bodies may be modified later in the history, don't do anything otherwise
1076   if (!aContext.get() || aContext->groupName() != ModelAPI_ResultBody::group())
1077     return;
1078   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1079   if (!aContData.get() || !aContData->isValid())
1080     return;
1081   TDF_Label aContLab = aContData->label(); // named shape where the selected context is located
1082   Handle(TNaming_NamedShape) aContNS;
1083   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS))
1084     return;
1085   std::shared_ptr<Model_Document> aDoc = 
1086     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1087   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1088   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1089   // iterate the context shape modifications in order to find a feature that is upper in history
1090   // that this one and is really modifies the referenced result to refer to it
1091   ResultPtr aModifierResFound;
1092   TNaming_Iterator aPairIter(aContNS);
1093   TopoDS_Shape aNewShape = aPairIter.NewShape();
1094   bool anIterate = true;
1095   // trying to update also the sub-shape selected
1096   GeomShapePtr aSubShape = value();
1097   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1098     aSubShape.reset();
1099
1100   while(anIterate) {
1101     anIterate = false;
1102     TNaming_SameShapeIterator aModifIter(aNewShape, aContLab);
1103     for(; aModifIter.More(); aModifIter.Next()) {
1104       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1105         (aDoc->objects()->object(aModifIter.Label().Father()));
1106       if (!aModifierObj.get())
1107         break;
1108       FeaturePtr aModifierFeat = aDoc->feature(aModifierObj);
1109       if (!aModifierFeat.get())
1110         break;
1111       if (aModifierFeat == aThisFeature || aDoc->objects()->isLater(aModifierFeat, aThisFeature))
1112         continue; // the modifier feature is later than this, so, should not be used
1113       if (aCurrentModifierFeat == aModifierFeat || aDoc->objects()->isLater(aCurrentModifierFeat, aModifierFeat))
1114         continue; // the current modifier is later than the found, so, useless
1115       Handle(TNaming_NamedShape) aNewNS;
1116       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1117       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1118         aModifierResFound = aModifierObj;
1119         aCurrentModifierFeat = aModifierFeat;
1120         TNaming_Iterator aPairIter(aNewNS);
1121         aNewShape = aPairIter.NewShape();
1122         /*
1123         // searching for sub-shape equivalent on the sub-label of the new context result
1124         TDF_ChildIDIterator aNSIter(aNewNS->Label(), TNaming_NamedShape::GetID());
1125         for(; aNSIter.More(); aNSIter.Next()) {
1126           TNaming_Iterator aPairsIter(aNSIter.Value()->Label());
1127           for(; aPairsIter.More(); aPairsIter.Next()) {
1128             if (aSubShape->impl<TopoDS_Shape>().IsEqual()
1129           }
1130         }*/
1131         anIterate = true;
1132         break;
1133       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is null
1134         ResultPtr anEmptyContext;
1135         std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1136         setValue(anEmptyContext, anEmptyShape); // nullify the selection
1137         return;
1138       } else { // not-precessed modification => don't support it
1139         continue;
1140       }
1141     }
1142
1143     /*
1144     TNaming_NewShapeIterator aModifIter(aPairIter.NewShape(), aContLab);
1145     if (aModifIter.More()) aModifIter.Next(); // skip this shape result
1146     for(; aModifIter.More(); aModifIter.Next()) {
1147       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1148         (aDoc->objects()->object(aModifIter.Label().Father()));
1149       if (!aModifierObj.get())
1150         break;
1151       FeaturePtr aModifierFeat = aDoc->feature(aModifierObj);
1152       if (!aModifierFeat.get())
1153         break;
1154       if (aModifierFeat == aThisFeature || aDoc->objects()->isLater(aModifierFeat, aThisFeature))
1155         break; // the modifier feature is later than this, so, should not be used
1156       Handle(TNaming_NamedShape) aNewNS = aModifIter.NamedShape();
1157       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1158         aModifierResFound = aModifierObj;
1159       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is null
1160         ResultPtr anEmptyContext;
1161         std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1162         setValue(anEmptyContext, anEmptyShape); // nullify the selection
1163         return;
1164       } else { // not-precessed modification => don't support it
1165         break;
1166       }
1167     }
1168     // already found what is needed, don't iterate the next pair since normally
1169     if (aModifierResFound.get()) //  there must be only one pair in the result-shape
1170       break;
1171     */
1172   }
1173   if (aModifierResFound.get()) {
1174     // update scope to reset to a new one
1175     myScope.Clear();
1176     myRef.setValue(aModifierResFound);
1177     update(); // it must recompute a new sub-shape automatically
1178   }
1179   /*
1180   if (aModifierResFound.get()) {
1181     // update scope to reset to a new one
1182     myScope.Clear();
1183     if (!aSubShape.get() || aSubShape->isNull()) { // no sub-shape, so, just update a context
1184       setValue(aModifierResFound, aSubShape);
1185       return;
1186     }
1187     // seaching for the same sub-shape: the old topology stays the same
1188     TopoDS_Shape anOldShape = aSubShape->impl<TopoDS_Shape>();
1189     TopAbs_ShapeEnum aSubType = anOldShape.ShapeType();
1190     TopoDS_Shape aNewContext = aModifierResFound->shape()->impl<TopoDS_Shape>();
1191     TopExp_Explorer anExp(aNewContext, aSubType);
1192     for(; anExp.More(); anExp.Next()) {
1193       if (anExp.Current().IsEqual(anOldShape))
1194         break;
1195     }
1196     if (anExp.More()) { // found
1197       setValue(aModifierResFound, aSubShape);
1198       return;
1199     }
1200     // seaching for the same sub-shape: equal geometry
1201     for(anExp.Init(aNewContext, aSubType); anExp.More(); anExp.Next()) {
1202       if (aSubType == TopAbs_VERTEX) {
1203
1204       }
1205     }
1206   }*/
1207   // if sub-shape selection exists, search also sub-shape new instance
1208   /*
1209   GeomShapePtr aSubShape = value();
1210   if (aSubShape.get() && aSubShape != aContext->shape()) {
1211
1212   }*/
1213 }