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