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