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