Salome HOME
Merge branch 'master' into Dev_1.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.h
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 <ModelAPI_Feature.h>
13 #include <ModelAPI_ResultBody.h>
14 #include <ModelAPI_ResultConstruction.h>
15 #include <ModelAPI_CompositeFeature.h>
16 #include <GeomAPI_Shape.h>
17 #include <GeomAPI_PlanarEdges.h>
18 #include <Events_Error.h>
19
20 #include <TNaming_Selector.hxx>
21 #include <TNaming_NamedShape.hxx>
22 #include <TNaming_Tool.hxx>
23 #include <TNaming_Builder.hxx>
24 #include <TNaming_Localizer.hxx>
25 #include <TopoDS_Shape.hxx>
26 #include <TopoDS_Compound.hxx>
27 #include <TDataStd_IntPackedMap.hxx>
28 #include <TDataStd_Integer.hxx>
29 #include <TDataStd_UAttribute.hxx>
30 #include <TDataStd_Name.hxx>
31 #include <TopTools_MapOfShape.hxx>
32 #include <TopTools_IndexedMapOfShape.hxx>
33 #include <TopTools_MapIteratorOfMapOfShape.hxx>
34 #include <TopTools_ListOfShape.hxx>
35 #include <TopExp_Explorer.hxx>
36 #include <TDF_LabelMap.hxx>
37 #include <BRep_Tool.hxx>
38 #include <BRep_Builder.hxx>
39 #include <TopoDS_Edge.hxx>
40 #include <TopoDS.hxx>
41 #include <TopExp.hxx>
42 #include <TColStd_MapOfTransient.hxx>
43 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
44 #include <TopTools_ListIteratorOfListOfShape.hxx>
45 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
46 #include <gp_Pnt.hxx>
47 #include <Precision.hxx>
48 #include <TDF_ChildIterator.hxx>
49 #include <TDF_ChildIDIterator.hxx>
50 #include <TDataStd_Name.hxx>
51 #include <TopAbs_ShapeEnum.hxx>
52 #include <TopoDS_Iterator.hxx>
53 #include <TNaming_Iterator.hxx>
54 using namespace std;
55 //#define DEB_NAMING 1
56 #ifdef DEB_NAMING
57 #include <BRepTools.hxx>
58 #endif
59 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
60 /// (multiplied by the index of the edge)
61 static const int kSTART_VERTEX_DELTA = 1000000;
62 // identifier that there is simple reference: selection equals to context
63 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
64 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
65
66 // on this label is stored:
67 // TNaming_NamedShape - selected shape
68 // TNaming_Naming - topological selection information (for the body)
69 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
70 // TDataStd_Integer - type of the selected shape (for construction)
71 // TDF_Reference - from ReferenceAttribute, the context
72 #define DDDD 1
73 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
74   const std::shared_ptr<GeomAPI_Shape>& theSubShape)
75 {
76   const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
77   bool isOldContext = theContext == myRef.value();
78   bool isOldShape = isOldContext &&
79     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
80   if (isOldShape) return; // shape is the same, so context is also unchanged
81   // update the referenced object if needed
82   if (!isOldContext)
83     myRef.setValue(theContext);
84
85   // do noth use naming if selected shape is result shape itself, but not sub-shape
86   TDF_Label aSelLab = selectionLabel();
87   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
88   aSelLab.ForgetAttribute(kCONSTUCTION_SIMPLE_REF_ID);
89
90   bool isDegeneratedEdge = false;
91   // do not use the degenerated edge as a shape, a null context and shape is used in the case
92   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
93     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
94     if (aSubShape.ShapeType() == TopAbs_EDGE)
95       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape));
96   }
97   if (!theContext.get() || isDegeneratedEdge) {
98     // to keep the reference attribute label
99     TDF_Label aRefLab = myRef.myRef->Label();
100     aSelLab.ForgetAllAttributes(true);
101     myRef.myRef = TDF_Reference::Set(aSelLab, aSelLab);
102     return;
103   }
104   if (theContext->groupName() == ModelAPI_ResultBody::group()) {
105     // do not select the whole shape for body:it is already must be in the data framework
106     if (theContext->shape().get() && theContext->shape()->isEqual(theSubShape)) {
107       aSelLab.ForgetAllAttributes(true);
108       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
109     } else {
110       selectBody(theContext, theSubShape);
111     }
112   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
113     if (!theSubShape.get()) {
114       // to sub, so the whole result is selected
115       aSelLab.ForgetAllAttributes(true);
116       TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
117     } else {
118       selectConstruction(theContext, theSubShape);
119     }
120   }
121   myIsInitialized = true;
122
123   std::string aSelName = namingName();
124   if(!aSelName.empty())
125     TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
126 #ifdef DDDD
127   //####
128   //selectSubShape("FACE",  "Extrusion_1/LateralFace_3");
129   //selectSubShape("FACE",  "Extrusion_1/TopFace");
130   //selectSubShape("EDGE", "Extrusion_1/TopFace|Extrusion_1/LateralFace_1");
131   //selectSubShape("EDGE", "Sketch_1/Edge_6");
132 #endif
133   owner()->data()->sendAttributeUpdated(this);
134 }
135
136 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
137 {
138   std::shared_ptr<GeomAPI_Shape> aResult;
139   if (myIsInitialized) {
140     TDF_Label aSelLab = selectionLabel();
141     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
142       ResultPtr aContext = context();
143       if (!aContext.get()) 
144         return aResult; // empty result
145       return aContext->shape();
146     }
147     if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
148         return aResult; // empty result
149     }
150
151     Handle(TNaming_NamedShape) aSelection;
152     if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
153       TopoDS_Shape aSelShape = aSelection->Get();
154       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
155       aResult->setImpl(new TopoDS_Shape(aSelShape));
156     } else { // for simple construction element: just shape of this construction element
157       ResultConstructionPtr aConstr = 
158         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
159       if (aConstr) {
160         return aConstr->shape();
161       }
162     }
163   }
164   return aResult;
165 }
166
167 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
168   : myRef(theLabel)
169 {
170   myIsInitialized = myRef.isInitialized();
171 }
172
173 ResultPtr Model_AttributeSelection::context() {
174   return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
175 }
176
177
178 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
179 {
180   ModelAPI_AttributeSelection::setObject(theObject);
181   myRef.setObject(theObject);
182 }
183
184 TDF_LabelMap& Model_AttributeSelection::scope()
185 {
186   if (myScope.IsEmpty()) { // create a new scope if not yet done
187     // gets all labels with named shapes that are bofore this feature label (before in history)
188     TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
189       owner()->data())->label().Father();
190     int aFeatureID = aFeatureLab.Tag();
191     TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
192     for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
193       if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
194         break;
195       TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
196       for(; aNSIter.More(); aNSIter.Next()) {
197         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
198         if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
199           myScope.Add(aNS->Label());
200         }
201       }
202     }
203   }
204   return myScope;
205 }
206
207 bool Model_AttributeSelection::update()
208 {
209   ResultPtr aContext = context();
210   if (!aContext.get()) return false;
211   TDF_Label aSelLab = selectionLabel();
212   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
213     return aContext->shape() && !aContext->shape()->isNull();
214   }
215   if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
216     return aContext->shape() && !aContext->shape()->isNull();
217   }
218
219   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
220     // body: just a named shape, use selection mechanism from OCCT
221     TNaming_Selector aSelector(aSelLab);
222     bool aResult = aSelector.Solve(scope()) == Standard_True;
223     owner()->data()->sendAttributeUpdated(this);
224     return aResult;
225   } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
226     // construction: identification by the results indexes, recompute faces and
227     // take the face that more close by the indexes
228     ResultConstructionPtr aConstructionContext = 
229       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
230     FeaturePtr aContextFeature = aContext->document()->feature(aContext);
231     // sketch sub-element
232     if (aConstructionContext && 
233         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
234     {
235       TDF_Label aLab = myRef.myRef->Label();
236       // getting a type of selected shape
237       Handle(TDataStd_Integer) aTypeAttr;
238       if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
239         return false;
240       }
241       TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
242       // selected indexes will be needed in each "if"
243       Handle(TDataStd_IntPackedMap) aSubIds;
244       std::shared_ptr<GeomAPI_Shape> aNewSelected;
245       bool aNoIndexes = 
246         !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
247       // for now working only with composite features
248       CompositeFeaturePtr aComposite = 
249         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
250       if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
251         return false;
252       }
253
254       if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
255         // If this is a wire with plane defined thin it is a sketch-like object
256         if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
257           return false;
258         // if there is no edges indexes, any face can be used: take the first
259         std::shared_ptr<GeomAPI_Shape> aNewSelected;
260         if (aNoIndexes) {
261           aNewSelected = aConstructionContext->face(0);
262         } else { // searching for most looks-like initial face by the indexes
263           // prepare edges of the current resut for the fast searching
264           TColStd_MapOfTransient allCurves;
265           const int aSubNum = aComposite->numberOfSubs();
266           for(int a = 0; a < aSubNum; a++) {
267             if (aSubIds->Contains(aComposite->subFeatureId(a))) {
268               FeaturePtr aSub = aComposite->subFeature(a);
269               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
270               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
271               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
272                 ResultConstructionPtr aConstr = 
273                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
274                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
275                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
276                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
277                   if (!anEdge.IsNull()) {
278                     Standard_Real aFirst, aLast;
279                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
280                     allCurves.Add(aCurve);
281                   }
282                 }
283               }
284             }
285           }
286           double aBestFound = 0; // best percentage of found edges
287           for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
288             int aFound = 0, aNotFound = 0;
289             TopExp_Explorer anEdgesExp(
290               aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>(), TopAbs_EDGE);
291             for(; anEdgesExp.More(); anEdgesExp.Next()) {
292               TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
293               if (!anEdge.IsNull()) {
294                 Standard_Real aFirst, aLast;
295                 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
296                 if (allCurves.Contains(aCurve)) {
297                   aFound++;
298                 } else {
299                   aNotFound++;
300                 }
301               }
302             }
303             if (aFound + aNotFound != 0) {
304               double aPercentage = double(aFound) / double(aFound + aNotFound);
305               if (aPercentage > aBestFound) {
306                 aBestFound = aPercentage;
307                 aNewSelected = aConstructionContext->face(aFaceIndex);
308               }
309             }
310           }
311         }
312         if (aNewSelected) { // store this new selection
313           selectConstruction(aContext, aNewSelected);
314           owner()->data()->sendAttributeUpdated(this);
315           return true;
316         }
317       } else if (aShapeType == TopAbs_EDGE) {
318         // just reselect the edge by the id
319         const int aSubNum = aComposite->numberOfSubs();
320         for(int a = 0; a < aSubNum; a++) {
321           // if aSubIds take any, the first appropriate
322           if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
323             // found the appropriate feature
324             FeaturePtr aFeature = aComposite->subFeature(a);
325             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
326               aFeature->results().cbegin();
327             for(;aResIter != aFeature->results().cend(); aResIter++) {
328               ResultConstructionPtr aRes = 
329                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
330               if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
331                 selectConstruction(aContext, aRes->shape());
332                 owner()->data()->sendAttributeUpdated(this);
333                 return true;
334               }
335             }
336           }
337         }
338       } else if (aShapeType == TopAbs_VERTEX) {
339         // just reselect the vertex by the id of edge
340         const int aSubNum = aComposite->numberOfSubs();
341         for(int a = 0; a < aSubNum; a++) {
342           // if aSubIds take any, the first appropriate
343           int aFeatureID = aComposite->subFeatureId(a);
344           if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
345             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
346             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
347               // searching for deltas
348               int aVertexNum = 0;
349               if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
350               else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
351               // found the feature with appropriate edge
352               FeaturePtr aFeature = aComposite->subFeature(a);
353               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
354                 aFeature->results().cbegin();
355               for(;aResIter != aFeature->results().cend(); aResIter++) {
356                 ResultConstructionPtr aRes = 
357                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
358                 if (aRes && aRes->shape()) {
359                   if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
360                     selectConstruction(aContext, aRes->shape());
361                     owner()->data()->sendAttributeUpdated(this);
362                     return true;
363                   } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
364                     const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
365                     int aVIndex = 1;
366                     for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
367                       if (aVIndex == aVertexNum) { // found!
368                         std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
369                         aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
370                         selectConstruction(aContext, aVertex);
371                         owner()->data()->sendAttributeUpdated(this);
372                         return true;
373                       }
374                       aVIndex++;
375                     }
376                   }
377                 }
378               }
379           }
380         }
381       }
382     } else { // simple construction element: the selected is that needed
383       selectConstruction(aContext, aContext->shape());
384       owner()->data()->sendAttributeUpdated(this);
385       return true;
386     }
387   }
388   return false; // unknown case
389 }
390
391
392 void Model_AttributeSelection::selectBody(
393   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
394 {
395   // perform the selection
396   TNaming_Selector aSel(selectionLabel());
397   TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
398   TopoDS_Shape aContext;
399
400   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
401   if (aBody) {
402     aContext = aBody->shape()->impl<TopoDS_Shape>();
403   } else {
404     ResultConstructionPtr aConstr = 
405       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
406     if (aConstr) {
407       aContext = aConstr->shape()->impl<TopoDS_Shape>();
408     } else {
409       Events_Error::send("A result with shape is expected");
410       return;
411     }
412   }
413   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
414   FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
415   if (aFeatureOwner.get())
416     aFeatureOwner->eraseResults();
417
418   aSel.Select(aNewShape, aContext); 
419 }
420
421 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
422 /// if theID is zero, 
423 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
424   const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
425   std::string theAdditionalName,
426   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
427 {
428   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
429   TNaming_Builder aBuilder(aLab);
430   aBuilder.Generated(theShape);
431   std::stringstream aName;
432   aName<<theContextFeature->name()<<"/";
433   if (!theAdditionalName.empty())
434     aName<<theAdditionalName<<"/";
435   if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
436   else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
437   else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
438
439   if (theRefs.IsNull()) {
440     aName<<theID;
441   } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
442     TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
443     for(; aRef.More(); aRef.Next()) {
444       aName<<"-"<<aRef.Key();
445     }
446   }
447
448   theDoc->addNamingName(aLab, aName.str());
449   TDataStd_Name::Set(aLab, aName.str().c_str());
450 }
451
452 void Model_AttributeSelection::selectConstruction(
453   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
454 {
455   std::shared_ptr<Model_Document> aMyDoc = 
456     std::dynamic_pointer_cast<Model_Document>(owner()->document());
457   FeaturePtr aContextFeature = theContext->document()->feature(theContext);
458   CompositeFeaturePtr aComposite = 
459     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
460   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
461   if (!aComposite || aComposite->numberOfSubs() == 0) {
462     // saving of context is enough: result construction contains exactly the needed shape
463     TNaming_Builder aBuilder(selectionLabel());
464     aBuilder.Generated(aSubShape);
465     aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
466     TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
467     return;
468   }
469   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
470   TDF_Label aLab = myRef.myRef->Label();
471   // identify the reuslts of sub-object of the composite by edges
472   // save type of the selected shape in integer attribute
473   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
474   TDataStd_Integer::Set(aLab, (int)aShapeType);
475   gp_Pnt aVertexPos;
476   TColStd_MapOfTransient allCurves;
477   if (aShapeType == TopAbs_VERTEX) { // compare positions
478     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
479   } else { 
480     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
481       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
482       Standard_Real aFirst, aLast;
483       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
484       allCurves.Add(aCurve);
485     }
486   }
487   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
488   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
489   aRefs->Clear();
490   const int aSubNum = aComposite->numberOfSubs();
491   for(int a = 0; a < aSubNum; a++) {
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 = aResults.cbegin();
495     // there may be many shapes (circle and center): register if at least one is in selection
496     for(; aRes != aResults.cend(); aRes++) {
497       ResultConstructionPtr aConstr = 
498         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
499       if (!aConstr->shape()) {
500         continue;
501       }
502       if (aShapeType == TopAbs_VERTEX) {
503         if (aConstr->shape()->isVertex()) { // compare vertices positions
504           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
505           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
506           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
507             aRefs->Add(aComposite->subFeatureId(a));
508           }
509         } else { // get first or last vertex of the edge: last is stored with negative sign
510           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
511           int aDelta = kSTART_VERTEX_DELTA;
512           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
513             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
514             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
515               aRefs->Add(aDelta + aComposite->subFeatureId(a));
516               break;
517             }
518             aDelta += kSTART_VERTEX_DELTA;
519           }
520         }
521       } else {
522         if (aConstr->shape()->isEdge()) {
523           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
524           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
525           if (!anEdge.IsNull()) {
526             Standard_Real aFirst, aLast;
527             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
528             if (allCurves.Contains(aCurve)) {
529               int anID = aComposite->subFeatureId(a);
530               aRefs->Add(anID);
531               if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
532                 // add edges to sub-label to support naming for edges selection
533                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
534                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
535                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
536                   Standard_Real aFirst, aLast;
537                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
538                   if (aFaceCurve == aCurve) {
539                     registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
540                   }
541                 }
542               } else { // put vertices of the selected edge to sub-labels
543                 // add edges to sub-label to support naming for edges selection
544                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
545                 int aTagIndex = anID + kSTART_VERTEX_DELTA;
546                 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
547                   TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
548
549                   std::stringstream anAdditionalName; 
550                   registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
551                     "");
552                 }
553               }
554             }
555           }
556         }
557       }
558     }
559   }
560   // store the selected as primitive
561   TNaming_Builder aBuilder(selectionLabel());
562   aBuilder.Generated(aSubShape);
563   registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
564 }
565
566 TDF_Label Model_AttributeSelection::selectionLabel()
567 {
568   return myRef.myRef->Label().FindChild(1);
569 }
570
571 #define FIX_BUG1 1
572 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape, 
573   const TDF_Label& theLabel)
574 {
575   std::string aName;
576   // check if the subShape is already in DF
577   Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
578   Handle(TDataStd_Name) anAttr;
579   if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document    
580     if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
581       aName = TCollection_AsciiString(anAttr->Get()).ToCString();
582       if(!aName.empty()) {          
583         const TDF_Label& aLabel = theDoc->findNamingName(aName);
584         /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
585         if(!aLabel.IsEqual(aNS->Label())) {
586         //aName.erase(); //something is wrong, to be checked!!!
587         aName += "_SomethingWrong";
588         return aName;
589         }*/
590
591         static const std::string aPostFix("_");
592         TNaming_Iterator anItL(aNS);
593         for(int i = 1; anItL.More(); anItL.Next(), i++) {
594           if(anItL.NewShape() == theShape) {
595             aName += aPostFix;
596             aName += TCollection_AsciiString (i).ToCString();
597             break;
598           }
599         }
600         /* MPV: the code below does not work because of TNaming_Tool.cxx line 145: aNS->Get() uses maps
601         const TopoDS_Shape& aShape = aNS->Get();
602         if(aShape.ShapeType() == TopAbs_COMPOUND) {
603         std::string aPostFix("_");
604         TopoDS_Iterator it(aShape);                     
605         for (int i = 1;it.More();it.Next(), i++) {
606         if(it.Value() == theShape) {
607         aPostFix += TCollection_AsciiString (i).ToCString();
608         aName    += aPostFix;
609         break;
610         }
611         else continue;                                          
612         }
613         }
614         */
615       } 
616     }
617   }
618   return aName;
619 }
620
621 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
622 {
623   // a trivial case: F1 & F2,  aNumber = 1, i.e. intersection gives 1 edge.
624   TopoDS_Compound aCmp;
625   BRep_Builder BB;
626   BB.MakeCompound(aCmp);
627   TopTools_ListIteratorOfListOfShape it(theAncestors);
628   for(;it.More();it.Next()) {
629     BB.Add(aCmp, it.Value());
630     theSMap.Add(it.Value());
631   }
632   int aNumber(0);
633   TopTools_IndexedDataMapOfShapeListOfShape aMap2;
634   TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
635   for (int i = 1; i <= aMap2.Extent(); i++) {
636     const TopoDS_Shape& aKey = aMap2.FindKey(i);
637     const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
638     if(anAncestors.Extent() > 1) aNumber++;
639   }
640   if(aNumber > 1) return false;
641   return true;
642 }
643 std::string Model_AttributeSelection::namingName()
644 {
645   std::string aName("");
646   if(!this->isInitialized()) return aName;
647   Handle(TDataStd_Name) anAtt;
648   if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
649     aName = TCollection_AsciiString(anAtt->Get()).ToCString();
650     return aName;
651   }
652
653   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
654   ResultPtr aCont = context();
655   aName = "Undefined name";
656   if(!aCont.get() || aCont->shape()->isNull()) 
657     return aName;
658   if (!aSubSh.get() || aSubSh->isNull()) { // no subshape, so just the whole feature name
659     return aCont->data()->name();
660   }
661   TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
662   TopoDS_Shape aContext  = aCont->shape()->impl<TopoDS_Shape>();
663 #ifdef DEB_NAMING
664   if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
665   BRepTools::Write(aSubShape, "Selection.brep");
666   BRepTools::Write(aContext, "Context.brep");
667   }
668 #endif
669   std::shared_ptr<Model_Document> aDoc = 
670     std::dynamic_pointer_cast<Model_Document>(aCont->document());
671
672   // check if the subShape is already in DF
673   aName = GetShapeName(aDoc, aSubShape, selectionLabel());
674   if(aName.empty() ) { // not in the document!
675     TopAbs_ShapeEnum aType = aSubShape.ShapeType();
676     switch (aType) {
677     case TopAbs_FACE:
678       // the Face should be in DF. If it is not the case, it is an error ==> to be debugged             
679                 break;
680           case TopAbs_EDGE:
681                   {
682                   // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
683                   // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces    
684                   if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
685                           aName = "Degenerated_Edge";
686                           break;
687                   }    
688                   TopTools_IndexedDataMapOfShapeListOfShape aMap;
689                   TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
690                   TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
691                   bool isTrivialCase(true);
692 /*                for (int i = 1; i <= aMap.Extent(); i++) {
693                         const TopoDS_Shape& aKey = aMap.FindKey(i);
694                         //if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
695                         if (aKey.IsSame(aSubShape)) continue;
696             const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
697                         // check that it is not a trivial case (F1 & F2: aNumber = 1)
698                         isTrivialCase = isTrivial(anAncestors, aSMap);                  
699                         break;
700                   }*/
701                   if(aMap.Contains(aSubShape)) {
702                         const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
703                         // check that it is not a trivial case (F1 & F2: aNumber = 1)
704                         isTrivialCase = isTrivial(anAncestors, aSMap);          
705                   } else 
706                           break;
707                   TopTools_ListOfShape aListOfNbs;
708                   if(!isTrivialCase) { // find Neighbors
709                         TNaming_Localizer aLocalizer;
710                         TopTools_MapOfShape aMap3;
711                         aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
712                         //int n = aMap3.Extent();
713                         TopTools_MapIteratorOfMapOfShape it(aMap3);
714                         for(;it.More();it.Next()) {
715                           const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
716                           //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
717                           const TopTools_ListOfShape& aList  = aMap.FindFromKey(aNbShape);
718                           TopTools_ListIteratorOfListOfShape it2(aList);
719                           for(;it2.More();it2.Next()) {
720                                 if(aSMap.Contains(it2.Value())) continue; // skip this Face
721                                 aListOfNbs.Append(it2.Value());
722                           }
723                         }
724                   }  // else a trivial case
725                   
726                   // build name of the sub-shape Edge
727                   for(int i=1; i <= aSMap.Extent(); i++) {
728                         const TopoDS_Shape& aFace = aSMap.FindKey(i);
729                         std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
730                         if(i == 1)
731                           aName = aFaceName;
732                         else 
733                           aName += "|" + aFaceName;
734                   }
735                   TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
736                   for (;itl.More();itl.Next()) {
737                         std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
738                         aName += "|" + aFaceName;
739                   }               
740                   }
741                   break;
742
743     case TopAbs_VERTEX:
744       // name structure (Monifold Topology): 
745       // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
746       // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
747       // 2) F1 | F2      - intersection of 2 faces definses a vertex - applicable for case
748       //                   when 1 faces is cylindrical, conical, spherical or revolution and etc.
749       // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
750       //                   or compound of 2 open faces.
751       // 4) E1 | E2      - intesection of 2 edges defines a vertex - when we have a case of 
752       //                   two independent edges (wire or compound)
753       // implemented 2 first cases
754       {
755         TopTools_IndexedDataMapOfShapeListOfShape aMap;
756         TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
757         const TopTools_ListOfShape& aList2  = aMap.FindFromKey(aSubShape);
758         TopTools_ListOfShape aList;
759         TopTools_MapOfShape aFMap;
760 #ifdef FIX_BUG1
761         //int n = aList2.Extent(); //bug! duplication
762         // fix is below
763         TopTools_ListIteratorOfListOfShape itl2(aList2);
764         for (int i = 1;itl2.More();itl2.Next(),i++) {
765           if(aFMap.Add(itl2.Value()))
766             aList.Append(itl2.Value());
767         }
768         //n = aList.Extent();
769 #endif
770         int n = aList.Extent();
771         if(n < 3) { // open topology case or Compound case => via edges
772           TopTools_IndexedDataMapOfShapeListOfShape aMap;
773           TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
774           const TopTools_ListOfShape& aList22  = aMap.FindFromKey(aSubShape);
775           if(aList22.Extent() >= 2)  { // regular solution
776 #ifdef FIX_BUG1
777
778             // bug! duplication; fix is below
779             aFMap.Clear();
780             TopTools_ListOfShape aListE;
781             TopTools_ListIteratorOfListOfShape itl2(aList22);
782             for (int i = 1;itl2.More();itl2.Next(),i++) {
783               if(aFMap.Add(itl2.Value()))
784                 aListE.Append(itl2.Value());
785             }
786             n = aListE.Extent();
787 #endif
788             TopTools_ListIteratorOfListOfShape itl(aListE);
789             for (int i = 1;itl.More();itl.Next(),i++) {
790               const TopoDS_Shape& anEdge = itl.Value();
791               std::string anEdgeName = GetShapeName(aDoc, anEdge, selectionLabel());
792               if(i == 1)
793                 aName = anEdgeName;
794               else 
795                 aName += "|" + anEdgeName;
796             }
797           }//reg
798           else { // dangle vertex: if(aList22.Extent() == 1)
799             //it should be already in DF
800           }
801         } 
802         else {
803           TopTools_ListIteratorOfListOfShape itl(aList);
804           for (int i = 1;itl.More();itl.Next(),i++) {
805             const TopoDS_Shape& aFace = itl.Value();
806             std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
807             if(i == 1)
808               aName = aFaceName;
809             else 
810               aName += "|" + aFaceName;
811           }
812         }
813       }
814       break;
815     }
816     // register name                    
817     // aDoc->addNamingName(selectionLabel(), aName);
818     // the selected sub-shape will not be shared and as result it will not require registration
819   }
820   return aName;
821 }
822
823 TopAbs_ShapeEnum translateType (const std::string& theType)
824 {
825   // map from the textual shape types to OCCT enumeration
826   static std::map<std::string, TopAbs_ShapeEnum> MyShapeTypes;
827   if (MyShapeTypes.size() == 0) {
828     MyShapeTypes["face"] = TopAbs_FACE;
829     MyShapeTypes["faces"] = TopAbs_FACE;
830     MyShapeTypes["vertex"] = TopAbs_VERTEX;
831     MyShapeTypes["vertices"] = TopAbs_VERTEX;
832     MyShapeTypes["wire"] = TopAbs_WIRE;
833     MyShapeTypes["edge"] = TopAbs_EDGE;
834     MyShapeTypes["edges"] = TopAbs_EDGE;
835     MyShapeTypes["shell"] = TopAbs_SHELL;
836     MyShapeTypes["solid"] = TopAbs_SOLID;
837     MyShapeTypes["solids"] = TopAbs_SOLID;
838     MyShapeTypes["FACE"] = TopAbs_FACE;
839     MyShapeTypes["FACES"] = TopAbs_FACE;
840     MyShapeTypes["VERTEX"] = TopAbs_VERTEX;
841     MyShapeTypes["VERTICES"] = TopAbs_VERTEX;
842     MyShapeTypes["WIRE"] = TopAbs_WIRE;
843     MyShapeTypes["EDGE"] = TopAbs_EDGE;
844     MyShapeTypes["EDGES"] = TopAbs_EDGE;
845     MyShapeTypes["SHELL"] = TopAbs_SHELL;
846     MyShapeTypes["SOLID"] = TopAbs_SOLID;
847     MyShapeTypes["SOLIDS"] = TopAbs_SOLID;
848   }
849   if (MyShapeTypes.find(theType) != MyShapeTypes.end())
850     return MyShapeTypes[theType];
851   Events_Error::send("Shape type defined in XML is not implemented!");
852   return TopAbs_SHAPE;
853 }
854
855 const TopoDS_Shape getShapeFromNS(
856   const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
857 {
858   TopoDS_Shape aSelection;
859   std::string::size_type n = theSubShapeName.rfind('/');                        
860   if (n == std::string::npos) n = 0;
861   std::string aSubString = theSubShapeName.substr(n + 1);
862   n = aSubString.rfind('_');
863   if (n == std::string::npos) return aSelection;
864   aSubString = aSubString.substr(n+1);
865   int indx = atoi(aSubString.c_str());
866
867   TNaming_Iterator anItL(theNS);
868   for(int i = 1; anItL.More(); anItL.Next(), i++) {
869     if (i == indx) {
870       return anItL.NewShape();
871     }
872   }
873   return aSelection;    
874 }
875
876 const TopoDS_Shape findFaceByName(
877   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
878 {
879   TopoDS_Shape aFace;
880   std::string::size_type n, nb = theSubShapeName.rfind('/');                    
881   if (nb == std::string::npos) nb = 0;
882   std::string aSubString = theSubShapeName.substr(nb + 1);
883   n = aSubString.rfind('_');
884   if (n != std::string::npos) {
885     std::string aSubStr2 = aSubString.substr(0, n);
886     aSubString  = theSubShapeName.substr(0, nb + 1);
887     aSubString = aSubString + aSubStr2; 
888   } else
889     aSubString = theSubShapeName;
890
891   const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
892   if(aLabel.IsNull()) return aFace;
893   Handle(TNaming_NamedShape) aNS;
894   if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
895     aFace = getShapeFromNS(theSubShapeName, aNS);
896   }
897   return aFace;
898 }
899
900 int ParseName(const std::string& theSubShapeName,   std::list<std::string>& theList)
901 {
902   std::string aName = theSubShapeName;
903   std::string aLastName;
904   int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
905   while ((n2 = aName.find('|', n1)) != std::string::npos) {
906     const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
907     theList.push_back(aName1);  
908     n1 = n2 + 1;
909     aLastName = aName.substr(n1);
910   }
911   if(!aLastName.empty())
912     theList.push_back(aLastName);
913   return theList.size();
914 }
915
916 const TopoDS_Shape findCommonShape(
917   const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
918 {
919   TopoDS_Shape aShape;
920   std::vector<TopTools_MapOfShape> aVec;
921   TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
922   if(theList.Extent() > 1) {
923     aVec.push_back(aMap1);
924     aVec.push_back(aMap2);
925   }
926   if(theList.Extent() > 2)
927     aVec.push_back(aMap3);
928   if(theList.Extent() == 4)
929     aVec.push_back(aMap4);
930
931   //fill maps
932   TopTools_ListIteratorOfListOfShape it(theList);
933   for(int i = 0;it.More();it.Next(),i++) {
934     const TopoDS_Shape& aFace = it.Value();             
935     if(i < 2) {
936       TopExp_Explorer anExp (aFace, theType);
937       for(;anExp.More();anExp.Next()) {
938         const TopoDS_Shape& anEdge = anExp.Current();
939         if (!anEdge.IsNull())
940           aVec[i].Add(anExp.Current());
941       }
942     } else {
943       TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
944       for(;anExp.More();anExp.Next()) {
945         const TopoDS_Shape& aVertex = anExp.Current();
946         if (!aVertex.IsNull())
947           aVec[i].Add(anExp.Current());
948       }
949     }
950   }
951   //trivial case: 2 faces
952   TopTools_ListOfShape aList;
953   TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
954   for(;it2.More();it2.Next()) {
955     if(aVec[1].Contains(it2.Key())) {
956       aShape = it2.Key();
957       if(theList.Extent() == 2)
958         break;
959       else 
960         aList.Append(it2.Key());
961     }
962   }
963   if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors 
964     if(aVec[2].Extent() && aVec[3].Extent()) {
965       TopTools_ListIteratorOfListOfShape it(aList);
966       for(;it.More();it.Next()) {
967         const TopoDS_Shape& aCand = it.Value();
968         // not yet completelly implemented, to be rechecked
969         TopoDS_Vertex aV1, aV2;
970         TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
971         int aNum(0);
972         if(aVec[2].Contains(aV1)) aNum++;
973         else if(aVec[2].Contains(aV2)) aNum++;
974         if(aVec[3].Contains(aV1)) aNum++;
975         else if(aVec[3].Contains(aV2)) aNum++;
976         if(aNum == 2) {
977           aShape = aCand;
978           break;
979         }
980       }
981     }
982   }
983
984   if(aList.Extent() && aVec.size() == 3) {
985
986     TopTools_ListIteratorOfListOfShape it(aList);
987     for(;it.More();it.Next()) {
988       const TopoDS_Shape& aCand = it.Value();
989       if(aVec[2].Contains(aCand)) {
990         aShape = aCand;
991         break;
992       }
993     }
994   }
995   return aShape;
996 }
997
998 std::string getContextName(const std::string& theSubShapeName)
999 {
1000   std::string aName;
1001   std::string::size_type n = theSubShapeName.find('/');                 
1002   if (n == std::string::npos) return aName;
1003   aName = theSubShapeName.substr(0, n);
1004   return aName;
1005 }
1006 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
1007 void Model_AttributeSelection::selectSubShape(
1008   const std::string& theType, const std::string& theSubShapeName)
1009 {
1010   if(theSubShapeName.empty() || theType.empty()) return;
1011   TopAbs_ShapeEnum aType = translateType(theType);
1012   std::shared_ptr<Model_Document> aDoc = 
1013     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1014   std::string aContName = getContextName(theSubShapeName);
1015   if(aContName.empty()) return;
1016   //ResultPtr aCont = context();
1017   ResultPtr aCont = aDoc->findByName(aContName);
1018   if(!aCont.get() || aCont->shape()->isNull()) return;
1019   TopoDS_Shape aContext  = aCont->shape()->impl<TopoDS_Shape>();
1020   TopAbs_ShapeEnum aContType = aContext.ShapeType();
1021   if(aType <= aContType) return; // not applicable
1022
1023
1024   TopoDS_Shape aSelection;
1025   switch (aType) 
1026   {
1027   case TopAbs_COMPOUND:
1028     break;
1029   case TopAbs_COMPSOLID:
1030     break;
1031   case TopAbs_SOLID:
1032     break;
1033   case TopAbs_SHELL:
1034     break;
1035   case TopAbs_FACE:
1036     {
1037       const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
1038       if(!aSelection.IsNull()) {// Select it
1039         std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1040         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1041         setValue(aCont, aShapeToBeSelected);
1042       }
1043     }
1044     break;
1045   case TopAbs_WIRE:
1046     break;
1047   case TopAbs_EDGE:
1048     {  
1049       TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
1050       const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1051       if(!aLabel.IsNull()) {
1052         Handle(TNaming_NamedShape) aNS;
1053         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1054           aSelection = getShapeFromNS(theSubShapeName, aNS);
1055         }
1056       }
1057       if(aSelection.IsNull()) {
1058         std::list<std::string> aListofNames;
1059         int n = ParseName(theSubShapeName, aListofNames);
1060         if(n > 1 && n < 5) {
1061           TopTools_ListOfShape aList;
1062           std::list<std::string>::iterator it =aListofNames.begin();
1063           for(;it != aListofNames.end();it++){
1064             const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1065             aList.Append(aFace);                
1066           }
1067           aSelection = findCommonShape(TopAbs_EDGE, aList);
1068         }
1069       }
1070       if(!aSelection.IsNull()) {// Select it
1071         std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1072         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1073         setValue(aCont, aShapeToBeSelected);
1074       }
1075     }
1076     break;
1077   case TopAbs_VERTEX:
1078     {
1079       TopoDS_Shape aSelection;
1080       const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1081       if(!aLabel.IsNull()) {
1082         Handle(TNaming_NamedShape) aNS;
1083         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1084           aSelection = getShapeFromNS(theSubShapeName, aNS);
1085         }
1086       }
1087       if(aSelection.IsNull()) {
1088         std::list<std::string> aListofNames;
1089         int n = ParseName(theSubShapeName, aListofNames);
1090         if(n > 1 && n < 4) { // 2 || 3
1091           TopTools_ListOfShape aList;
1092           std::list<std::string>::iterator it = aListofNames.begin();
1093           for(; it != aListofNames.end(); it++){
1094             const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1095             if(!aFace.IsNull())
1096               aList.Append(aFace);              
1097           }
1098           aSelection = findCommonShape(TopAbs_VERTEX, aList);
1099         }
1100       }
1101       if(!aSelection.IsNull()) {// Select it
1102         std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1103         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1104         setValue(aCont, aShapeToBeSelected);
1105       }
1106     }
1107     break;
1108   default: //TopAbs_SHAPE
1109     return;
1110   }
1111
1112 }
1113
1114 int Model_AttributeSelection::Id()
1115 {
1116   std::shared_ptr<GeomAPI_Shape> aSelection = value();
1117   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
1118   const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
1119   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1120   int anID = 0;
1121   if (aSelection && !aSelection->isNull() &&
1122     aContext   && !aContext->isNull())
1123   {
1124     TopTools_IndexedMapOfShape aSubShapesMap;
1125     TopExp::MapShapes(aMainShape, aSubShapesMap);
1126     anID = aSubShapesMap.FindIndex(aSubShape);
1127   }
1128   return anID;
1129 }