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