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