Salome HOME
Creation of producedByFeature initial implementation neede for the issue #1306
[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 /// added to the index in the packed map to signalize that the vertex of edge is selected
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.get() ? myTmpSubShape : myTmpContext->shape();
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 checks 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 features with named shapes that are before 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     } else {
420       // For correct naming selection, put the shape into the naming structure.
421       // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
422       TNaming_Builder aBuilder(aSelLab);
423       aBuilder.Generated(aContext->shape()->impl<TopoDS_Shape>());
424       std::shared_ptr<Model_Document> aMyDoc = 
425         std::dynamic_pointer_cast<Model_Document>(owner()->document());
426       std::string aName = aContext->data()->name();
427       aMyDoc->addNamingName(aSelLab, aName);
428       TDataStd_Name::Set(aSelLab, aName.c_str());
429     }
430     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
431   }
432
433   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
434     std::shared_ptr<GeomAPI_Shape> aNoSelection;
435     bool aResult = selectPart(aContext, aNoSelection, true);
436     if (aResult) {
437       owner()->data()->sendAttributeUpdated(this);
438     }
439     return setInvalidIfFalse(aSelLab, aResult);
440   }
441
442   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
443     // body: just a named shape, use selection mechanism from OCCT
444     TNaming_Selector aSelector(aSelLab);
445     bool aResult = aSelector.Solve(scope()) == Standard_True;
446     owner()->data()->sendAttributeUpdated(this);
447     return setInvalidIfFalse(aSelLab, aResult);
448   } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
449     // construction: identification by the results indexes, recompute faces and
450     // take the face that more close by the indexes
451     ResultConstructionPtr aConstructionContext = 
452       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
453     FeaturePtr aContextFeature = aContext->document()->feature(aContext);
454     // sketch sub-element
455     if (aConstructionContext && 
456         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
457     {
458       TDF_Label aLab = myRef.myRef->Label();
459       // getting a type of selected shape
460       Handle(TDataStd_Integer) aTypeAttr;
461       if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
462         return setInvalidIfFalse(aSelLab, false);
463       }
464       TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
465       // selected indexes will be needed in each "if"
466       Handle(TDataStd_IntPackedMap) aSubIds;
467       std::shared_ptr<GeomAPI_Shape> aNewSelected;
468       bool aNoIndexes = 
469         !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
470       // for now working only with composite features
471       CompositeFeaturePtr aComposite = 
472         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
473       if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
474         return setInvalidIfFalse(aSelLab, false);
475       }
476
477       if (aShapeType == TopAbs_FACE || aShapeType == TopAbs_WIRE) { // compound is for the whole sketch selection
478         // If this is a wire with plane defined thin it is a sketch-like object
479         if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
480           return setInvalidIfFalse(aSelLab, false);
481         // if there is no edges indexes, any face can be used: take the first
482         std::shared_ptr<GeomAPI_Shape> aNewSelected;
483         if (aNoIndexes) {
484           aNewSelected = aConstructionContext->face(0);
485         } else { // searching for most looks-like initial face by the indexes
486           // prepare edges of the current result for the fast searching
487           NCollection_DataMap<Handle(Geom_Curve), int> allCurves; // curves and orientations of edges
488           const int aSubNum = aComposite->numberOfSubs();
489           for(int a = 0; a < aSubNum; a++) {
490             int aSubID = aComposite->subFeatureId(a);
491             if (aSubIds->Contains(aSubID)) {
492               FeaturePtr aSub = aComposite->subFeature(a);
493               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
494               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
495               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
496                 ResultConstructionPtr aConstr = 
497                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
498                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
499                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
500                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
501                   if (!anEdge.IsNull()) {
502                     Standard_Real aFirst, aLast;
503                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
504                     // searching for orientation information
505                     int anOrient = 0;
506                     Handle(TDataStd_Integer) anInt;
507                     if (aSelLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)){
508                       anOrient = anInt->Get();
509                     }
510                     allCurves.Bind(aCurve, anOrient);
511                   }
512                 }
513               }
514             }
515           }
516           int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
517           int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
518           for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
519             int aFound = 0, aNotFound = 0, aSameOrientation = 0;
520             TopoDS_Face aFace = 
521               TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
522             TopExp_Explorer anEdgesExp(aFace, TopAbs_EDGE);
523             TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
524             for(; anEdgesExp.More(); anEdgesExp.Next()) {
525               TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
526               if (!anEdge.IsNull()) {
527                 Standard_Real aFirst, aLast;
528                 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
529                 if (alreadyProcessed.Contains(aCurve))
530                   continue;
531                 alreadyProcessed.Add(aCurve);
532                 if (allCurves.IsBound(aCurve)) {
533                   aFound++;
534                   int anOrient = allCurves.Find(aCurve);
535                   if (anOrient != 0) {  // extra comparision score is orientation
536                     if (edgeOrientation(aFace, anEdge) == anOrient)
537                       aSameOrientation++;
538                   }
539                 } else {
540                   aNotFound++;
541                 }
542               }
543             }
544             if (aFound + aNotFound != 0) {
545               if (aFound > aBestFound || 
546                   (aFound == aBestFound && aSameOrientation > aBestOrient)) {
547                 aBestFound = aFound;
548                 aBestOrient = aSameOrientation;
549                 aNewSelected = aConstructionContext->face(aFaceIndex);
550               }
551             }
552           }
553         }
554         if (aNewSelected) { // store this new selection
555           if (aShapeType == TopAbs_WIRE) { // just get a wire from face to have wire
556             TopExp_Explorer aWireExp(aNewSelected->impl<TopoDS_Shape>(), TopAbs_WIRE);
557             if (aWireExp.More()) {
558               aNewSelected.reset(new GeomAPI_Shape);
559               aNewSelected->setImpl<TopoDS_Shape>(new TopoDS_Shape(aWireExp.Current()));
560             }
561           }
562           selectConstruction(aContext, aNewSelected);
563           owner()->data()->sendAttributeUpdated(this);
564           return setInvalidIfFalse(aSelLab, true);
565         } else { // if the selection is not found, put the empty shape: it's better to have disappeared shape, than the old, the lost one
566           TNaming_Builder anEmptyBuilder(selectionLabel());
567           return setInvalidIfFalse(aSelLab, false);
568         }
569       } else if (aShapeType == TopAbs_EDGE) {
570         // just reselect the edge by the id
571         const int aSubNum = aComposite->numberOfSubs();
572         for(int a = 0; a < aSubNum; a++) {
573           // if aSubIds take any, the first appropriate
574           if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
575             // found the appropriate feature
576             FeaturePtr aFeature = aComposite->subFeature(a);
577             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
578               aFeature->results().cbegin();
579             for(;aResIter != aFeature->results().cend(); aResIter++) {
580               ResultConstructionPtr aRes = 
581                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
582               if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
583                 selectConstruction(aContext, aRes->shape());
584                 owner()->data()->sendAttributeUpdated(this);
585                 return setInvalidIfFalse(aSelLab, true);
586               }
587             }
588           }
589         }
590       } else if (aShapeType == TopAbs_VERTEX) {
591         // just reselect the vertex by the id of edge
592         const int aSubNum = aComposite->numberOfSubs();
593         for(int a = 0; a < aSubNum; a++) {
594           // if aSubIds take any, the first appropriate
595           int aFeatureID = aComposite->subFeatureId(a);
596           if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
597             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
598             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
599               // searching for deltas
600               int aVertexNum = 0;
601               if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
602               else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
603               // found the feature with appropriate edge
604               FeaturePtr aFeature = aComposite->subFeature(a);
605               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
606                 aFeature->results().cbegin();
607               for(;aResIter != aFeature->results().cend(); aResIter++) {
608                 ResultConstructionPtr aRes = 
609                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
610                 if (aRes && aRes->shape()) {
611                   if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
612                     selectConstruction(aContext, aRes->shape());
613                     owner()->data()->sendAttributeUpdated(this);
614                     return setInvalidIfFalse(aSelLab, true);
615                   } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
616                     const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
617                     int aVIndex = 1;
618                     for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
619                       if (aVIndex == aVertexNum) { // found!
620                         std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
621                         aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
622                         selectConstruction(aContext, aVertex);
623                         owner()->data()->sendAttributeUpdated(this);
624                         return setInvalidIfFalse(aSelLab, true);
625                       }
626                       aVIndex++;
627                     }
628                   }
629                 }
630               }
631           }
632         }
633       }
634     } else { // simple construction element: the selected is that needed
635       selectConstruction(aContext, aContext->shape());
636       owner()->data()->sendAttributeUpdated(this);
637       return setInvalidIfFalse(aSelLab, true);
638     }
639   }
640   return setInvalidIfFalse(aSelLab, false); // unknown case
641 }
642
643
644 void Model_AttributeSelection::selectBody(
645   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
646 {
647   // perform the selection
648   TNaming_Selector aSel(selectionLabel());
649   TopoDS_Shape aContext;
650
651   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
652   if (aBody) {
653     aContext = aBody->shape()->impl<TopoDS_Shape>();
654   } else {
655     ResultPtr aResult = 
656       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
657     if (aResult) {
658       aContext = aResult->shape()->impl<TopoDS_Shape>();
659     } else {
660       Events_Error::send("A result with shape is expected");
661       return;
662     }
663   }
664   TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
665   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
666   FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
667   if (aFeatureOwner.get())
668     aFeatureOwner->eraseResults();
669   if (!aContext.IsNull()) {
670     aSel.Select(aNewShape, aContext); 
671   }
672 }
673
674 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
675 /// if theID is zero, 
676 /// theOrientation is additional information about the positioning of edge relatively to face
677 ///    it is stored in the integer attribute of the edge sub-label: 
678 ///    -1 is out, 1 is in, 0 is not needed
679 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
680   const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
681   std::string theAdditionalName, std::map<int, int>& theOrientations,
682   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)(),
683   const int theOrientation = 0)
684 {
685   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
686   if (theOrientation != 0) { // store the orientation of edge relatively to face if needed
687     TDataStd_Integer::Set(aLab, theOrientation);
688   }
689   TNaming_Builder aBuilder(aLab);
690   aBuilder.Generated(theShape);
691   std::stringstream aName;
692   aName<<theContextFeature->name()<<"/";
693   if (!theAdditionalName.empty())
694     aName<<theAdditionalName<<"/";
695   if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
696   else if (theShape.ShapeType() == TopAbs_WIRE) aName<<"Wire";
697   else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
698   else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
699
700   if (theRefs.IsNull()) {
701     aName<<theID;
702     if (theOrientation == 1)
703       aName<<"f";
704     else if (theOrientation == -1)
705       aName<<"r";
706   } else { // make a composite name from all sub-elements indexes: "1_2_3_4"
707     TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
708     for(; aRef.More(); aRef.Next()) {
709       aName<<"-"<<aRef.Key();
710       if (theOrientations.find(aRef.Key()) != theOrientations.end()) {
711         if (theOrientations[aRef.Key()] == 1)
712           aName<<"f";
713         else if (theOrientations[aRef.Key()] == -1)
714           aName<<"r";
715       }
716     }
717   }
718
719   theDoc->addNamingName(aLab, aName.str());
720   TDataStd_Name::Set(aLab, aName.str().c_str());
721 }
722
723 void Model_AttributeSelection::selectConstruction(
724   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
725 {
726   std::shared_ptr<Model_Document> aMyDoc = 
727     std::dynamic_pointer_cast<Model_Document>(owner()->document());
728   FeaturePtr aContextFeature = theContext->document()->feature(theContext);
729   CompositeFeaturePtr aComposite = 
730     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
731   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
732   if (!aComposite || aComposite->numberOfSubs() == 0) {
733     // saving of context is enough: result construction contains exactly the needed shape
734     TNaming_Builder aBuilder(selectionLabel());
735     aBuilder.Generated(aSubShape);
736     aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
737     TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
738     return;
739   }
740   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
741   TDF_Label aLab = myRef.myRef->Label();
742   // identify the results of sub-object of the composite by edges
743   // save type of the selected shape in integer attribute
744   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
745   TDataStd_Integer::Set(aLab, (int)aShapeType);
746   gp_Pnt aVertexPos;
747   TColStd_MapOfTransient allCurves;
748   if (aShapeType == TopAbs_VERTEX) { // compare positions
749     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
750   } else { 
751     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
752       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
753       Standard_Real aFirst, aLast;
754       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
755       allCurves.Add(aCurve);
756     }
757   }
758   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
759   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
760   std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
761   aRefs->Clear();
762   const int aSubNum = aComposite->numberOfSubs();
763   for(int a = 0; a < aSubNum; a++) {
764     FeaturePtr aSub = aComposite->subFeature(a);
765     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
766     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
767     // there may be many shapes (circle and center): register if at least one is in selection
768     for(; aRes != aResults.cend(); aRes++) {
769       ResultConstructionPtr aConstr = 
770         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
771       if (!aConstr->shape()) {
772         continue;
773       }
774       if (aShapeType == TopAbs_VERTEX) {
775         if (aConstr->shape()->isVertex()) { // compare vertices positions
776           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
777           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
778           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
779             aRefs->Add(aComposite->subFeatureId(a));
780           }
781         } else { // get first or last vertex of the edge: last is stored with negative sign
782           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
783           int aDelta = kSTART_VERTEX_DELTA;
784           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
785             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
786             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
787               aRefs->Add(aDelta + aComposite->subFeatureId(a));
788               break;
789             }
790             aDelta += kSTART_VERTEX_DELTA;
791           }
792         }
793       } else {
794         if (aConstr->shape()->isEdge()) {
795           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
796           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
797           if (!anEdge.IsNull()) {
798             Standard_Real aFirst, aLast;
799             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
800             if (allCurves.Contains(aCurve)) {
801               int anID = aComposite->subFeatureId(a);
802               aRefs->Add(anID);
803               if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
804                 // add edges to sub-label to support naming for edges selection
805                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
806                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
807                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
808                   Standard_Real aFirst, aLast;
809                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
810                   if (aFaceCurve == aCurve) {
811                     int anOrient = edgeOrientation(aSubShape, anEdge);
812                     anOrientations[anID] = anOrient;
813                     registerSubShape(
814                       selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "", anOrientations,
815                       Handle(TDataStd_IntPackedMap)(), anOrient);
816                   }
817                 }
818               } else { // put vertices of the selected edge to sub-labels
819                 // add edges to sub-label to support naming for edges selection
820                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
821                 int aTagIndex = anID + kSTART_VERTEX_DELTA;
822                 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
823                   TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
824
825                   std::stringstream anAdditionalName; 
826                   registerSubShape(
827                     selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc, "", anOrientations);
828                 }
829               }
830             }
831           }
832         }
833       }
834     }
835   }
836   // store the selected as primitive
837   TNaming_Builder aBuilder(selectionLabel());
838   aBuilder.Generated(aSubShape);
839     registerSubShape(
840       selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", anOrientations, aRefs); 
841 }
842
843 bool Model_AttributeSelection::selectPart(
844   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
845   const bool theUpdate)
846 {
847   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
848   if (!aPart.get() || !aPart->isActivated())
849     return true; // postponed naming
850   if (theUpdate) {
851     Handle(TDataStd_Integer) anIndex;
852     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) { // by internal selection
853       if (anIndex->Get() > 0) {
854         // update the selection by index
855         return aPart->updateInPart(anIndex->Get());
856       } else {
857         return true; // nothing to do, referencing just by name
858       }
859     }
860     return true; // nothing to do, referencing just by name
861   }
862   // store the shape (in case part is not loaded it should be useful
863   TopoDS_Shape aShape;
864   std::string aName = theContext->data()->name();
865   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
866     aShape = theContext->shape()->impl<TopoDS_Shape>();
867   } else {
868     aShape = theSubShape->impl<TopoDS_Shape>();
869     int anIndex;
870     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
871     TDataStd_Integer::Set(selectionLabel(), anIndex);
872   }
873   TNaming_Builder aBuilder(selectionLabel());
874   aBuilder.Select(aShape, aShape);
875   // identify by name in the part
876   TDataStd_Name::Set(selectionLabel(), aName.c_str());
877   return !aName.empty();
878 }
879
880 TDF_Label Model_AttributeSelection::selectionLabel()
881 {
882   return myRef.myRef->Label().FindChild(1);
883 }
884
885 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
886 {
887   std::string aName("");
888   if(!this->isInitialized())
889     return !theDefaultName.empty() ? theDefaultName : aName;
890   Handle(TDataStd_Name) anAtt;
891   if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
892     aName = TCollection_AsciiString(anAtt->Get()).ToCString();
893     return aName;
894   }
895
896   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
897   ResultPtr aCont = context();
898
899   Model_SelectionNaming aSelNaming(selectionLabel());
900   return aSelNaming.namingName(aCont, aSubSh, theDefaultName);
901 }
902
903 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
904 void Model_AttributeSelection::selectSubShape(
905   const std::string& theType, const std::string& theSubShapeName)
906 {
907   if(theSubShapeName.empty() || theType.empty()) return;
908
909   // check this is Part-name: 2 delimiters in the name
910   std::size_t aPartEnd = theSubShapeName.find('/');
911   if (aPartEnd != string::npos && aPartEnd != theSubShapeName.rfind('/')) {
912     std::string aPartName = theSubShapeName.substr(0, aPartEnd);
913     ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
914     if (aFound.get()) { // found such part, so asking it for the name
915       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
916       string aNameInPart = theSubShapeName.substr(aPartEnd + 1);
917       int anIndex;
918       std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, theType, anIndex);
919       if (aSelected.get()) {
920         setValue(aPart, aSelected);
921         TDataStd_Integer::Set(selectionLabel(), anIndex);
922         return;
923       }
924     }
925   }
926
927   Model_SelectionNaming aSelNaming(selectionLabel());
928   std::shared_ptr<Model_Document> aDoc = 
929     std::dynamic_pointer_cast<Model_Document>(owner()->document());
930   std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
931   ResultPtr aCont;
932   if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
933     setValue(aCont, aShapeToBeSelected);
934   }
935 }
936
937 int Model_AttributeSelection::Id()
938 {
939   int anID = 0;
940   std::shared_ptr<GeomAPI_Shape> aSelection = value();
941   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
942   // support for compsolids:
943   if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
944     aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
945
946
947   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
948   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
949   // searching for the latest main shape
950   if (aSelection && !aSelection->isNull() &&
951     aContext   && !aContext->isNull())
952   {
953     std::shared_ptr<Model_Document> aDoc =
954       std::dynamic_pointer_cast<Model_Document>(context()->document());
955     if (aDoc.get()) {
956       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
957       if (!aNS.IsNull()) {
958         aMainShape = TNaming_Tool::CurrentShape(aNS);
959       }
960     }
961
962     TopTools_IndexedMapOfShape aSubShapesMap;
963     TopExp::MapShapes(aMainShape, aSubShapesMap);
964     anID = aSubShapesMap.FindIndex(aSubShape);
965   }
966   return anID;
967 }