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