Salome HOME
Issue #2631: SIGSEGV when creating a point on the result of a cut edge by edge
[modules/shaper.git] / src / Model / Model_SelectionNaming.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "Model_SelectionNaming.h"
22 #include "Model_Document.h"
23 #include "Model_Objects.h"
24 #include "Model_Data.h"
25 #include <ModelAPI_Feature.h>
26 #include <Events_InfoMessage.h>
27 #include <ModelAPI_Session.h>
28 #include <ModelAPI_ResultPart.h>
29 #include <ModelAPI_ResultConstruction.h>
30 #include <ModelAPI_CompositeFeature.h>
31 #include <ModelAPI_ResultBody.h>
32 #include <GeomAPI_Wire.h>
33
34 #include <TopoDS_Iterator.hxx>
35 #include <TopoDS.hxx>
36 #include <TopoDS_Compound.hxx>
37 #include <TopExp.hxx>
38 #include <TopExp_Explorer.hxx>
39 #include <TopTools_ListOfShape.hxx>
40 #include <TopTools_MapOfShape.hxx>
41 #include <TopTools_IndexedMapOfShape.hxx>
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
43 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
44 #include <TopTools_MapIteratorOfMapOfShape.hxx>
45 #include <BRep_Builder.hxx>
46 #include <TNaming_Iterator.hxx>
47 #include <TNaming_Tool.hxx>
48 #include <TNaming_NamedShape.hxx>
49 #include <TNaming_Localizer.hxx>
50 #include <TNaming_SameShapeIterator.hxx>
51 #include <TDataStd_Name.hxx>
52 #include <TColStd_MapOfTransient.hxx>
53 #include <algorithm>
54 #include <stdexcept>
55
56 #ifdef DEB_NAMING
57 #include <BRepTools.hxx>
58 #endif
59
60 Model_SelectionNaming::Model_SelectionNaming(TDF_Label theSelectionLab)
61 {
62   myLab = theSelectionLab;
63 }
64
65 // searches named shape by the shape in the given document (identified by the label)
66 // tries to find s shape nearest to the context-label
67 static Handle(TNaming_NamedShape) shapeToNS(const TDF_Label theLabAccess,
68   const TopoDS_Shape& theShape, const TDF_Label& theContextLab)
69 {
70   Handle(TNaming_NamedShape) aResult;
71   if (!TNaming_Tool::HasLabel(theLabAccess, theShape)) // no shape in the document
72     return aResult;
73   int aContextLabDepth = theContextLab.IsNull() ? 100 : theContextLab.Depth();
74   TNaming_SameShapeIterator aNSIter(theShape, theLabAccess);
75   for(; aNSIter.More(); aNSIter.Next()) {
76     TDF_Label aLabel = aNSIter.Label();
77     Handle(TNaming_NamedShape) aNS;
78     if (aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
79       if (aNS->Evolution() != TNaming_SELECTED && aNS->Evolution() != TNaming_DELETE) {
80         // check this is new shape in this named shape
81         bool aIsNew = false;
82         for(TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next())
83           if (!aNSIter.NewShape().IsNull() && aNSIter.NewShape().IsSame(theShape))
84             aIsNew = true;
85         if (!aIsNew)
86           continue;
87         // check this is the context-shape
88         while(aLabel.Depth() > aContextLabDepth)
89           aLabel = aLabel.Father();
90         if (aLabel.IsEqual(theContextLab))
91           return aNS;
92         if (aResult.IsNull()) // take the first, otherwise it will get shapes from results, etc
93           aResult = aNS; // keep some result anyway - if there are no context labels return any
94       }
95     }
96   }
97   return aResult;
98 }
99
100 std::string Model_SelectionNaming::getShapeName(
101   std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape,
102   ResultPtr& theContext, const bool theAnotherDoc, const bool theWholeContext)
103 {
104   std::string aName;
105   // add the result name to the name of the shape
106   // (it was in BodyBuilder, but did not work on Result rename)
107   bool isNeedContextName = theContext->shape().get() != NULL;
108   // check if the subShape is already in DF
109   std::shared_ptr<Model_Data> aData =
110     std::dynamic_pointer_cast<Model_Data>(theContext->data());
111   TDF_Label aContextDataLab(aData.get() && aData->isValid() ? aData->label() : TDF_Label());
112   Handle(TNaming_NamedShape) aNS = shapeToNS(myLab, theShape, aContextDataLab);
113   Handle(TDataStd_Name) anAttr;
114   if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document
115     if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
116       if (isNeedContextName && aData && aContextDataLab.IsEqual(aNS->Label())) {
117         // do nothing because this context name will be added later in this method
118       } else {
119         aName = TCollection_AsciiString(anAttr->Get()).ToCString();
120         // indexes are added to sub-shapes not primitives
121         // (primitives must not be located at the same label)
122         if(!aName.empty() && aNS->Evolution() != TNaming_PRIMITIVE && isNeedContextName) {
123           const TDF_Label& aLabel = aNS->Label();
124           static const std::string aPostFix("_");
125           TNaming_Iterator anItL(aNS);
126           for(int i = 1; anItL.More(); anItL.Next(), i++) {
127             // in #1766 IsEqual produced no index of the face
128             if(anItL.NewShape().IsSame(theShape)) {
129               aName += aPostFix;
130               aName += TCollection_AsciiString (i).ToCString();
131               break;
132             }
133           }
134         }
135         // if a shape is under another context, use this name, not theContext
136         std::shared_ptr<Model_Data> aContextData =
137           std::dynamic_pointer_cast<Model_Data>(theContext->data());
138         // for constructions the naming is in arguments and has no evolution, so, apply this only
139         // for bodies
140         if (isNeedContextName && theContext->groupName() == ModelAPI_ResultBody::group() &&
141             !aNS->Label().IsDescendant(aContextData->label())) {
142           isNeedContextName = false;
143           TDF_Label aNSDataLab = aNS->Label();
144           if (aNSDataLab.Depth() % 2 == 0)
145             aNSDataLab = aNSDataLab.Father();
146           ObjectPtr aNewContext = theDoc->objects()->object(aNSDataLab);
147           while(!aNewContext.get() && aNSDataLab.Depth() > 5) {
148             aNSDataLab = aNSDataLab.Father().Father();
149             aNewContext = theDoc->objects()->object(aNSDataLab);
150           }
151           if (aNewContext.get()) {
152             // this is to avoid duplicated names of results problem
153             std::string aContextName = aNewContext->data()->name();
154             // myLab corresponds to the current time
155             TDF_Label aCurrentLab = myLab;
156             while(aCurrentLab.Depth() > 3)
157               aCurrentLab = aCurrentLab.Father();
158
159             int aNumInHistoryNames =
160               theDoc->numberOfNameInHistory(aNewContext, aCurrentLab);
161             while(aNumInHistoryNames > 1) { // add "_" before name the needed number of times
162               aContextName = "_" + aContextName;
163               aNumInHistoryNames--;
164             }
165
166             aName = aContextName + "/" + aName;
167           }
168         }
169       }
170     }
171   }
172
173   // Name is empty and this is full context, it just add the whole context name that must be added
174   bool isEmptyName = aName.empty();
175   if (isNeedContextName && (!isEmptyName || theWholeContext)) {
176     aName = theContext->data()->name() + (isEmptyName ? "" : ("/" + aName));
177     if (theAnotherDoc)
178       aName = theContext->document()->kind() + "/" + aName; // PartSet
179   }
180   return aName;
181 }
182
183 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
184 {
185   // a trivial case: F1 & F2,  aNumber = 1, i.e. intersection gives 1 edge.
186   TopoDS_Compound aCmp;
187   BRep_Builder BB;
188   BB.MakeCompound(aCmp);
189   TopTools_ListIteratorOfListOfShape it(theAncestors);
190   for(;it.More();it.Next()) {
191     if (theSMap.Contains(it.Value()))
192       continue;
193     BB.Add(aCmp, it.Value());
194     theSMap.Add(it.Value());
195   }
196   int aNumber(0);
197   TopTools_IndexedDataMapOfShapeListOfShape aMap2;
198   TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
199   for (int i = 1; i <= aMap2.Extent(); i++) {
200     const TopoDS_Shape& aKey = aMap2.FindKey(i);
201     const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
202     if(anAncestors.Extent() > 1) aNumber++;
203   }
204   if(aNumber > 1) return false;
205   return true;
206 }
207
208 const TopoDS_Shape findCommonShape(
209   const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
210 {
211   if(theList.Extent() < 1) {
212     return TopoDS_Shape();
213   } else if (theList.Extent() == 1) { // check that sub-shape is bounded by this alone shape
214     TopTools_MapOfShape aSubsInShape;
215     TopExp_Explorer anExp(theList.First(), theType);
216     for(; anExp.More(); anExp.Next()) {
217       if (aSubsInShape.Contains(anExp.Current())) { // found duplicate
218         return anExp.Current();
219       }
220       aSubsInShape.Add(anExp.Current());
221     }
222   }
223
224   // Store in maps sub-shapes from each face.
225   std::vector<TopTools_MapOfShape> aVec;
226   for(TopTools_ListIteratorOfListOfShape anIt(theList); anIt.More(); anIt.Next()) {
227     const TopoDS_Shape aFace = anIt.Value();
228     TopTools_MapOfShape aMap;
229     for(TopExp_Explorer anExp(aFace, theType); anExp.More(); anExp.Next()) {
230       const TopoDS_Shape& aSubShape = anExp.Current();
231       aMap.Add(anExp.Current());
232     }
233     aVec.push_back(aMap);
234   }
235
236   // Find sub-shape shared between all faces.
237   TopoDS_Shape aSharedShape;
238   for(TopTools_MapIteratorOfMapOfShape anIt(aVec[0]); anIt.More(); anIt.Next()) {
239     const TopoDS_Shape& aSubShape = anIt.Value();
240     int aSharedNb = 1;
241     for(int anIndex = 1; anIndex < aVec.size(); ++anIndex) {
242       if(aVec[anIndex].Contains(aSubShape)) {
243         ++aSharedNb;
244       }
245     }
246     if(aSharedNb == theList.Extent()) {
247       if(aSharedShape.IsNull()) {
248         aSharedShape = aSubShape;
249       } else {
250         // More than one shape shared between all faces, return null shape in this case.
251         return TopoDS_Shape();
252       }
253     }
254   }
255
256   return aSharedShape;
257 }
258
259 // searches theType shape that contains theConnectionType sub-shapes in each shape from the List,
260 // so, implements the neighbours searching
261 /*
262 const TopoDS_Shape findCommonShapeByNB(const TopAbs_ShapeEnum theType,
263   const TopAbs_ShapeEnum theConnectionType, const TopTools_ListOfShape& theList)
264 {
265 TopTools_MapOfShape aCheckedShapes; // already checked shapes of type theType
266   TopoDS_Shape aResult; // theType result shape
267   for(TopTools_ListIteratorOfListOfShape anIt(theList); anIt.More(); anIt.Next()) { // iterate all
268     for(TopExp_Explorer anExp(anIt.ChangeValue(), theType); anExp.More(); anExp.Next()) {
269       if (aCheckedShapes.Contains(anExp.Current()))
270         continue; // already checked
271       aCheckedShapes.Add(anExp.Current());
272       TopTools_MapOfShape aConnectors; // all connectors of the checked theType shape
273       for(TopExp_Explorer aCExp(anExp.Current(), theConnectionType); aCExp.More(); aCExp.Next()) {
274         aConnectors.Add(aCExp.Current());
275       }
276       // check that all shapes from the List contain the connector sub-shapes
277       bool aFound = true;
278       for(TopTools_ListIteratorOfListOfShape anIt2(theList); anIt2.More() && aFound; anIt2.Next()) {
279         if (anIt2.Value().IsSame(anIt.Value()))
280           continue;
281         aFound = false;
282         for(TopExp_Explorer anE(anIt2.ChangeValue(), theConnectionType); anE.More(); anE.Next()) {
283           if (aConnectors.Contains(anE.Current())) {
284             aFound = true;
285             break;
286           }
287         }
288       }
289       if (aFound) {
290         if (!aResult.IsNull()) // more than one result
291           return TopoDS_Shape();
292         aResult = anExp.Current();
293       }
294     }
295   }
296   return aResult;
297 }*/
298
299 std::string Model_SelectionNaming::vertexNameByEdges(TopoDS_Shape theContext, TopoDS_Shape theSub,
300   std::shared_ptr<Model_Document> theDoc, ResultPtr& theContextRes, const bool theAnotherDoc)
301 {
302   std::string aResult;
303   TopTools_IndexedDataMapOfShapeListOfShape aMap;
304   TopExp::MapShapesAndAncestors(theContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
305   const TopTools_ListOfShape& aList22  = aMap.FindFromKey(theSub);
306   if(aList22.Extent() >= 2)  { // regular solution
307     TopTools_MapOfShape aFMap;
308     TopTools_ListOfShape aListE;
309     TopTools_ListIteratorOfListOfShape itl2(aList22);
310     for (int i = 1;itl2.More();itl2.Next(),i++) {
311       if(aFMap.Add(itl2.Value()))
312         aListE.Append(itl2.Value());
313     }
314     TopTools_ListIteratorOfListOfShape itl(aListE);
315     for (int i = 1;itl.More();itl.Next(),i++) {
316       const TopoDS_Shape& anEdge = itl.Value();
317       std::string anEdgeName = getShapeName(theDoc, anEdge, theContextRes, theAnotherDoc, false);
318       if (anEdgeName.empty()) { // edge is not in DS
319         aResult.clear();
320         return aResult;
321       }
322       if(i == 1)
323         aResult = anEdgeName;
324       else
325         aResult += "&" + anEdgeName;
326     }
327   }
328   return aResult;
329 }
330
331 std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
332   std::shared_ptr<GeomAPI_Shape> theSubSh, const std::string& theDefaultName,
333   const bool theAnotherDoc)
334 {
335   std::string aName("Undefined name");
336   if(!theContext.get()
337       || !theContext->shape().get()
338       || theContext->shape()->isNull()) {
339     return !theDefaultName.empty() ? theDefaultName : aName;
340   }
341
342   // if it is in result of another part
343   std::shared_ptr<Model_Document> aDoc =
344     std::dynamic_pointer_cast<Model_Document>(theContext->document());
345   if (theContext->groupName() == ModelAPI_ResultPart::group()) {
346     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
347     int anIndex;
348     if (theSubSh.get())
349       return aPart->data()->name() + "/" + aPart->nameInPart(theSubSh, anIndex);
350     else
351       return aPart->data()->name();
352   }
353
354   if (!theSubSh.get() || theSubSh->isNull()) { // no subshape, so just the whole feature name
355     // but if it is in another Part, add this part name
356     std::string aPartName;
357     if (theAnotherDoc)
358       aPartName = theContext->document()->kind() + "/"; // PartSet
359     return aPartName + theContext->data()->name();
360   }
361   TopoDS_Shape aSubShape = theSubSh->impl<TopoDS_Shape>();
362   TopoDS_Shape aContext  = theContext->shape()->impl<TopoDS_Shape>();
363 #ifdef DEB_NAMING
364   if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
365     BRepTools::Write(aSubShape, "Selection.brep");
366     BRepTools::Write(aContext, "Context.brep");
367   }
368 #endif
369   aName = getShapeName(aDoc, aSubShape, theContext, theAnotherDoc,
370     theContext->shape()->isEqual(theSubSh));
371
372   if(aName.empty() ) { // not in the document!
373     TopAbs_ShapeEnum aType = aSubShape.ShapeType();
374     switch (aType) {
375     case TopAbs_FACE:
376       // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
377       break;
378     case TopAbs_EDGE:
379       {
380         // name structure: F1 & F2 [& F3 & F4],
381         // where F1 & F2 the faces which gives the Edge in trivial case
382         // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
383         if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
384           aName = "Degenerated_Edge";
385           break;
386         }
387         TopTools_IndexedDataMapOfShapeListOfShape aMap;
388         TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
389         TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
390         bool isTrivialCase(true);
391         if(aMap.Contains(aSubShape)) {
392           const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
393           // check that it is not a trivial case (F1 & F2: aNumber = 1)
394           isTrivialCase = isTrivial(anAncestors, aSMap);
395           if (!isTrivialCase) { // another try: check that common shape can be processed anyway
396             isTrivialCase = !findCommonShape(TopAbs_EDGE, anAncestors).IsNull();
397           }
398         } else
399           break;
400         TopTools_MapOfShape aNbs;
401         if(!isTrivialCase) { // find Neighbors
402           TNaming_Localizer aLocalizer;
403           TopTools_MapOfShape aMap3;
404           aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
405           //int n = aMap3.Extent();
406           TopTools_MapIteratorOfMapOfShape it(aMap3);
407           for(;it.More();it.Next()) {
408             const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
409             //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
410             const TopTools_ListOfShape& aList  = aMap.FindFromKey(aNbShape);
411             TopTools_ListIteratorOfListOfShape it2(aList);
412             for(;it2.More();it2.Next()) {
413               if(aSMap.Contains(it2.Value())) continue; // skip this Face
414               aNbs.Add(it2.Value());
415             }
416           }
417         }  // else a trivial case
418
419         // build name of the sub-shape Edge
420         // iterate faces of the context to get stable order, not map-order
421         TopTools_MapOfShape aStoredFaces; // to avoid duplicates
422         for(TopExp_Explorer aContExp(aContext, TopAbs_FACE); aContExp.More(); aContExp.Next()) {
423           const TopoDS_Shape& aFace = aContExp.Current();
424           if (aStoredFaces.Contains(aFace) || !(aSMap.Contains(aFace) || aNbs.Contains(aFace)))
425             continue;
426           aStoredFaces.Add(aFace);
427           std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
428           if(aName.empty())
429             aName = aFaceName;
430           else
431             aName += "&" + aFaceName;
432         }
433       }
434       break;
435
436     case TopAbs_VERTEX:
437       // name structure (Monifold Topology):
438       // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
439       // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition,
440       //                               but it should be kept as is to obtain safe recomputation
441       // 2) F1 | F2      - intersection of 2 faces definses a vertex - applicable for case
442       //                   when 1 faces is cylindrical, conical, spherical or revolution and etc.
443       // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
444       //                   or compound of 2 open faces.
445       // 4) E1 | E2      - intesection of 2 edges defines a vertex - when we have a case of
446       //                   two independent edges (wire or compound)
447       // implemented 2 first cases
448       {
449         TopTools_IndexedDataMapOfShapeListOfShape aMap;
450         TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
451         TopTools_ListOfShape aList;
452         TopTools_MapOfShape aFMap;
453         // simetimes when group is moved in history, naming may be badly updated, so
454         // avoid crash in FindFromKey (issue 1842)
455         if (aMap.Contains(aSubShape)) {
456           const TopTools_ListOfShape& aList2  = aMap.FindFromKey(aSubShape);
457           // fix is below
458           TopTools_ListIteratorOfListOfShape itl2(aList2);
459           for (int i = 1;itl2.More();itl2.Next(),i++) {
460             if(aFMap.Add(itl2.Value()))
461               aList.Append(itl2.Value());
462           }
463         } else
464           break;
465         int n = aList.Extent();
466         bool isByFaces = n >= 3;
467         if (isByFaces) { // check that by faces vertex is identified uniquly (2317)
468           TopoDS_Shape aVertex = findCommonShape(TopAbs_VERTEX, aList);
469           isByFaces = !aVertex.IsNull() && aVertex.ShapeType() == TopAbs_VERTEX;
470         }
471
472         if(!isByFaces) { // open topology case or Compound case => via edges
473           aName = vertexNameByEdges(aContext, aSubShape, aDoc, theContext, theAnotherDoc);
474           isByFaces = aName.empty();
475           if (isByFaces) { // try to find a vertex in sketch faces
476             ResultConstructionPtr aConstr =
477               std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
478             if (aConstr.get() && aConstr->facesNum()) {
479               for(int aFace = aConstr->facesNum() - 1; isByFaces && aFace >= 0; aFace--) {
480                 std::shared_ptr<GeomAPI_Face> aGFace = aConstr->face(aFace);
481                 aName = vertexNameByEdges(aGFace->impl<TopoDS_Face>(), aSubShape,
482                   aDoc, theContext, theAnotherDoc);
483                 isByFaces = aName.empty();
484               }
485             }
486           }
487         }
488
489         if (isByFaces) {
490           TopTools_ListIteratorOfListOfShape itl(aList);
491           for (int i = 1;itl.More();itl.Next(),i++) {
492             const TopoDS_Shape& aFace = itl.Value();
493             std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
494             if(i == 1)
495               aName = aFaceName;
496             else
497               aName += "&" + aFaceName;
498           }
499         }
500       }
501       break;
502     }
503   }
504   return aName;
505 }
506
507 TopAbs_ShapeEnum translateType (const std::string& theType)
508 {
509   // map from the textual shape types to OCCT enumeration
510   static std::map<std::string, TopAbs_ShapeEnum> aShapeTypes;
511
512   if(aShapeTypes.size() == 0) {
513     aShapeTypes["compound"]   = TopAbs_COMPOUND;
514     aShapeTypes["compounds"]  = TopAbs_COMPOUND;
515     aShapeTypes["compsolid"]  = TopAbs_COMPSOLID;
516     aShapeTypes["compsolids"] = TopAbs_COMPSOLID;
517     aShapeTypes["solid"]      = TopAbs_SOLID;
518     aShapeTypes["solids"]     = TopAbs_SOLID;
519     aShapeTypes["shell"]      = TopAbs_SHELL;
520     aShapeTypes["shells"]     = TopAbs_SHELL;
521     aShapeTypes["face"]       = TopAbs_FACE;
522     aShapeTypes["faces"]      = TopAbs_FACE;
523     aShapeTypes["wire"]       = TopAbs_WIRE;
524     aShapeTypes["wires"]      = TopAbs_WIRE;
525     aShapeTypes["edge"]       = TopAbs_EDGE;
526     aShapeTypes["edges"]      = TopAbs_EDGE;
527     aShapeTypes["vertex"]     = TopAbs_VERTEX;
528     aShapeTypes["vertices"]   = TopAbs_VERTEX;
529     aShapeTypes["COMPOUND"]   = TopAbs_COMPOUND;
530     aShapeTypes["COMPOUNDS"]  = TopAbs_COMPOUND;
531     aShapeTypes["COMPSOLID"]  = TopAbs_COMPSOLID;
532     aShapeTypes["COMPSOLIDS"] = TopAbs_COMPSOLID;
533     aShapeTypes["SOLID"]      = TopAbs_SOLID;
534     aShapeTypes["SOLIDS"]     = TopAbs_SOLID;
535     aShapeTypes["SHELL"]      = TopAbs_SHELL;
536     aShapeTypes["SHELLS"]     = TopAbs_SHELL;
537     aShapeTypes["FACE"]       = TopAbs_FACE;
538     aShapeTypes["FACES"]      = TopAbs_FACE;
539     aShapeTypes["WIRE"]       = TopAbs_WIRE;
540     aShapeTypes["WIRES"]      = TopAbs_WIRE;
541     aShapeTypes["EDGE"]       = TopAbs_EDGE;
542     aShapeTypes["EDGES"]      = TopAbs_EDGE;
543     aShapeTypes["VERTEX"]     = TopAbs_VERTEX;
544     aShapeTypes["VERTICES"]   = TopAbs_VERTEX;
545   }
546   if (aShapeTypes.find(theType) != aShapeTypes.end())
547     return aShapeTypes[theType];
548   Events_InfoMessage("Model_SelectionNaming",
549     "Shape type defined in XML is not implemented!").send();
550   return TopAbs_SHAPE;
551 }
552
553 const TopoDS_Shape getShapeFromNS(
554   const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
555 {
556   TopoDS_Shape aSelection;
557   std::string::size_type n = theSubShapeName.rfind('/');
558   if (n == std::string::npos) n = -1;
559   std::string aSubString = theSubShapeName.substr(n + 1);
560   n = aSubString.rfind('_');
561   int indx = 1;
562   if (n != std::string::npos) {// for primitives this is a first
563     // if we have here the same name as theSubShapeName, there is no index in compound, it is whole
564     Handle(TDataStd_Name) aName;
565     if (!theNS->Label().FindAttribute(TDataStd_Name::GetID(), aName) ||
566         aName->Get() != aSubString.c_str()) {
567       aSubString = aSubString.substr(n+1);
568       indx = atoi(aSubString.c_str());
569     }
570   }
571
572   TNaming_Iterator anItL(theNS);
573   for(int i = 1; anItL.More(); anItL.Next(), i++) {
574     if (i == indx) {
575       return anItL.NewShape();
576     }
577   }
578   return aSelection;
579 }
580
581 const TopoDS_Shape findFaceByName(
582   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
583   const ResultPtr theDetectedContext, bool theContextIsUnique)
584 {
585   TopoDS_Shape aFace;
586   std::string aSubString = theSubShapeName;
587
588   static const ResultPtr anEmpty;
589   TDF_Label aLabel = theDoc->findNamingName(aSubString,
590     theContextIsUnique ? theDetectedContext : anEmpty);
591   if (aLabel.IsNull()) { // try to remove additional artificial suffix
592     std::string::size_type n = aSubString.rfind('_');
593     if (n != std::string::npos) {
594       aSubString = aSubString.substr(0, n);
595       aLabel = theDoc->findNamingName(aSubString,
596         theContextIsUnique ? theDetectedContext : anEmpty);
597     }
598   }
599   if(aLabel.IsNull()) return aFace;
600   Handle(TNaming_NamedShape) aNS;
601   if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
602     aFace = getShapeFromNS(theSubShapeName, aNS);
603   }
604   return aFace;
605 }
606
607 size_t ParseName(const std::string& theSubShapeName,   std::list<std::string>& theList)
608 {
609   std::string aName = theSubShapeName;
610   std::string aLastName = aName;
611   size_t n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
612   while ((n2 = aName.find('&', n1)) != std::string::npos) {
613     const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
614     theList.push_back(aName1);
615     n1 = n2 + 1;
616     aLastName = aName.substr(n1);
617   }
618   if(!aLastName.empty())
619     theList.push_back(aLastName);
620   return theList.size();
621 }
622
623 std::string getContextName(const std::string& theSubShapeName)
624 {
625   std::string aName;
626   std::string::size_type n = theSubShapeName.find('/');
627   if (n == std::string::npos) return theSubShapeName;
628   aName = theSubShapeName.substr(0, n);
629   return aName;
630 }
631
632 /// Parses naming name of sketch sub-elements: takes indices and orientation
633 /// (if theOriented = true) from this name. Map theIDs constains indices ->
634 /// orientations and start/end vertices: negative is reversed, 2 - start, 3 - end
635 bool parseSubIndices(CompositeFeaturePtr theComp, //< to iterate names
636   const std::string& theName, const char* theShapeType,
637   std::map<int, int>& theIDs, const bool theOriented = false)
638 {
639   // collect all IDs in the name
640   std::map<std::string, int> aNames; // short name of sub -> ID of sub of theComp
641   const int aSubNum = theComp->numberOfSubs();
642   for(int a = 0; a < aSubNum; a++) {
643     FeaturePtr aSub = theComp->subFeature(a);
644     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
645     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
646     // there may be many shapes (circle and center)
647     for(; aRes != aResults.cend(); aRes++) {
648       ResultConstructionPtr aConstr =
649         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
650       if (aConstr.get()) {
651         aNames[Model_SelectionNaming::shortName(aConstr)] = theComp->subFeatureId(a);
652       }
653     }
654   }
655
656   size_t aPrevPos = theName.find("/") + 1, aLastNamePos;
657   bool isShape = false; // anyway the first world must be 'Vertex'
658   do {
659     aLastNamePos = theName.find('-', aPrevPos);
660     std::string anID = theName.substr(aPrevPos, aLastNamePos - aPrevPos);
661     if (!isShape) {
662       if (anID != theShapeType)
663         return false;
664       isShape = true;
665     } else {
666       int anOrientation = 1; // default
667       if (theOriented) { // here must be a symbol in the end of digit 'f' or 'r'
668         std::string::iterator aSymbol = anID.end() - 1;
669         if (*aSymbol == 'r') anOrientation = -1;
670         anID.erase(aSymbol); // remove last symbol
671       }
672       // check start/end symbols
673       std::string::iterator aBack = anID.end() - 1;
674       if (*aBack == 's') {
675         anOrientation *= 2;
676         anID.erase(aBack); // remove last symbol
677       } else if (*aBack == 'e') {
678         anOrientation *= 3;
679         anID.erase(aBack); // remove last symbol
680       }
681
682       if (aNames.find(anID) != aNames.end()) {
683         theIDs[aNames[anID]] = anOrientation;
684       }
685     }
686     aPrevPos = aLastNamePos + 1;
687   } while (aLastNamePos != std::string::npos);
688   return true;
689 }
690
691 /// produces theEdge orientation relatively to theContext face
692 int Model_SelectionNaming::edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
693 {
694   if (theContext.ShapeType() != TopAbs_FACE && theContext.ShapeType() != TopAbs_WIRE)
695     return 0;
696   if (theEdge.Orientation() == TopAbs_FORWARD)
697     return 1;
698   if (theEdge.Orientation() == TopAbs_REVERSED)
699     return -1;
700   return 0; // unknown
701 }
702
703 std::shared_ptr<GeomAPI_Shape> Model_SelectionNaming::findAppropriateFace(
704   std::shared_ptr<ModelAPI_Result>& theConstr,
705   NCollection_DataMap<Handle(Geom_Curve), int>& theCurves, const bool theIsWire)
706 {
707   int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
708   int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
709   std::shared_ptr<GeomAPI_Shape> aResult;
710   ResultConstructionPtr aConstructionContext =
711       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theConstr);
712   if (!aConstructionContext.get())
713     return aResult;
714   for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
715     int aFound = 0, aNotFound = 0, aSameOrientation = 0;
716     TopoDS_Face aFace =
717       TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
718     std::list<TopoDS_Shape> aFacesWires; // faces or wires to iterate
719     if (theIsWire) {
720       for(TopExp_Explorer aWires(aFace, TopAbs_WIRE); aWires.More(); aWires.Next()) {
721         aFacesWires.push_back(aWires.Current());
722       }
723     } else {
724       aFacesWires.push_back(aFace);
725     }
726     std::list<TopoDS_Shape>::iterator aFW = aFacesWires.begin();
727     for(; aFW != aFacesWires.end(); aFW++) {
728       TopExp_Explorer anEdgesExp(*aFW, TopAbs_EDGE);
729       TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
730       for(; anEdgesExp.More(); anEdgesExp.Next()) {
731         TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
732         if (!anEdge.IsNull()) {
733           Standard_Real aFirst, aLast;
734           Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
735           if (alreadyProcessed.Contains(aCurve))
736             continue;
737           alreadyProcessed.Add(aCurve);
738           if (theCurves.IsBound(aCurve)) {
739             aFound++;
740             int anOrient = theCurves.Find(aCurve);
741             if (anOrient != 0) {  // extra comparision score is orientation
742               if (edgeOrientation(aFace, anEdge) == anOrient)
743                 aSameOrientation++;
744             }
745           } else {
746             aNotFound++;
747           }
748         }
749       }
750       if (aFound + aNotFound != 0) {
751         if (aFound > aBestFound ||
752           (aFound == aBestFound && aSameOrientation > aBestOrient)) {
753             aBestFound = aFound;
754             aBestOrient = aSameOrientation;
755             if (theIsWire) {
756               std::shared_ptr<GeomAPI_Wire> aWire(new GeomAPI_Wire);
757               aWire->setImpl(new TopoDS_Shape(*aFW));
758               aResult = aWire;
759             } else {
760               aResult = aConstructionContext->face(aFaceIndex);
761             }
762         }
763       }
764     }
765   }
766   return aResult;
767 }
768
769 std::string Model_SelectionNaming::shortName(
770   std::shared_ptr<ModelAPI_ResultConstruction>& theConstr, const int theEdgeVertexPos)
771 {
772   std::string aName = theConstr->data()->name();
773   // remove "-", "/" and "&" command-symbols
774   aName.erase(std::remove(aName.begin(), aName.end(), '-'), aName.end());
775   aName.erase(std::remove(aName.begin(), aName.end(), '/'), aName.end());
776   aName.erase(std::remove(aName.begin(), aName.end(), '&'), aName.end());
777   // remove the last 's', 'e', 'f' and 'r' symbols:
778   // they are used as markers of start/end/forward/rewersed indicators
779   static const std::string aSyms("sefr");
780   std::string::iterator aSuffix = aName.end() - 1;
781   while(aSyms.find(*aSuffix) != std::string::npos) {
782     --aSuffix;
783   }
784   aName.erase(aSuffix + 1, aName.end());
785
786   if (theEdgeVertexPos == 1) {
787     aName += "s"; // start
788   } else if (theEdgeVertexPos == 2) {
789     aName += "e"; // end
790   }
791   return aName;
792 }
793
794 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
795 bool Model_SelectionNaming::selectSubShape(const std::string& theType,
796   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
797   std::shared_ptr<GeomAPI_Shape>& theShapeToBeSelected, std::shared_ptr<ModelAPI_Result>& theCont)
798 {
799   if(theSubShapeName.empty() || theType.empty()) return false;
800   TopAbs_ShapeEnum aType = translateType(theType);
801
802   // check that it was selected in another document
803   size_t aSlash = theSubShapeName.find("/");
804   std::string aSubShapeName = theSubShapeName;
805   std::shared_ptr<Model_Document> aDoc = theDoc;
806   if (aSlash != std::string::npos) {
807     std::string aDocName = theSubShapeName.substr(0, aSlash);
808     ResultPartPtr aFoundPart;
809     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
810     if (aDocName == aRootDoc->kind()) {
811       aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
812     } else {
813       for (int a = aRootDoc->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
814         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
815             aRootDoc->object(ModelAPI_ResultPart::group(), a));
816         if (aPart.get() && aPart->isActivated() && aPart->data()->name() == aDocName) {
817           aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
818           aFoundPart = aPart;
819           break;
820         }
821       }
822     }
823     if (aDoc != theDoc) {
824       // so, the first word is the document name => reduce the string for the next manips
825       aSubShapeName = theSubShapeName.substr(aSlash + 1);
826       if (aSubShapeName.empty() && aFoundPart.get()) { // the whole Part result
827         theCont = aFoundPart;
828         return true;
829       }
830     }
831   }
832
833   std::string aContName = getContextName(aSubShapeName);
834   if(aContName.empty()) return false;
835   bool anUniqueContext = false;
836   ResultPtr aCont = aDoc->findByName(aContName, aSubShapeName, anUniqueContext);
837    // possible this is body where postfix is added to distinguish several shapes on the same label
838   int aSubShapeId = -1; // -1 means sub shape not found
839   // for result body the name wihtout "_" has higher priority than with it: it is always added
840   if ((!aCont.get()/* || (aCont->groupName() == ModelAPI_ResultBody::group())*/) &&
841        aContName == aSubShapeName) {
842     size_t aPostIndex = aContName.rfind('_');
843     if (aPostIndex != std::string::npos) {
844       std::string anEmpty, aSubContName = aContName.substr(0, aPostIndex);
845       ResultPtr aSubCont = aDoc->findByName(aSubContName, anEmpty, anUniqueContext);
846       if (aSubCont.get()) {
847         try {
848           std::string aNum = aContName.substr(aPostIndex + 1);
849           aSubShapeId = std::stoi(aNum);
850         } catch (std::invalid_argument&) {
851           aSubShapeId = -1;
852         }
853         if (aSubShapeId > 0) {
854           aContName = aSubContName;
855           aCont = aSubCont;
856         }
857       }
858     }
859   }
860
861
862   static const ResultPtr anEmpty;
863   TopoDS_Shape aSelection;
864   switch (aType)
865   {
866   case TopAbs_FACE:
867   case TopAbs_WIRE:
868     {
869       aSelection = findFaceByName(aSubShapeName, aDoc, aCont, anUniqueContext);
870     }
871     break;
872   case TopAbs_EDGE:
873     {
874       const TDF_Label& aLabel =
875         aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
876       if(!aLabel.IsNull()) {
877         Handle(TNaming_NamedShape) aNS;
878         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
879           aSelection = getShapeFromNS(aSubShapeName, aNS);
880         }
881       }
882     }
883     break;
884   case TopAbs_VERTEX:
885     {
886       const TDF_Label& aLabel =
887         aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
888       if(!aLabel.IsNull()) {
889         Handle(TNaming_NamedShape) aNS;
890         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
891           aSelection = getShapeFromNS(aSubShapeName, aNS);
892         }
893       }
894     }
895     break;
896   case TopAbs_COMPOUND:
897   case TopAbs_COMPSOLID:
898   case TopAbs_SOLID:
899   case TopAbs_SHELL:
900   default: {//TopAbs_SHAPE
901     /// case when the whole sketch is selected, so,
902     /// selection type is compound, but there is no value
903     if (aCont.get() && aCont->shape().get()) {
904       if (aCont->shape()->impl<TopoDS_Shape>().ShapeType() == aType) {
905         theCont = aCont;
906         return true;
907       } else if (aSubShapeId > 0) { // try to find sub-shape by the index
908         TopExp_Explorer anExp(aCont->shape()->impl<TopoDS_Shape>(), aType);
909         for(; aSubShapeId > 1 && anExp.More(); aSubShapeId--) {
910           anExp.Next();
911         }
912         if (anExp.More()) {
913           std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
914           aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
915           theShapeToBeSelected = aShapeToBeSelected;
916           theCont = aCont;
917           return true;
918         }
919       }
920     }
921     return false;
922     }
923   }
924   if (!aSelection.IsNull() &&
925       aSelection.ShapeType() != aType && aSelection.ShapeType() != TopAbs_COMPOUND)
926       aSelection.Nullify(); // to avoid selection of face instead of edge that is described by face
927   // another try to find edge or vertex by faces
928   std::list<std::string> aListofNames;
929   size_t aN = aSelection.IsNull() ? ParseName(aSubShapeName, aListofNames) : 0;
930   if ((aSelection.IsNull() && (aType == TopAbs_EDGE || aType == TopAbs_VERTEX)) ||
931       (!aSelection.IsNull() && aSelection.ShapeType() != aType)) { // edge by one face as example
932     if(aN >= 1) {
933       TopTools_ListOfShape aList;
934       std::list<std::string>::iterator it = aListofNames.begin();
935       for(; it != aListofNames.end(); it++) {
936         ResultPtr aFaceContext = aCont;
937         if (it != aListofNames.begin()) { // there may be other context for different sub-faces
938           std::string aContName = getContextName(*it);
939           if(!aContName.empty()) {
940             aFaceContext = aDoc->findByName(aContName, *it, anUniqueContext);
941           }
942         }
943         TopoDS_Shape aFace = findFaceByName(*it, aDoc, aFaceContext, anUniqueContext);
944         if (aFace.IsNull() && aFaceContext.get() &&
945             aFaceContext->groupName() == ModelAPI_ResultConstruction::group() ) {
946           // search the construction sub-elements for the intersection if they are in the tree
947           size_t aSlash = it->find("/");
948           if (aSlash != std::string::npos) {
949             std::string aSubShapeName = it->substr(aSlash + 1);
950             aFace = findFaceByName(aSubShapeName, aDoc, aFaceContext, true);
951           }
952         }
953         if(!aFace.IsNull())
954           aList.Append(aFace);
955       }
956       aSelection = findCommonShape(aType, aList);
957       //if (aSelection.IsNull() && aType == TopAbs_EDGE) { // try to find selection by neighbours
958       //  aSelection = findCommonShapeByNB(aType, TopAbs_VERTEX, aList);
959       //}
960     }
961   }
962   // in case of construction, there is no registered names for all sub-elements,
963   // even for the main element; so, trying to find them by name (without "&" intersections)
964   if (aSelection.IsNull() && aN < 2) {
965     size_t aConstrNamePos = aSubShapeName.find("/");
966     bool isFullName = aConstrNamePos == std::string::npos;
967     std::string anEmpty, aContrName = aContName;
968     ResultPtr aConstr = aDoc->findByName(aContrName, anEmpty, anUniqueContext);
969     if (aConstr.get() && aConstr->groupName() == ModelAPI_ResultConstruction::group()) {
970       theCont = aConstr;
971       if (isFullName) {
972         // For the full construction selection shape must be empty.
973         //theShapeToBeSelected = aConstr->shape();
974         return true;
975       }
976       // for sketch sub-elements selected
977       CompositeFeaturePtr aComposite =
978         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aConstr));
979       if (aComposite.get()) {
980         if (aType == TopAbs_VERTEX || aType == TopAbs_EDGE) {
981           // collect all IDs in the name
982           bool isVertexByEdge = false;
983           std::map<int, int> anIDs;
984           if (!parseSubIndices(aComposite, aSubShapeName,
985               aType == TopAbs_EDGE ? "Edge" : "Vertex", anIDs)) {
986             // there is a case when vertex is identified by one circle-edge (2253)
987             if (aType == TopAbs_VERTEX &&
988                 parseSubIndices(aComposite, aSubShapeName, "Edge", anIDs))
989               isVertexByEdge = true;
990             else
991               return false;
992           }
993
994           const int aSubNum = aComposite->numberOfSubs();
995           for(int a = 0; a < aSubNum; a++) {
996             int aCompID = aComposite->subFeatureId(a);
997             if (anIDs.find(aCompID) != anIDs.end()) { // found the vertex/edge shape
998               FeaturePtr aSub = aComposite->subFeature(a);
999               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
1000               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIt = aResults.cbegin();
1001               // there may be many shapes (circle and center)
1002               for(; aRIt != aResults.cend(); aRIt++) {
1003                 ResultConstructionPtr aRes =
1004                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRIt);
1005                 if (aRes) {
1006                   int anOrientation = abs(anIDs[aCompID]);
1007                   TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
1008                   if (anOrientation == 1) {
1009                     if (!isVertexByEdge && aType == aShape.ShapeType()) {
1010                       theShapeToBeSelected = aRes->shape();
1011                       return true;
1012                     } else if (isVertexByEdge && aType != aShape.ShapeType()) {
1013                       // check that there is only one vertex produces by and circular edge
1014                       TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
1015                       TopExp_Explorer anExp(aShape, TopAbs_VERTEX);
1016                       if (anExp.More())
1017                         aShape = anExp.Current();
1018                       anExp.Next();
1019                       if (!anExp.More() || anExp.Current().IsSame(aShape)) {
1020                         std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1021                         aShapeToBeSelected->setImpl(new TopoDS_Shape(aShape));
1022                         theShapeToBeSelected = aShapeToBeSelected;
1023                         return true;
1024                       }
1025                     }
1026                   } else { // take first or second vertex of the edge
1027                     TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
1028                     if (aShape.ShapeType() == TopAbs_VERTEX) continue;
1029                     TopExp_Explorer anExp(aShape, aType);
1030                     for(; anExp.More() && anOrientation != 2; anOrientation--)
1031                       anExp.Next();
1032                     if (anExp.More()) {
1033                       std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1034                       aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
1035                       theShapeToBeSelected = aShapeToBeSelected;
1036                       return true;
1037                     }
1038                   }
1039                 }
1040               }
1041             }
1042           }
1043           // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
1044         } else if (aType == TopAbs_FACE || aType == TopAbs_WIRE) {
1045           std::map<int, int> anIDs;
1046           if (!parseSubIndices(aComposite, aSubShapeName,
1047               aType == TopAbs_FACE ? "Face" : "Wire", anIDs, true))
1048             return false;
1049
1050           // curves and orientations of edges
1051           NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
1052           const int aSubNum = aComposite->numberOfSubs();
1053           for(int a = 0; a < aSubNum; a++) {
1054             int aSubID = aComposite->subFeatureId(a);
1055             if (anIDs.find(aSubID) != anIDs.end()) {
1056               FeaturePtr aSub = aComposite->subFeature(a);
1057               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
1058               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
1059               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
1060                 ResultConstructionPtr aConstr =
1061                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
1062                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
1063                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
1064                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
1065                   if (!anEdge.IsNull()) {
1066                     Standard_Real aFirst, aLast;
1067                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
1068                     allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
1069                   }
1070                 }
1071               }
1072             }
1073           }
1074           std::shared_ptr<GeomAPI_Shape> aFoundFW =
1075             findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
1076           if (aFoundFW.get()) {
1077             theShapeToBeSelected = aFoundFW;
1078             return true;
1079           }
1080         } else if (aType == TopAbs_WIRE) {
1081           // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
1082           std::map<int, int> anIDs;
1083           if (!parseSubIndices(aComposite, aSubShapeName, "Wire", anIDs))
1084             return false;
1085
1086            // curves and orientations of edges
1087           NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
1088           const int aSubNum = aComposite->numberOfSubs();
1089           for(int a = 0; a < aSubNum; a++) {
1090             int aSubID = aComposite->subFeatureId(a);
1091             if (anIDs.find(aSubID) != anIDs.end()) {
1092               FeaturePtr aSub = aComposite->subFeature(a);
1093               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
1094               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
1095               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
1096                 ResultConstructionPtr aConstr =
1097                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
1098                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
1099                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
1100                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
1101                   if (!anEdge.IsNull()) {
1102                     Standard_Real aFirst, aLast;
1103                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
1104                     allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
1105                   }
1106                 }
1107               }
1108             }
1109           }
1110           std::shared_ptr<GeomAPI_Shape> aFoundFW =
1111             findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
1112           if (aFoundFW.get()) {
1113             theShapeToBeSelected = aFoundFW;
1114             return true;
1115           }
1116         }
1117       }
1118     }
1119   } else if (aSelection.IsNull() && aN >= 2 && aType == TopAbs_VERTEX) {
1120     // support of shape name as intersection separated by "&"
1121     static std::string anEdgeType = "edge"; // for now it works only with su-edges
1122     std::list<std::string>::iterator aSubNames = aListofNames.begin();
1123     TopTools_ListOfShape aSubsList;
1124     for(; aSubNames != aListofNames.end(); aSubNames++) {
1125       std::string aSubName = *aSubNames;
1126       std::shared_ptr<GeomAPI_Shape> aSubShapeFound;
1127       std::shared_ptr<ModelAPI_Result> aContextFound;
1128       if (selectSubShape(anEdgeType, aSubName, theDoc, aSubShapeFound, aContextFound)) {
1129         if (aSubShapeFound.get())
1130           aSubsList.Append(aSubShapeFound->impl<TopoDS_Shape>());
1131       }
1132     }
1133     aSelection = findCommonShape(TopAbs_VERTEX, aSubsList);
1134   }
1135   if (!aSelection.IsNull()) {
1136     // Select it (must be after N=0 checking,
1137     // since for simple constructions the shape must be null)
1138     std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1139     aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1140     theShapeToBeSelected = aShapeToBeSelected;
1141     theCont = aCont;
1142     return true;
1143   }
1144
1145   return false;
1146 }