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