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