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