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