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