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