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