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