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