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