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