]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
f8be8ab4dfb82ead5673a574c2a6cbac1c208a76
[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 using namespace std;
54 //#define DEB_NAMING 1
55 #ifdef DEB_NAMING
56 #include <BRepTools.hxx>
57 #endif
58 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
59 /// (multiplied by the index of the edge)
60 static const int kSTART_VERTEX_DELTA = 1000000;
61 // identifier that there is simple reference: selection equals to context
62 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
63 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
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 isOldContext = theContext == myRef.value();
77   bool isOldShape = isOldContext &&
78     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
79   if (isOldShape) return; // shape is the same, so context is also unchanged
80   // update the referenced object if needed
81   if (!isOldContext)
82     myRef.setValue(theContext);
83
84   // do noth use naming if selected shape is result shape itself, but not sub-shape
85   TDF_Label aSelLab = selectionLabel();
86   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
87   aSelLab.ForgetAttribute(kCONSTUCTION_SIMPLE_REF_ID);
88
89   bool isDegeneratedEdge = false;
90   // do not use the degenerated edge as a shape, a null context and shape is used in the case
91   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
92     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
93     if (aSubShape.ShapeType() == TopAbs_EDGE)
94       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape));
95   }
96   if (!theContext.get() || isDegeneratedEdge) {
97     // to keep the reference attribute label
98     TDF_Label aRefLab = myRef.myRef->Label();
99     aSelLab.ForgetAllAttributes(true);
100     myRef.myRef = TDF_Reference::Set(aSelLab, aSelLab);
101     return;
102   }
103   if (theContext->groupName() == ModelAPI_ResultBody::group()) {
104     // do not select the whole shape for body:it is already must be in the data framework
105     if (theContext->shape().get() && theContext->shape()->isEqual(theSubShape)) {
106       aSelLab.ForgetAllAttributes(true);
107       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
108     } else {
109       selectBody(theContext, theSubShape);
110     }
111   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
112     if (!theSubShape.get()) {
113       // to sub, so the whole result is selected
114       aSelLab.ForgetAllAttributes(true);
115       TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
116     } else {
117       selectConstruction(theContext, theSubShape);
118     }
119   }
120   //the attribute initialized state should be changed by sendAttributeUpdated only
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 = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
405     if (aConstr) {
406       aContext = aConstr->shape()->impl<TopoDS_Shape>();
407     } else {
408       Events_Error::send("A result with shape is expected");
409       return;
410     }
411   }
412   //BRepTools::Write(aNewShape, "Selection0.brep");
413   aSel.Select(aNewShape, aContext); 
414 }
415
416 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
417 /// if theID is zero, 
418 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
419   const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
420   std::string theAdditionalName,
421   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
422 {
423   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
424   TNaming_Builder aBuilder(aLab);
425   aBuilder.Generated(theShape);
426   std::stringstream aName;
427   aName<<theContextFeature->name()<<"/";
428   if (!theAdditionalName.empty())
429     aName<<theAdditionalName<<"/";
430   if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
431   else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
432   else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
433
434   if (theRefs.IsNull()) {
435     aName<<theID;
436   } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
437     TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
438     for(; aRef.More(); aRef.Next()) {
439       aName<<"-"<<aRef.Key();
440     }
441   }
442
443   theDoc->addNamingName(aLab, aName.str());
444   TDataStd_Name::Set(aLab, aName.str().c_str());
445 }
446
447 void Model_AttributeSelection::selectConstruction(
448     const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
449 {
450   std::shared_ptr<Model_Document> aMyDoc = 
451     std::dynamic_pointer_cast<Model_Document>(owner()->document());
452   FeaturePtr aContextFeature = theContext->document()->feature(theContext);
453   CompositeFeaturePtr aComposite = 
454     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
455   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
456   if (!aComposite || aComposite->numberOfSubs() == 0) {
457     // saving of context is enough: result construction contains exactly the needed shape
458     TNaming_Builder aBuilder(selectionLabel());
459     aBuilder.Generated(aSubShape);
460     aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
461     TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
462     return;
463   }
464   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
465   TDF_Label aLab = myRef.myRef->Label();
466   // identify the reuslts of sub-object of the composite by edges
467   // save type of the selected shape in integer attribute
468   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
469   TDataStd_Integer::Set(aLab, (int)aShapeType);
470   gp_Pnt aVertexPos;
471   TColStd_MapOfTransient allCurves;
472   if (aShapeType == TopAbs_VERTEX) { // compare positions
473     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
474   } else { 
475     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
476       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
477       Standard_Real aFirst, aLast;
478       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
479       allCurves.Add(aCurve);
480     }
481   }
482   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
483   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
484   aRefs->Clear();
485   const int aSubNum = aComposite->numberOfSubs();
486   for(int a = 0; a < aSubNum; a++) {
487     FeaturePtr aSub = aComposite->subFeature(a);
488     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
489     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
490     // there may be many shapes (circle and center): register if at least one is in selection
491     for(; aRes != aResults.cend(); aRes++) {
492       ResultConstructionPtr aConstr = 
493         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
494       if (!aConstr->shape()) {
495         continue;
496       }
497       if (aShapeType == TopAbs_VERTEX) {
498         if (aConstr->shape()->isVertex()) { // compare vertices positions
499           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
500           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
501           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
502             aRefs->Add(aComposite->subFeatureId(a));
503           }
504         } else { // get first or last vertex of the edge: last is stored with negative sign
505           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
506           int aDelta = kSTART_VERTEX_DELTA;
507           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
508             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
509             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
510               aRefs->Add(aDelta + aComposite->subFeatureId(a));
511               break;
512             }
513             aDelta += kSTART_VERTEX_DELTA;
514           }
515         }
516       } else {
517         if (aConstr->shape()->isEdge()) {
518           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
519           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
520           if (!anEdge.IsNull()) {
521             Standard_Real aFirst, aLast;
522             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
523             if (allCurves.Contains(aCurve)) {
524               int anID = aComposite->subFeatureId(a);
525               aRefs->Add(anID);
526               if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
527                 // add edges to sub-label to support naming for edges selection
528                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
529                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
530                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
531                   Standard_Real aFirst, aLast;
532                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
533                   if (aFaceCurve == aCurve) {
534                     registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
535                   }
536                 }
537               } else { // put vertices of the selected edge to sub-labels
538                 // add edges to sub-label to support naming for edges selection
539                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
540                 int aTagIndex = anID + kSTART_VERTEX_DELTA;
541                 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
542                   TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
543
544                   std::stringstream anAdditionalName; 
545                   registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
546                     "");
547                 }
548               }
549             }
550           }
551         }
552       }
553     }
554   }
555   // store the selected as primitive
556   TNaming_Builder aBuilder(selectionLabel());
557   aBuilder.Generated(aSubShape);
558   registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
559 }
560
561 TDF_Label Model_AttributeSelection::selectionLabel()
562 {
563   return myRef.myRef->Label().FindChild(1);
564 }
565
566 #define FIX_BUG1 1
567 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape, 
568                                              const TDF_Label& theLabel)
569 {
570   std::string aName;
571   // check if the subShape is already in DF
572   Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
573   Handle(TDataStd_Name) anAttr;
574   if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document    
575         if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
576           aName = TCollection_AsciiString(anAttr->Get()).ToCString();
577           if(!aName.empty()) {      
578             const TDF_Label& aLabel = theDoc->findNamingName(aName);
579     /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
580                 if(!aLabel.IsEqual(aNS->Label())) {
581                   //aName.erase(); //something is wrong, to be checked!!!
582                   aName += "_SomethingWrong";
583                   return aName;
584                 }*/
585                 const TopoDS_Shape& aShape = aNS->Get();
586                 if(aShape.ShapeType() == TopAbs_COMPOUND) {
587                   std::string aPostFix("_");
588                   TopoDS_Iterator it(aShape);                   
589                   for (int i = 1;it.More();it.Next(), i++) {
590                     if(it.Value() == theShape) {
591                           aPostFix += TCollection_AsciiString (i).ToCString();
592                           aName    += aPostFix;
593                           break;
594                         }
595                         else continue;                                          
596                   }
597                 }
598           }     
599         }
600   }
601   return aName;
602 }
603
604 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
605 {
606 // a trivial case: F1 & F2,  aNumber = 1, i.e. intersection gives 1 edge.
607   TopoDS_Compound aCmp;
608   BRep_Builder BB;
609   BB.MakeCompound(aCmp);
610   TopTools_ListIteratorOfListOfShape it(theAncestors);
611   for(;it.More();it.Next()) {
612         BB.Add(aCmp, it.Value());
613         theSMap.Add(it.Value());
614   }
615   int aNumber(0);
616   TopTools_IndexedDataMapOfShapeListOfShape aMap2;
617   TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
618   for (int i = 1; i <= aMap2.Extent(); i++) {
619         const TopoDS_Shape& aKey = aMap2.FindKey(i);
620         const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
621         if(anAncestors.Extent() > 1) aNumber++;
622   }
623   if(aNumber > 1) return false;
624   return true;
625 }
626 std::string Model_AttributeSelection::namingName()
627 {
628   std::string aName("");
629   if(!this->isInitialized()) return aName;
630   Handle(TDataStd_Name) anAtt;
631   if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
632         aName = TCollection_AsciiString(anAtt->Get()).ToCString();
633         return aName;
634   }
635
636   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
637   ResultPtr aCont = context();
638   aName = "Undefined name";
639   if(!aCont.get() || aCont->shape()->isNull()) 
640     return aName;
641   if (!aSubSh.get() || aSubSh->isNull()) { // no subshape, so just the whole feature name
642     return aCont->data()->name();
643   }
644   TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
645   TopoDS_Shape aContext  = aCont->shape()->impl<TopoDS_Shape>();
646 #ifdef DEB_NAMING
647   if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
648   BRepTools::Write(aSubShape, "Selection.brep");
649   BRepTools::Write(aContext, "Context.brep");
650   }
651 #endif
652   std::shared_ptr<Model_Document> aDoc = 
653     std::dynamic_pointer_cast<Model_Document>(aCont->document());
654
655   // check if the subShape is already in DF
656   aName = GetShapeName(aDoc, aSubShape, selectionLabel());
657   if(aName.empty() ) { // not in the document!
658     TopAbs_ShapeEnum aType = aSubShape.ShapeType();
659         switch (aType) {
660           case TopAbs_FACE:
661       // the Face should be in DF. If it is not the case, it is an error ==> to be debugged             
662                 break;
663           case TopAbs_EDGE:
664                   {
665                   // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
666                   // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces    
667                   if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
668                           aName = "Degenerated_Edge";
669                           break;
670                   }    
671                   TopTools_IndexedDataMapOfShapeListOfShape aMap;
672                   TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
673                   TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
674                   bool isTrivialCase(true);
675 /*                for (int i = 1; i <= aMap.Extent(); i++) {
676                         const TopoDS_Shape& aKey = aMap.FindKey(i);
677                         //if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
678                         if (aKey.IsSame(aSubShape)) continue;
679             const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
680                         // check that it is not a trivial case (F1 & F2: aNumber = 1)
681                         isTrivialCase = isTrivial(anAncestors, aSMap);                  
682                         break;
683                   }*/
684                   if(aMap.Contains(aSubShape)) {
685                         const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
686                         // check that it is not a trivial case (F1 & F2: aNumber = 1)
687                         isTrivialCase = isTrivial(anAncestors, aSMap);          
688                   } else 
689                           break;
690                   TopTools_ListOfShape aListOfNbs;
691                   if(!isTrivialCase) { // find Neighbors
692                         TNaming_Localizer aLocalizer;
693                         TopTools_MapOfShape aMap3;
694                         aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
695                         //int n = aMap3.Extent();
696                         TopTools_MapIteratorOfMapOfShape it(aMap3);
697                         for(;it.More();it.Next()) {
698                           const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
699                           //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
700                           const TopTools_ListOfShape& aList  = aMap.FindFromKey(aNbShape);
701                           TopTools_ListIteratorOfListOfShape it2(aList);
702                           for(;it2.More();it2.Next()) {
703                                 if(aSMap.Contains(it2.Value())) continue; // skip this Face
704                                 aListOfNbs.Append(it2.Value());
705                           }
706                         }
707                   }  // else a trivial case
708                   
709                   // build name of the sub-shape Edge
710                   for(int i=1; i <= aSMap.Extent(); i++) {
711                         const TopoDS_Shape& aFace = aSMap.FindKey(i);
712                         std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
713                         if(i == 1)
714                           aName = aFaceName;
715                         else 
716                           aName += "|" + aFaceName;
717                   }
718                   TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
719                   for (;itl.More();itl.Next()) {
720                         std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
721                         aName += "|" + aFaceName;
722                   }               
723                   }
724                   break;
725
726           case TopAbs_VERTEX:
727                   // name structure (Monifold Topology): 
728                   // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
729                   // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
730                   // 2) F1 | F2      - intersection of 2 faces definses a vertex - applicable for case
731                   //                   when 1 faces is cylindrical, conical, spherical or revolution and etc.
732                   // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
733                   //                   or compound of 2 open faces.
734                   // 4) E1 | E2      - intesection of 2 edges defines a vertex - when we have a case of 
735                   //                   two independent edges (wire or compound)
736                   // implemented 2 first cases
737                   {
738                         TopTools_IndexedDataMapOfShapeListOfShape aMap;
739                     TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
740                         const TopTools_ListOfShape& aList2  = aMap.FindFromKey(aSubShape);
741                         TopTools_ListOfShape aList;
742                         TopTools_MapOfShape aFMap;
743 #ifdef FIX_BUG1
744                         //int n = aList2.Extent(); //bug! duplication
745                         // fix is below
746                         TopTools_ListIteratorOfListOfShape itl2(aList2);
747                     for (int i = 1;itl2.More();itl2.Next(),i++) {
748                           if(aFMap.Add(itl2.Value()))
749                                 aList.Append(itl2.Value());
750                         }
751                         //n = aList.Extent();
752 #endif
753                         int n = aList.Extent();
754                         if(n < 3) { // open topology case or Compound case => via edges
755                           TopTools_IndexedDataMapOfShapeListOfShape aMap;
756                       TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
757                           const TopTools_ListOfShape& aList22  = aMap.FindFromKey(aSubShape);
758                           if(aList22.Extent() >= 2)  { // regular solution
759 #ifdef FIX_BUG1
760                         
761                             // bug! duplication; fix is below
762                             aFMap.Clear();
763                             TopTools_ListOfShape aListE;
764                             TopTools_ListIteratorOfListOfShape itl2(aList22);
765                         for (int i = 1;itl2.More();itl2.Next(),i++) {
766                             if(aFMap.Add(itl2.Value()))
767                                   aListE.Append(itl2.Value());
768                                 }
769                             n = aListE.Extent();
770 #endif
771                                 TopTools_ListIteratorOfListOfShape itl(aListE);
772                         for (int i = 1;itl.More();itl.Next(),i++) {
773                               const TopoDS_Shape& anEdge = itl.Value();
774                               std::string anEdgeName = GetShapeName(aDoc, anEdge, selectionLabel());
775                               if(i == 1)
776                                 aName = anEdgeName;
777                               else 
778                                 aName += "|" + anEdgeName;
779                                 }
780                           }//reg
781                           else { // dangle vertex: if(aList22.Extent() == 1)
782                                   //it should be already in DF
783                           }
784                         } 
785                         else {
786                           TopTools_ListIteratorOfListOfShape itl(aList);
787                       for (int i = 1;itl.More();itl.Next(),i++) {
788                             const TopoDS_Shape& aFace = itl.Value();
789                             std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
790                             if(i == 1)
791                               aName = aFaceName;
792                             else 
793                               aName += "|" + aFaceName;
794                           }
795                         }
796                   }
797                   break;
798         }
799     // register name                    
800     // aDoc->addNamingName(selectionLabel(), aName);
801         // the selected sub-shape will not be shared and as result it will not require registration
802   }
803   return aName;
804 }
805
806 TopAbs_ShapeEnum translateType (const std::string& theType)
807 {
808   // map from the textual shape types to OCCT enumeration
809   static std::map<std::string, TopAbs_ShapeEnum> MyShapeTypes;
810   if (MyShapeTypes.size() == 0) {
811     MyShapeTypes["face"] = TopAbs_FACE;
812     MyShapeTypes["faces"] = TopAbs_FACE;
813     MyShapeTypes["vertex"] = TopAbs_VERTEX;
814     MyShapeTypes["vertices"] = TopAbs_VERTEX;
815     MyShapeTypes["wire"] = TopAbs_WIRE;
816     MyShapeTypes["edge"] = TopAbs_EDGE;
817     MyShapeTypes["edges"] = TopAbs_EDGE;
818     MyShapeTypes["shell"] = TopAbs_SHELL;
819     MyShapeTypes["solid"] = TopAbs_SOLID;
820     MyShapeTypes["solids"] = TopAbs_SOLID;
821     MyShapeTypes["FACE"] = TopAbs_FACE;
822     MyShapeTypes["FACES"] = TopAbs_FACE;
823     MyShapeTypes["VERTEX"] = TopAbs_VERTEX;
824     MyShapeTypes["VERTICES"] = TopAbs_VERTEX;
825     MyShapeTypes["WIRE"] = TopAbs_WIRE;
826     MyShapeTypes["EDGE"] = TopAbs_EDGE;
827     MyShapeTypes["EDGES"] = TopAbs_EDGE;
828     MyShapeTypes["SHELL"] = TopAbs_SHELL;
829     MyShapeTypes["SOLID"] = TopAbs_SOLID;
830     MyShapeTypes["SOLIDS"] = TopAbs_SOLID;
831   }
832   if (MyShapeTypes.find(theType) != MyShapeTypes.end())
833     return MyShapeTypes[theType];
834   Events_Error::send("Shape type defined in XML is not implemented!");
835   return TopAbs_SHAPE;
836 }
837
838 const TopoDS_Shape getShapeFromCompound(const std::string& theSubShapeName, const TopoDS_Shape& theCompound)
839 {
840   TopoDS_Shape aSelection;
841   std::string::size_type n = theSubShapeName.rfind('/');                        
842   if (n == std::string::npos) n = 0;
843         std::string aSubString = theSubShapeName.substr(n + 1);
844         n = aSubString.rfind('_');
845         if (n == std::string::npos) return aSelection;
846         aSubString = aSubString.substr(n+1);
847         int indx = atoi(aSubString.c_str());
848         TopoDS_Iterator it(theCompound);                        
849         for (int i = 1;it.More();it.Next(), i++) {
850           if(i == indx) {                         
851             aSelection = it.Value();                      
852             break;
853           }
854           else continue;                                                
855         }
856   return aSelection;    
857 }
858
859 const TopoDS_Shape findFaceByName(const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
860 {
861   TopoDS_Shape aFace;
862   std::string::size_type n, nb = theSubShapeName.rfind('/');                    
863   if (nb == std::string::npos) nb = 0;
864   std::string aSubString = theSubShapeName.substr(nb + 1);
865   n = aSubString.rfind('_');
866   if (n != std::string::npos) {
867           std::string aSubStr2 = aSubString.substr(0, n);
868         aSubString  = theSubShapeName.substr(0, nb + 1);
869         aSubString = aSubString + aSubStr2;     
870   } else
871         aSubString = theSubShapeName;
872                                 
873   const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
874   if(aLabel.IsNull()) return aFace;
875   Handle(TNaming_NamedShape) aNS;
876   if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
877         const TopoDS_Shape& aShape = aNS->Get();
878         if(!aShape.IsNull()) {
879           if(aShape.ShapeType() == TopAbs_COMPOUND) 
880             aFace = getShapeFromCompound(theSubShapeName, aShape);
881           else 
882                 aFace = aShape;   
883         }
884   }
885   return aFace;
886 }
887
888 int ParseName(const std::string& theSubShapeName,   std::list<std::string>& theList)
889 {
890   std::string aName = theSubShapeName;
891   std::string aLastName;
892   int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
893   while ((n2 = aName.find('|', n1)) != std::string::npos) {
894     const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
895         theList.push_back(aName1);      
896         n1 = n2 + 1;
897         aLastName = aName.substr(n1);
898   }
899   if(!aLastName.empty())
900         theList.push_back(aLastName);
901   return theList.size();
902 }
903
904 const TopoDS_Shape findCommonShape(const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
905 {
906   TopoDS_Shape aShape;
907   std::vector<TopTools_MapOfShape> aVec;
908   TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
909   if(theList.Extent() > 1) {
910         aVec.push_back(aMap1);
911         aVec.push_back(aMap2);
912   }
913   if(theList.Extent() > 2)
914     aVec.push_back(aMap3);
915   if(theList.Extent() == 4)
916     aVec.push_back(aMap4);
917
918   //fill maps
919   TopTools_ListIteratorOfListOfShape it(theList);
920   for(int i = 0;it.More();it.Next(),i++) {
921         const TopoDS_Shape& aFace = it.Value();         
922         if(i < 2) {
923           TopExp_Explorer anExp (aFace, theType);
924           for(;anExp.More();anExp.Next()) {
925             const TopoDS_Shape& anEdge = anExp.Current();
926             if (!anEdge.IsNull())
927                   aVec[i].Add(anExp.Current());
928           }
929         } else {
930           TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
931           for(;anExp.More();anExp.Next()) {
932             const TopoDS_Shape& aVertex = anExp.Current();
933             if (!aVertex.IsNull())
934                   aVec[i].Add(anExp.Current());
935           }
936         }
937   }
938   //trivial case: 2 faces
939   TopTools_ListOfShape aList;
940   TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
941   for(;it2.More();it2.Next()) {
942         if(aVec[1].Contains(it2.Key())) {
943           aShape = it2.Key();
944           if(theList.Extent() == 2)
945             break;
946           else 
947                 aList.Append(it2.Key());
948         }
949   }
950   if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors 
951         if(aVec[2].Extent() && aVec[3].Extent()) {
952           TopTools_ListIteratorOfListOfShape it(aList);
953           for(;it.More();it.Next()) {
954                 const TopoDS_Shape& aCand = it.Value();
955                 // not yet completelly implemented, to be rechecked
956                 TopoDS_Vertex aV1, aV2;
957                 TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
958                 int aNum(0);
959                 if(aVec[2].Contains(aV1)) aNum++;
960                 else if(aVec[2].Contains(aV2)) aNum++;
961                 if(aVec[3].Contains(aV1)) aNum++;
962                 else if(aVec[3].Contains(aV2)) aNum++;
963                 if(aNum == 2) {
964                   aShape = aCand;
965                   break;
966                 }
967           }
968         }
969   }
970
971   if(aList.Extent() && aVec.size() == 3) {
972
973     TopTools_ListIteratorOfListOfShape it(aList);
974           for(;it.More();it.Next()) {
975                 const TopoDS_Shape& aCand = it.Value();
976                 if(aVec[2].Contains(aCand)) {
977                   aShape = aCand;
978                   break;
979                 }
980           }
981   }
982   return aShape;
983 }
984
985 std::string getContextName(const std::string& theSubShapeName)
986 {
987   std::string aName;
988   std::string::size_type n = theSubShapeName.find('/');                 
989   if (n == std::string::npos) return aName;
990   aName = theSubShapeName.substr(0, n);
991   return aName;
992 }
993 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
994 void Model_AttributeSelection::selectSubShape(const std::string& theType, const std::string& theSubShapeName)
995 {
996   if(theSubShapeName.empty() || theType.empty()) return;
997   TopAbs_ShapeEnum aType = translateType(theType);
998   std::shared_ptr<Model_Document> aDoc =  std::dynamic_pointer_cast<Model_Document>(owner()->document());//std::dynamic_pointer_cast<Model_Document>(aCont->document());
999   std::string aContName = getContextName(theSubShapeName);
1000   if(aContName.empty()) return;
1001   //ResultPtr aCont = context();
1002   ResultPtr aCont = aDoc->findByName(aContName);
1003   if(!aCont.get() || aCont->shape()->isNull()) return;
1004   TopoDS_Shape aContext  = aCont->shape()->impl<TopoDS_Shape>();
1005   TopAbs_ShapeEnum aContType = aContext.ShapeType();
1006   if(aType <= aContType) return; // not applicable
1007  
1008   
1009   TopoDS_Shape aSelection;
1010   switch (aType) 
1011   {
1012   case TopAbs_COMPOUND:
1013     break;
1014   case TopAbs_COMPSOLID:
1015     break;
1016   case TopAbs_SOLID:
1017     break;
1018   case TopAbs_SHELL:
1019     break;
1020   case TopAbs_FACE:
1021     {
1022           const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
1023           if(!aSelection.IsNull()) {// Select it
1024                 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1025         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1026                 setValue(aCont, aShapeToBeSelected);
1027           }
1028         }
1029     break;
1030   case TopAbs_WIRE:
1031         break;
1032   case TopAbs_EDGE:
1033         {  
1034           TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
1035           const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1036       if(!aLabel.IsNull()) {
1037         Handle(TNaming_NamedShape) aNS;
1038         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1039               const TopoDS_Shape& aShape = aNS->Get();
1040               if(!aShape.IsNull()) {
1041                 if(aShape.ShapeType() == TopAbs_COMPOUND) 
1042                   aSelection = getShapeFromCompound(theSubShapeName, aShape);
1043                         else 
1044                     aSelection = aShape;          
1045                   }
1046                 }
1047           }
1048           if(aSelection.IsNull()) {
1049           std::list<std::string> aListofNames;
1050           int n = ParseName(theSubShapeName, aListofNames);
1051           if(n > 1 && n < 5) {
1052                 TopTools_ListOfShape aList;
1053         for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
1054                   const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1055                   aList.Append(aFace);          
1056                 }
1057                 aSelection = findCommonShape(TopAbs_EDGE, aList);
1058           }
1059           }
1060           if(!aSelection.IsNull()) {// Select it
1061                 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1062         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1063                 setValue(aCont, aShapeToBeSelected);
1064           }
1065         }
1066     break;
1067   case TopAbs_VERTEX:
1068           {
1069           TopoDS_Shape aSelection;
1070           const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1071       if(!aLabel.IsNull()) {
1072         Handle(TNaming_NamedShape) aNS;
1073         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1074               const TopoDS_Shape& aShape = aNS->Get();
1075               if(!aShape.IsNull()) {
1076                 if(aShape.ShapeType() == TopAbs_COMPOUND) 
1077                   aSelection = getShapeFromCompound(theSubShapeName, aShape);
1078                         else 
1079                     aSelection = aShape;          
1080                   }
1081                 }
1082           }
1083           if(aSelection.IsNull()) {
1084             std::list<std::string> aListofNames;
1085                 int n = ParseName(theSubShapeName, aListofNames);
1086             if(n > 1 && n < 4) { // 2 || 3
1087                 TopTools_ListOfShape aList;
1088           for(std::list<std::string>::iterator it =aListofNames.begin();it != aListofNames.end();it++){
1089                     const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1090                         if(!aFace.IsNull())
1091                       aList.Append(aFace);              
1092                   }
1093                  aSelection = findCommonShape(TopAbs_VERTEX, aList);
1094                 }
1095           }
1096           if(!aSelection.IsNull()) {// Select it
1097                 std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1098         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1099                 setValue(aCont, aShapeToBeSelected);
1100           }
1101           }
1102         break;
1103   default: //TopAbs_SHAPE
1104         return;
1105   }
1106
1107 }
1108
1109 int Model_AttributeSelection::Id()
1110 {
1111   std::shared_ptr<GeomAPI_Shape> aSelection = value();
1112   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
1113   const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
1114   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1115   int anID = 0;
1116   if (aSelection && !aSelection->isNull() &&
1117       aContext   && !aContext->isNull())
1118   {
1119     TopTools_IndexedMapOfShape aSubShapesMap;
1120     TopExp::MapShapes(aMainShape, aSubShapesMap);
1121     anID = aSubShapesMap.FindIndex(aSubShape);
1122   }
1123   return anID;
1124 }