Salome HOME
Issue #1837: make all files with UNIX end lines
[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     TopoDS_Shape anOldShape = aSelector.NamedShape()->Get();
440     bool aResult = aSelector.Solve(scope()) == Standard_True;
441     aResult = setInvalidIfFalse(aSelLab, aResult); // must be before sending of updated attribute (1556)
442     if (!anOldShape.IsEqual(aSelector.NamedShape()->Get())) // send updated if shape is changed
443       owner()->data()->sendAttributeUpdated(this);
444     return aResult;
445   } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
446     // construction: identification by the results indexes, recompute faces and
447     // take the face that more close by the indexes
448     ResultConstructionPtr aConstructionContext = 
449       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
450     FeaturePtr aContextFeature = aContext->document()->feature(aContext);
451     // sketch sub-element
452     if (aConstructionContext && 
453         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
454     {
455       TDF_Label aLab = myRef.myRef->Label();
456       // getting a type of selected shape
457       Handle(TDataStd_Integer) aTypeAttr;
458       if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
459         return setInvalidIfFalse(aSelLab, false);
460       }
461       TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
462       // selected indexes will be needed in each "if"
463       Handle(TDataStd_IntPackedMap) aSubIds;
464       std::shared_ptr<GeomAPI_Shape> aNewSelected;
465       bool aNoIndexes = 
466         !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
467       // for now working only with composite features
468       CompositeFeaturePtr aComposite = 
469         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
470       if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
471         return setInvalidIfFalse(aSelLab, false);
472       }
473
474       if (aShapeType == TopAbs_FACE || aShapeType == TopAbs_WIRE) { // compound is for the whole sketch selection
475         // If this is a wire with plane defined then it is a sketch-like object
476         if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
477           return setInvalidIfFalse(aSelLab, false);
478         // if there is no edges indexes, any face can be used: take the first
479         std::shared_ptr<GeomAPI_Shape> aNewSelected;
480         if (aNoIndexes) {
481           aNewSelected = aConstructionContext->face(0);
482         } else { // searching for most looks-like initial face by the indexes
483           // prepare edges of the current result for the fast searching
484           NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
485           const int aSubNum = aComposite->numberOfSubs();
486           for(int a = 0; a < aSubNum; a++) {
487             int aSubID = aComposite->subFeatureId(a);
488             if (aSubIds->Contains(aSubID)) {
489               FeaturePtr aSub = aComposite->subFeature(a);
490               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
491               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
492               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
493                 ResultConstructionPtr aConstr = 
494                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
495                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
496                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
497                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
498                   if (!anEdge.IsNull()) {
499                     Standard_Real aFirst, aLast;
500                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
501                     // searching for orientation information
502                     int anOrient = 0;
503                     Handle(TDataStd_Integer) anInt;
504                     if (aSelLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)){
505                       anOrient = anInt->Get();
506                     }
507                     allCurves.Bind(aCurve, anOrient);
508                   }
509                 }
510               }
511             }
512           }
513           aNewSelected = Model_SelectionNaming::findAppropriateFace(
514             aContext, allCurves, aShapeType == TopAbs_WIRE);
515         }
516         if (aNewSelected) { // store this new selection
517           selectConstruction(aContext, aNewSelected);
518           setInvalidIfFalse(aSelLab, true);
519           owner()->data()->sendAttributeUpdated(this);
520           return true;
521         } else { // if the selection is not found, put the empty shape: it's better to have disappeared shape, than the old, the lost one
522           TNaming_Builder anEmptyBuilder(selectionLabel());
523           return setInvalidIfFalse(aSelLab, false);
524         }
525       } else if (aShapeType == TopAbs_EDGE) {
526         // just reselect the edge by the id
527         const int aSubNum = aComposite->numberOfSubs();
528         for(int a = 0; a < aSubNum; a++) {
529           // if aSubIds take any, the first appropriate
530           if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
531             // found the appropriate feature
532             FeaturePtr aFeature = aComposite->subFeature(a);
533             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
534               aFeature->results().cbegin();
535             for(;aResIter != aFeature->results().cend(); aResIter++) {
536               ResultConstructionPtr aRes = 
537                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
538               if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
539                 selectConstruction(aContext, aRes->shape());
540                 setInvalidIfFalse(aSelLab, true);
541                 owner()->data()->sendAttributeUpdated(this);
542                 return true;
543               }
544             }
545           }
546         }
547       } else if (aShapeType == TopAbs_VERTEX) {
548         // just reselect the vertex by the id of edge
549         const int aSubNum = aComposite->numberOfSubs();
550         for(int a = 0; a < aSubNum; a++) {
551           // if aSubIds take any, the first appropriate
552           int aFeatureID = aComposite->subFeatureId(a);
553           if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
554             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
555             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
556               // searching for deltas
557               int aVertexNum = 0;
558               if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
559               else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
560               // found the feature with appropriate edge
561               FeaturePtr aFeature = aComposite->subFeature(a);
562               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
563                 aFeature->results().cbegin();
564               for(;aResIter != aFeature->results().cend(); aResIter++) {
565                 ResultConstructionPtr aRes = 
566                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
567                 if (aRes && aRes->shape()) {
568                   if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
569                     selectConstruction(aContext, aRes->shape());
570                     setInvalidIfFalse(aSelLab, true);
571                     owner()->data()->sendAttributeUpdated(this);
572                     return true;
573                   } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
574                     const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
575                     int aVIndex = 1;
576                     for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
577                       if (aVIndex == aVertexNum) { // found!
578                         std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
579                         aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
580                         selectConstruction(aContext, aVertex);
581                         setInvalidIfFalse(aSelLab, true);
582                         owner()->data()->sendAttributeUpdated(this);
583                         return true;
584                       }
585                       aVIndex++;
586                     }
587                   }
588                 }
589               }
590           }
591         }
592       }
593     } else { // simple construction element: the selected is that needed
594       selectConstruction(aContext, aContext->shape());
595       setInvalidIfFalse(aSelLab, true);
596       owner()->data()->sendAttributeUpdated(this);
597       return true;
598     }
599   }
600   return setInvalidIfFalse(aSelLab, false); // unknown case
601 }
602
603 void Model_AttributeSelection::selectBody(
604   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
605 {
606   // perform the selection
607   TNaming_Selector aSel(selectionLabel());
608   TopoDS_Shape aContext;
609
610   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
611   if (aBody) {
612     aContext = aBody->shape()->impl<TopoDS_Shape>();
613   } else {
614     ResultPtr aResult = 
615       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
616     if (aResult) {
617       aContext = aResult->shape()->impl<TopoDS_Shape>();
618     } else {
619       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
620       return;
621     }
622   }
623
624   // with "recover" feature the selected context may be not up to date (issue 1710)
625   Handle(TNaming_NamedShape) aResult;
626   TDF_Label aSelLab = selectionLabel();
627   TopoDS_Shape aNewContext = aContext;
628   bool isUpdated = true;
629   while(!aNewContext.IsNull() && isUpdated) { // searching for the very last shape that was produced from this one
630     isUpdated = false;
631     if (!TNaming_Tool::HasLabel(aSelLab, aNewContext)) // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
632       break;
633     for(TNaming_SameShapeIterator anIter(aNewContext, aSelLab); anIter.More(); anIter.Next()) {
634       TDF_Label aNSLab = anIter.Label();
635       if (!scope().Contains(aNSLab))
636         continue;
637       Handle(TNaming_NamedShape) aNS;
638       if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
639         for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
640           if (aShapesIter.Evolution() == TNaming_SELECTED)
641             continue; // don't use the selection evolution
642           if (!aShapesIter.OldShape().IsNull() && aShapesIter.OldShape().IsSame(aNewContext)) {
643              // found the original shape
644             aNewContext = aShapesIter.NewShape(); // go to the newer shape
645             isUpdated = true;
646             break;
647           }
648         }
649       }
650     }
651   }
652   if (aNewContext.IsNull()) { // a context is already deleted
653     setInvalidIfFalse(aSelLab, false);
654     Events_InfoMessage("Model_AttributeSelection", "Failed to select shape already deleted").send();
655     return;
656   }
657
658   TopoDS_Shape aNewSub = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
659   if (!aNewSub.IsEqual(aContext)) { // searching for subshape in the new context
660     bool isFound = false;
661     TopExp_Explorer anExp(aNewContext, aNewSub.ShapeType());
662     for(; anExp.More(); anExp.Next()) {
663       if (anExp.Current().IsEqual(aNewSub)) {
664         isFound = true;
665         break;
666       }
667     }
668     if (!isFound) { // sub-shape is not found in the up-to-date instance of the context shape
669       setInvalidIfFalse(aSelLab, false);
670       Events_InfoMessage("Model_AttributeSelection", "Failed to select sub-shape already modified").send();
671       return;
672     }
673   }
674
675
676   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
677   FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
678   if (aFeatureOwner.get())
679     aFeatureOwner->eraseResults();
680   if (!aContext.IsNull()) {
681     aSel.Select(aNewSub, aNewContext); 
682   }
683 }
684
685 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
686 /// if theID is zero, 
687 /// theOrientation is additional information about the positioning of edge relatively to face
688 ///    it is stored in the integer attribute of the edge sub-label: 
689 ///    -1 is out, 1 is in, 0 is not needed
690 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
691   const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
692   std::string theAdditionalName, std::map<int, int>& theOrientations,
693   std::map<int, std::string>& theSubNames, // name of sub-elements by ID to be exported instead of indexes
694   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)(),
695   const int theOrientation = 0)
696 {
697   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
698   if (theOrientation != 0) { // store the orientation of edge relatively to face if needed
699     TDataStd_Integer::Set(aLab, theOrientation);
700   }
701   TNaming_Builder aBuilder(aLab);
702   aBuilder.Generated(theShape);
703   std::stringstream aName;
704   // add the part name if the selected object is located in other part
705   if (theDoc != theContextFeature->document()) {
706     if (theContextFeature->document() == ModelAPI_Session::get()->moduleDocument()) {
707       aName<<theContextFeature->document()->kind()<<"/";
708     } else {
709       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
710         ModelAPI_Session::get()->moduleDocument(), theContextFeature->document());
711       if (aDocRes.get()) {
712         aName<<aDocRes->data()->name()<<"/";
713       }
714     }
715   }
716   aName<<theContextFeature->name();
717   if (theShape.ShapeType() != TopAbs_COMPOUND) { // compound means the whole result for construction
718     aName<<"/";
719     if (!theAdditionalName.empty())
720       aName<<theAdditionalName<<"/";
721     if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
722     else if (theShape.ShapeType() == TopAbs_WIRE) aName<<"Wire";
723     else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
724     else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
725
726     if (theRefs.IsNull()) {
727       aName<<theID;
728       if (theOrientation == 1)
729         aName<<"f";
730       else if (theOrientation == -1)
731         aName<<"r";
732     } else { // make a composite name from all sub-elements indexes: "1_2_3_4"
733       TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
734       for(; aRef.More(); aRef.Next()) {
735         aName<<"-"<<theSubNames[aRef.Key()];
736         if (theOrientations.find(aRef.Key()) != theOrientations.end()) {
737           if (theOrientations[aRef.Key()] == 1)
738             aName<<"f";
739           else if (theOrientations[aRef.Key()] == -1)
740             aName<<"r";
741         }
742       }
743     }
744   }
745
746   theDoc->addNamingName(aLab, aName.str());
747   TDataStd_Name::Set(aLab, aName.str().c_str());
748 }
749
750 void Model_AttributeSelection::selectConstruction(
751   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
752 {
753   std::shared_ptr<Model_Document> aMyDoc = 
754     std::dynamic_pointer_cast<Model_Document>(owner()->document());
755   FeaturePtr aContextFeature = theContext->document()->feature(theContext);
756   CompositeFeaturePtr aComposite = 
757     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
758   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
759   if (!aComposite || aComposite->numberOfSubs() == 0) {
760     // saving of context is enough: result construction contains exactly the needed shape
761     TNaming_Builder aBuilder(selectionLabel());
762     aBuilder.Generated(aSubShape);
763     std::string aName = contextName(theContext);
764     aMyDoc->addNamingName(selectionLabel(), aName);
765     TDataStd_Name::Set(selectionLabel(), aName.c_str());
766     return;
767   }
768   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
769   TDF_Label aLab = myRef.myRef->Label();
770   // identify the results of sub-object of the composite by edges
771   // save type of the selected shape in integer attribute
772   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
773   TDataStd_Integer::Set(aLab, (int)aShapeType);
774   gp_Pnt aVertexPos;
775   TColStd_MapOfTransient allCurves;
776   if (aShapeType == TopAbs_VERTEX) { // compare positions
777     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
778   } else { 
779     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
780       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
781       Standard_Real aFirst, aLast;
782       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
783       allCurves.Add(aCurve);
784     }
785   }
786   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
787   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
788   std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
789   std::map<int, std::string> aSubNames; //map from edges IDs to names of edges
790   aRefs->Clear();
791   const int aSubNum = aComposite->numberOfSubs();
792   for(int a = 0; a < aSubNum; a++) {
793     FeaturePtr aSub = aComposite->subFeature(a);
794     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
795     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
796     // there may be many shapes (circle and center): register if at least one is in selection
797     for(; aRes != aResults.cend(); aRes++) {
798       ResultConstructionPtr aConstr = 
799         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
800       if (!aConstr->shape()) {
801         continue;
802       }
803       if (aShapeType == TopAbs_VERTEX) {
804         if (aConstr->shape()->isVertex()) { // compare vertices positions
805           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
806           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
807           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
808             aRefs->Add(aComposite->subFeatureId(a));
809             aSubNames[aComposite->subFeatureId(a)] = Model_SelectionNaming::shortName(aConstr);
810           }
811         } else { // get first or last vertex of the edge: last is stored with additional delta
812           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
813           int aDelta = kSTART_VERTEX_DELTA;
814           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
815             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
816             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
817               aRefs->Add(aDelta + aComposite->subFeatureId(a));
818               aSubNames[aDelta + aComposite->subFeatureId(a)] =
819                 Model_SelectionNaming::shortName(aConstr, aDelta / kSTART_VERTEX_DELTA);
820               break;
821             }
822             aDelta += kSTART_VERTEX_DELTA;
823           }
824         }
825       } else {
826         if (aConstr->shape()->isEdge()) {
827           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
828           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
829           if (!anEdge.IsNull()) {
830             Standard_Real aFirst, aLast;
831             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
832             if (allCurves.Contains(aCurve)) {
833               int anID = aComposite->subFeatureId(a);
834               aRefs->Add(anID);
835               aSubNames[anID] = Model_SelectionNaming::shortName(aConstr);
836               if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
837                 // add edges to sub-label to support naming for edges selection
838                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
839                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
840                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
841                   Standard_Real aFirst, aLast;
842                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
843                   if (aFaceCurve == aCurve) {
844                     int anOrient = Model_SelectionNaming::edgeOrientation(aSubShape, anEdge);
845                     anOrientations[anID] = anOrient;
846                     registerSubShape(
847                       selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "", anOrientations,
848                       aSubNames, Handle(TDataStd_IntPackedMap)(), anOrient);
849                   }
850                 }
851               } else { // put vertices of the selected edge to sub-labels
852                 // add edges to sub-label to support naming for edges selection
853                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
854                 int aTagIndex = anID + kSTART_VERTEX_DELTA;
855                 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
856                   TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
857
858                   std::stringstream anAdditionalName; 
859                   registerSubShape(
860                     selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc, "", anOrientations,
861                     aSubNames);
862                 }
863               }
864             }
865           }
866         }
867       }
868     }
869   }
870   // store the selected as primitive
871   TNaming_Builder aBuilder(selectionLabel());
872   aBuilder.Generated(aSubShape);
873     registerSubShape(
874       selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", anOrientations, aSubNames, aRefs); 
875 }
876
877 bool Model_AttributeSelection::selectPart(
878   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
879   const bool theUpdate)
880 {
881   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
882   if (!aPart.get() || !aPart->isActivated())
883     return true; // postponed naming
884   if (theUpdate) {
885     Handle(TDataStd_Integer) anIndex;
886     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) { // by internal selection
887       if (anIndex->Get() > 0) {
888         // update the selection by index
889         return aPart->updateInPart(anIndex->Get());
890       } else {
891         return true; // nothing to do, referencing just by name
892       }
893     }
894     return true; // nothing to do, referencing just by name
895   }
896   // store the shape (in case part is not loaded it should be useful
897   TopoDS_Shape aShape;
898   std::string aName = theContext->data()->name();
899   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
900     aShape = theContext->shape()->impl<TopoDS_Shape>();
901   } else {
902     aShape = theSubShape->impl<TopoDS_Shape>();
903     int anIndex;
904     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
905     TDataStd_Integer::Set(selectionLabel(), anIndex);
906   }
907   TNaming_Builder aBuilder(selectionLabel());
908   aBuilder.Select(aShape, aShape);
909   // identify by name in the part
910   TDataStd_Name::Set(selectionLabel(), aName.c_str());
911   return !aName.empty();
912 }
913
914 TDF_Label Model_AttributeSelection::selectionLabel()
915 {
916   return myRef.myRef->Label().FindChild(1);
917 }
918
919 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
920 {
921   std::string aName("");
922   if(!this->isInitialized())
923     return !theDefaultName.empty() ? theDefaultName : aName;
924
925   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
926   ResultPtr aCont = context();
927
928   Model_SelectionNaming aSelNaming(selectionLabel());
929   return aSelNaming.namingName(
930     aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
931 }
932
933 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
934 void Model_AttributeSelection::selectSubShape(
935   const std::string& theType, const std::string& theSubShapeName)
936 {
937   if(theSubShapeName.empty() || theType.empty()) return;
938
939   // check this is Part-name: 2 delimiters in the name
940   std::size_t aPartEnd = theSubShapeName.find('/');
941   if (aPartEnd != string::npos && aPartEnd != theSubShapeName.rfind('/')) {
942     std::string aPartName = theSubShapeName.substr(0, aPartEnd);
943     ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
944     if (aFound.get()) { // found such part, so asking it for the name
945       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
946       string aNameInPart = theSubShapeName.substr(aPartEnd + 1);
947       int anIndex;
948       std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, theType, anIndex);
949       if (aSelected.get()) {
950         setValue(aPart, aSelected);
951         TDataStd_Integer::Set(selectionLabel(), anIndex);
952         return;
953       }
954     }
955   }
956
957   Model_SelectionNaming aSelNaming(selectionLabel());
958   std::shared_ptr<Model_Document> aDoc = 
959     std::dynamic_pointer_cast<Model_Document>(owner()->document());
960   std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
961   ResultPtr aCont;
962   if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
963     // try to find the last context to find the up to dat shape
964     if (aCont->shape().get() && !aCont->shape()->isNull() &&
965       aCont->groupName() == ModelAPI_ResultBody::group() && aDoc == owner()->document()) {
966       const TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
967       if (!aConShape.IsNull()) {
968         Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
969         if (!aNS.IsNull()) {
970           aNS = TNaming_Tool::CurrentNamedShape(aNS);
971           if (!aNS.IsNull()) {
972             TDF_Label aLab = aNS->Label();
973             while(aLab.Depth() != 7 && aLab.Depth() > 5)
974               aLab = aLab.Father();
975             ObjectPtr anObj = aDoc->objects()->object(aLab);
976             if (anObj.get()) {
977               ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
978               if (aRes)
979                 aCont = aRes;
980             }
981           }
982         }
983       }
984     }
985     setValue(aCont, aShapeToBeSelected);
986   }
987 }
988
989 int Model_AttributeSelection::Id()
990 {
991   int anID = 0;
992   std::shared_ptr<GeomAPI_Shape> aSelection = value();
993   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
994   // support for compsolids:
995   if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
996     aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
997
998
999   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1000   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1001   // searching for the latest main shape
1002   if (aSelection && !aSelection->isNull() &&
1003     aContext   && !aContext->isNull())
1004   {
1005     std::shared_ptr<Model_Document> aDoc =
1006       std::dynamic_pointer_cast<Model_Document>(context()->document());
1007     if (aDoc.get()) {
1008       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1009       if (!aNS.IsNull()) {
1010         aMainShape = TNaming_Tool::CurrentShape(aNS);
1011       }
1012     }
1013
1014     TopTools_IndexedMapOfShape aSubShapesMap;
1015     TopExp::MapShapes(aMainShape, aSubShapesMap);
1016     anID = aSubShapesMap.FindIndex(aSubShape);
1017   }
1018   return anID;
1019 }
1020
1021 void Model_AttributeSelection::setId(int theID)
1022 {
1023   const ResultPtr& aContext = context();
1024   std::shared_ptr<GeomAPI_Shape> aSelection;
1025
1026   std::shared_ptr<GeomAPI_Shape> aContextShape = aContext->shape();
1027   // support for compsolids:
1028   if (aContext.get() && ModelAPI_Tools::compSolidOwner(aContext).get())
1029     aContextShape = ModelAPI_Tools::compSolidOwner(aContext)->shape();
1030
1031   TopoDS_Shape aMainShape = aContextShape->impl<TopoDS_Shape>();
1032   // searching for the latest main shape
1033   if (theID > 0 &&
1034       aContextShape && !aContextShape->isNull())
1035   {
1036     std::shared_ptr<Model_Document> aDoc =
1037       std::dynamic_pointer_cast<Model_Document>(aContext->document());
1038     if (aDoc.get()) {
1039       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1040       if (!aNS.IsNull()) {
1041         aMainShape = TNaming_Tool::CurrentShape(aNS);
1042       }
1043     }
1044
1045     TopTools_IndexedMapOfShape aSubShapesMap;
1046     TopExp::MapShapes(aMainShape, aSubShapesMap);
1047     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1048
1049     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1050     aResult->setImpl(new TopoDS_Shape(aSelShape));
1051
1052     aSelection = aResult;
1053   }
1054
1055   setValue(aContext, aSelection);
1056 }
1057
1058 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1059 {
1060   std::string aResult;
1061   if (owner()->document() != theContext->document()) {
1062     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1063       aResult = theContext->document()->kind() + "/";
1064     } else {
1065       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1066         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1067       if (aDocRes.get()) {
1068         aResult = aDocRes->data()->name() + "/";
1069       }
1070     }
1071   }
1072   aResult += theContext->data()->name();
1073   return aResult;
1074 }