Salome HOME
Switch Wireframe/Shading with closing of context
[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 <ModelAPI_Feature.h>
12 #include <ModelAPI_ResultBody.h>
13 #include <ModelAPI_ResultConstruction.h>
14 #include <ModelAPI_CompositeFeature.h>
15 #include <GeomAPI_Shape.h>
16 #include <GeomAPI_PlanarEdges.h>
17 #include <GeomAlgoAPI_SketchBuilder.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 <TopTools_MapOfShape.hxx>
30 #include <TopTools_IndexedMapOfShape.hxx>
31 #include <TopTools_MapIteratorOfMapOfShape.hxx>
32 #include <TopTools_ListOfShape.hxx>
33 #include <TopExp_Explorer.hxx>
34 #include <TDF_LabelMap.hxx>
35 #include <BRep_Tool.hxx>
36 #include <BRep_Builder.hxx>
37 #include <TopoDS_Edge.hxx>
38 #include <TopoDS.hxx>
39 #include <TopExp.hxx>
40 #include <TColStd_MapOfTransient.hxx>
41 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
43 #include <gp_Pnt.hxx>
44 #include <Precision.hxx>
45 #include <TDF_ChildIterator.hxx>
46 #include <TDF_ChildIDIterator.hxx>
47 #include <TDataStd_Name.hxx>
48 #include <TopAbs_ShapeEnum.hxx>
49 #include <TopoDS_Iterator.hxx>
50 using namespace std;
51 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
52 /// (multiplied by the index of the edge)
53 static const int kSTART_VERTEX_DELTA = 1000000;
54
55 // on this label is stored:
56 // TNaming_NamedShape - selected shape
57 // TNaming_Naming - topological selection information (for the body)
58 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
59 // TDataStd_Integer - type of the selected shape (for construction)
60 // TDF_Reference - from ReferenceAttribute, the context
61
62 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
63   const std::shared_ptr<GeomAPI_Shape>& theSubShape)
64 {
65   const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
66   bool isOldShape = 
67     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
68   if (isOldShape) return; // shape is the same, so context is also unchanged
69   // update the referenced object if needed
70   bool isOldContext = theContext == myRef.value();
71   if (!isOldContext)
72     myRef.setValue(theContext);
73
74   if (theContext->groupName() == ModelAPI_ResultBody::group())
75     selectBody(theContext, theSubShape);
76   else if (theContext->groupName() == ModelAPI_ResultConstruction::group())
77     selectConstruction(theContext, theSubShape);
78
79   std::string aSelName = namingName();
80   if(!aSelName.empty())
81           TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
82
83   myIsInitialized = true;
84   owner()->data()->sendAttributeUpdated(this);
85 }
86
87 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
88 {
89   std::shared_ptr<GeomAPI_Shape> aResult;
90   if (myIsInitialized) {
91     Handle(TNaming_NamedShape) aSelection;
92     if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
93       TopoDS_Shape aSelShape = aSelection->Get();
94       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
95       aResult->setImpl(new TopoDS_Shape(aSelShape));
96     } else { // for simple construction element: just shape of this construction element
97       ResultConstructionPtr aConstr = 
98         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
99       if (aConstr) {
100         return aConstr->shape();
101       }
102     }
103   }
104   return aResult;
105 }
106
107 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
108   : myRef(theLabel)
109 {
110   myIsInitialized = myRef.isInitialized();
111 }
112
113 ResultPtr Model_AttributeSelection::context() {
114   return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
115 }
116
117
118 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
119 {
120   ModelAPI_AttributeSelection::setObject(theObject);
121   myRef.setObject(theObject);
122 }
123
124 TDF_LabelMap& Model_AttributeSelection::scope()
125 {
126   if (myScope.IsEmpty()) { // create a new scope if not yet done
127     // gets all labels with named shapes that are bofore this feature label (before in history)
128     TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
129       owner()->data())->label().Father();
130     int aFeatureID = aFeatureLab.Tag();
131     TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
132     for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
133       if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
134         break;
135       TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
136       for(; aNSIter.More(); aNSIter.Next()) {
137         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
138         if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
139           myScope.Add(aNS->Label());
140         }
141       }
142     }
143   }
144   return myScope;
145 }
146
147 bool Model_AttributeSelection::update()
148 {
149   ResultPtr aContext = context();
150   if (!aContext) return false;
151   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
152     // body: just a named shape, use selection mechanism from OCCT
153     TNaming_Selector aSelector(selectionLabel());
154     bool aResult = aSelector.Solve(scope()) == Standard_True;
155     owner()->data()->sendAttributeUpdated(this);
156     return aResult;
157   } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
158     // construction: identification by the results indexes, recompute faces and
159     // take the face that more close by the indexes
160     std::shared_ptr<GeomAPI_PlanarEdges> aWirePtr = 
161       std::dynamic_pointer_cast<GeomAPI_PlanarEdges>(
162       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext)->shape());
163     if (aWirePtr && aWirePtr->hasPlane()) { // sketch sub-element
164       TDF_Label aLab = myRef.myRef->Label();
165       // getting a type of selected shape
166       Handle(TDataStd_Integer) aTypeAttr;
167       if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
168         return false;
169       }
170       TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
171       // selected indexes will be needed in each "if"
172       Handle(TDataStd_IntPackedMap) aSubIds;
173       std::shared_ptr<GeomAPI_Shape> aNewSelected;
174       bool aNoIndexes = 
175         !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
176       // for now working only with composite features
177       FeaturePtr aContextFeature = aContext->document()->feature(aContext);
178       CompositeFeaturePtr aComposite = 
179         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
180       if (!aComposite || aComposite->numberOfSubs() == 0) {
181         return false;
182       }
183
184       if (aShapeType == TopAbs_FACE) {
185         // If this is a wire with plane defined thin it is a sketch-like object
186         std::list<std::shared_ptr<GeomAPI_Shape> > aFaces;
187         GeomAlgoAPI_SketchBuilder::createFaces(aWirePtr->origin(), aWirePtr->dirX(),
188           aWirePtr->dirY(), aWirePtr->norm(), aWirePtr, aFaces);
189         if (aFaces.empty()) // no faces, update can not work correctly
190           return false;
191         // if there is no edges indexes, any face can be used: take the first
192         std::shared_ptr<GeomAPI_Shape> aNewSelected;
193         if (aNoIndexes) {
194           aNewSelected = *(aFaces.begin());
195         } else { // searching for most looks-like initial face by the indexes
196           // prepare edges of the current resut for the fast searching
197           TColStd_MapOfTransient allCurves;
198           const int aSubNum = aComposite->numberOfSubs();
199           for(int a = 0; a < aSubNum; a++) {
200             if (aSubIds->Contains(aComposite->subFeatureId(a))) {
201               FeaturePtr aSub = aComposite->subFeature(a);
202               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
203               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
204               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
205                 ResultConstructionPtr aConstr = 
206                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
207                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
208                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
209                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
210                   if (!anEdge.IsNull()) {
211                     Standard_Real aFirst, aLast;
212                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
213                     allCurves.Add(aCurve);
214                   }
215                 }
216               }
217             }
218           }
219           // iterate new result faces and searching for these edges
220           std::list<std::shared_ptr<GeomAPI_Shape> >::iterator aFacesIter = aFaces.begin();
221           double aBestFound = 0; // best percentage of found edges
222           for(; aFacesIter != aFaces.end(); aFacesIter++) {
223             int aFound = 0, aNotFound = 0;
224             TopExp_Explorer anEdgesExp((*aFacesIter)->impl<TopoDS_Shape>(), TopAbs_EDGE);
225             for(; anEdgesExp.More(); anEdgesExp.Next()) {
226               TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
227               if (!anEdge.IsNull()) {
228                 Standard_Real aFirst, aLast;
229                 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
230                 if (allCurves.Contains(aCurve)) {
231                   aFound++;
232                 } else {
233                   aNotFound++;
234                 }
235               }
236             }
237             if (aFound + aNotFound != 0) {
238               double aPercentage = double(aFound) / double(aFound + aNotFound);
239               if (aPercentage > aBestFound) {
240                 aBestFound = aPercentage;
241                 aNewSelected = *aFacesIter;
242               }
243             }
244           }
245         }
246         if (aNewSelected) { // store this new selection
247           selectConstruction(aContext, aNewSelected);
248           owner()->data()->sendAttributeUpdated(this);
249           return true;
250         }
251       } else if (aShapeType == TopAbs_EDGE) {
252         // just reselect the edge by the id
253         const int aSubNum = aComposite->numberOfSubs();
254         for(int a = 0; a < aSubNum; a++) {
255           // if aSubIds take any, the first appropriate
256           if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
257             // found the appropriate feature
258             FeaturePtr aFeature = aComposite->subFeature(a);
259             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
260               aFeature->results().cbegin();
261             for(;aResIter != aFeature->results().cend(); aResIter++) {
262               ResultConstructionPtr aRes = 
263                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
264               if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
265                 selectConstruction(aContext, aRes->shape());
266                 owner()->data()->sendAttributeUpdated(this);
267                 return true;
268               }
269             }
270           }
271         }
272       } else if (aShapeType == TopAbs_VERTEX) {
273         // just reselect the vertex by the id of edge
274         const int aSubNum = aComposite->numberOfSubs();
275         for(int a = 0; a < aSubNum; a++) {
276           // if aSubIds take any, the first appropriate
277           int aFeatureID = aComposite->subFeatureId(a);
278           if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID)) {
279             // searching for deltas
280             int aVertexNum = 0;
281             if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
282             else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
283             // found the feature with appropriate edge
284             FeaturePtr aFeature = aComposite->subFeature(a);
285             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
286               aFeature->results().cbegin();
287             for(;aResIter != aFeature->results().cend(); aResIter++) {
288               ResultConstructionPtr aRes = 
289                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
290               if (aRes && aRes->shape()) {
291                 if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
292                   selectConstruction(aContext, aRes->shape());
293                   owner()->data()->sendAttributeUpdated(this);
294                   return true;
295                 } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
296                   const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
297                   int aVIndex = 1;
298                   for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
299                     if (aVIndex == aVertexNum) { // found!
300                       std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
301                       aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
302                       selectConstruction(aContext, aVertex);
303                       owner()->data()->sendAttributeUpdated(this);
304                       return true;
305                     }
306                     aVIndex++;
307                   }
308                 }
309               }
310             }
311           }
312         }
313       }
314     } else { // simple construction element: the selected is that needed
315       owner()->data()->sendAttributeUpdated(this);
316       return true;
317     }
318   }
319   return false; // unknown case
320 }
321
322
323 void Model_AttributeSelection::selectBody(
324     const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
325 {
326   // perform the selection
327   TNaming_Selector aSel(selectionLabel());
328   TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : TopoDS_Shape();
329   TopoDS_Shape aContext;
330
331   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
332   if (aBody)
333     aContext = aBody->shape()->impl<TopoDS_Shape>();
334   else {
335     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myRef.value());
336     if (aConstr) {
337       aContext = aConstr->shape()->impl<TopoDS_Shape>();
338     } else {
339       Events_Error::send("A result with shape is expected");
340       return;
341     }
342   }
343   aSel.Select(aNewShape, aContext);
344 }
345
346 void Model_AttributeSelection::selectConstruction(
347     const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
348 {
349   FeaturePtr aContextFeature = theContext->document()->feature(theContext);
350   CompositeFeaturePtr aComposite = 
351     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
352   if (!aComposite || aComposite->numberOfSubs() == 0) {
353     return; // saving of context is enough: result construction contains exactly the needed shape
354   }
355   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
356   TDF_Label aLab = myRef.myRef->Label();
357   // identify the reuslts of sub-object of the composite by edges
358   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
359   // save type of the selected shape in integer attribute
360   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
361   TDataStd_Integer::Set(aLab, (int)aShapeType);
362   gp_Pnt aVertexPos;
363   TColStd_MapOfTransient allCurves;
364   if (aShapeType == TopAbs_VERTEX) { // compare positions
365     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
366   } else { 
367     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
368       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
369       Standard_Real aFirst, aLast;
370       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
371       allCurves.Add(aCurve);
372     }
373   }
374   // iterate and store the result ids of sub-elements
375   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
376   aRefs->Clear();
377   const int aSubNum = aComposite->numberOfSubs();
378   for(int a = 0; a < aSubNum; a++) {
379     FeaturePtr aSub = aComposite->subFeature(a);
380     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
381     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
382     // there may be many shapes (circle and center): register if at least one is in selection
383     for(; aRes != aResults.cend(); aRes++) {
384       ResultConstructionPtr aConstr = 
385         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
386       if (!aConstr->shape()) {
387         continue;
388       }
389       if (aShapeType == TopAbs_VERTEX) {
390         if (aConstr->shape()->isVertex()) { // compare vertices positions
391           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
392           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
393           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
394             aRefs->Add(aComposite->subFeatureId(a));
395           }
396         } else { // get first or last vertex of the edge: last is stored with negative sign
397           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
398           int aDelta = kSTART_VERTEX_DELTA;
399           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
400             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
401             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
402               aRefs->Add(aComposite->subFeatureId(a));
403               aRefs->Add(aDelta + aComposite->subFeatureId(a));
404               break;
405             }
406             aDelta += kSTART_VERTEX_DELTA;
407           }
408         }
409       } else {
410         if (aConstr->shape()->isEdge()) {
411           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
412           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
413           if (!anEdge.IsNull()) {
414             Standard_Real aFirst, aLast;
415             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
416             if (allCurves.Contains(aCurve)) {
417               int anID = aComposite->subFeatureId(a);
418               aRefs->Add(anID);
419               // add edges to sub-label to support naming for edges selection
420               for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
421                 TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
422                 Standard_Real aFirst, aLast;
423                 Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
424                 if (aFaceCurve == aCurve) {
425                   TNaming_Builder anEdgeBuilder(selectionLabel().FindChild(anID));
426                   anEdgeBuilder.Generated(anEdge);
427                 }
428               }
429             }
430           }
431         }
432       }
433     }
434   }
435   // store the selected as primitive
436   TNaming_Builder aBuilder(selectionLabel());
437   aBuilder.Generated(aSubShape);
438 }
439
440 TDF_Label Model_AttributeSelection::selectionLabel()
441 {
442   return myRef.myRef->Label().FindChild(1);
443 }
444
445 #define FIX_BUG1 1
446 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape, 
447                                              const TDF_Label& theLabel)
448 {
449   std::string aName;
450   // check if the subShape is already in DF
451   Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
452   Handle(TDataStd_Name) anAttr;
453   if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document    
454         if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
455           aName = TCollection_AsciiString(anAttr->Get()).ToCString();
456           if(!aName.empty()) {      
457             const TDF_Label& aLabel = theDoc->findNamingName(aName);
458                 if(!aLabel.IsEqual(aNS->Label())) {
459                   //aName.erase(); //something is wrong, to be checked!!!
460                   aName += "_SomethingWrong";
461                   return aName;
462                 }
463                 const TopoDS_Shape& aShape = aNS->Get();
464                 if(aShape.ShapeType() == TopAbs_COMPOUND) {
465                   std::string aPostFix("_");
466                   TopoDS_Iterator it(aShape);                   
467                   for (int i = 1;it.More();it.Next(), i++) {
468                     if(it.Value() == theShape) {
469                           aPostFix += TCollection_AsciiString (i).ToCString();
470                           aName    += aPostFix;
471                           break;
472                         }
473                         else continue;                                          
474                   }
475                 }
476           }     
477         }
478   }
479   return aName;
480 }
481
482 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
483 {
484 // a trivial case: F1 & F2,  aNumber = 1, i.e. intersection gives 1 edge.
485   TopoDS_Compound aCmp;
486   BRep_Builder BB;
487   BB.MakeCompound(aCmp);
488   TopTools_ListIteratorOfListOfShape it(theAncestors);
489   for(;it.More();it.Next()) {
490         BB.Add(aCmp, it.Value());
491         theSMap.Add(it.Value());
492   }
493   int aNumber(0);
494   TopTools_IndexedDataMapOfShapeListOfShape aMap2;
495   TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
496   for (int i = 1; i <= aMap2.Extent(); i++) {
497         const TopoDS_Shape& aKey = aMap2.FindKey(i);
498         const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
499         if(anAncestors.Extent() > 1) aNumber++;
500   }
501   if(aNumber > 1) return false;
502   return true;
503 }
504 std::string Model_AttributeSelection::namingName()//std::shared_ptr<GeomAPI_Shape> theSubShape, 
505                                                         // const ResultPtr& theContext)
506 {
507   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
508   ResultPtr aCont = context();
509   std::string aName;
510   if(!aSubSh.get() || aSubSh->isNull() || !aCont.get() || aCont->shape()->isNull()) 
511     return aName;
512   TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
513   TopoDS_Shape aContext  = aCont->shape()->impl<TopoDS_Shape>();
514   std::shared_ptr<Model_Document> aDoc = 
515     std::dynamic_pointer_cast<Model_Document>(aCont->document());
516
517   // check if the subShape is already in DF
518   aName = GetShapeName(aDoc, aSubShape, selectionLabel());
519   if(aName.empty() ) { // not in the document!
520     TopAbs_ShapeEnum aType = aSubShape.ShapeType();
521         switch (aType) {
522           case TopAbs_FACE:
523       // the Face should be in DF. If it is not a case, it is an error ==> to be dbugged                
524                 break;
525           case TopAbs_EDGE:
526                   {
527                   // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
528                   // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
529                   TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
530                   TopTools_IndexedDataMapOfShapeListOfShape aMap;
531                   TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
532                   bool isTrivialCase(true);
533                   for (int i = 1; i <= aMap.Extent(); i++) {
534                         const TopoDS_Shape& aKey = aMap.FindKey(i);
535                         if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
536
537             const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
538                         // check that it is not a trivial case (F1 & F2: aNumber = 1)
539                         isTrivialCase = isTrivial(anAncestors, aSMap);                  
540                         break;
541                   }
542
543                   TopTools_ListOfShape aListOfNbs;
544                   if(!isTrivialCase) { // find Neighbors
545                         TNaming_Localizer aLocalizer;
546                         TopTools_MapOfShape aMap3;
547                         aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
548                         //int n = aMap3.Extent();
549                         TopTools_MapIteratorOfMapOfShape it(aMap3);
550                         for(;it.More();it.Next()) {
551                           const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
552                           //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
553                           const TopTools_ListOfShape& aList  = aMap.FindFromKey(aNbShape);
554                           TopTools_ListIteratorOfListOfShape it2(aList);
555                           for(;it2.More();it2.Next()) {
556                                 if(aSMap.Contains(it2.Value())) continue; // skip this Face
557                                 aListOfNbs.Append(it2.Value());
558                           }
559                         }
560                   }  // else a trivial case
561                   
562                   // build name of the sub-shape Edge
563                   for(int i=1; i <= aSMap.Extent(); i++) {
564                         const TopoDS_Shape& aFace = aSMap.FindKey(i);
565                         std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
566                         if(i == 1)
567                           aName = aFaceName;
568                         else 
569                           aName += "|" + aFaceName;
570                   }
571                   TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
572                   for (;itl.More();itl.Next()) {
573                         std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
574                         aName += "|" + aFaceName;
575                   }               
576                   }
577                   break;
578
579           case TopAbs_VERTEX:
580                   // name structure (Monifold Topology): 
581                   // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
582                   // 2) F1 | F2      - intersection of 2 faces definses a vertex - applicable for case
583                   //                   when 1 faces is cylindrical, conical, spherical or revolution and etc.
584                   // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
585                   //                   or compound of 2 open faces.
586                   // 4) E1 | E2      - intesection of 2 edges defines a vertex - when we have a case of 
587                   //                   two independent edges (wire or compound)
588                   // implemented 2 first cases
589                   {
590                         TopTools_IndexedDataMapOfShapeListOfShape aMap;
591                     TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
592                         const TopTools_ListOfShape& aList2  = aMap.FindFromKey(aSubShape);
593                         TopTools_ListOfShape aList;
594                         TopTools_MapOfShape aFMap;
595 #ifdef FIX_BUG1
596                         //int n = aList2.Extent(); //bug!
597                         // fix is below
598                         TopTools_ListIteratorOfListOfShape itl2(aList2);
599                     for (int i = 1;itl2.More();itl2.Next(),i++) {
600                           if(aFMap.Add(itl2.Value()))
601                                 aList.Append(itl2.Value());
602                         }
603                         //n = aList.Extent();
604 #endif
605                         TopTools_ListIteratorOfListOfShape itl(aList);
606                     for (int i = 1;itl.More();itl.Next(),i++) {
607                           const TopoDS_Shape& aFace = itl.Value();
608                           std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
609                           if(i == 1)
610                             aName = aFaceName;
611                           else 
612                             aName += "|" + aFaceName;
613                         }
614                   }
615                   break;
616         }
617     // register name                    
618     // aDoc->addNamingName(selectionLabel(), aName);
619         // the selected sub-shape will not be shared and as result it will not require registration
620   }
621   return aName;
622 }