]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_SelectionNaming.cpp
Salome HOME
Fixed the coding standards problem
[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           while(aNSDataLab.Depth() != 7 && aNSDataLab.Depth() > 5)
145             aNSDataLab = aNSDataLab.Father();
146           ObjectPtr aNewContext = theDoc->objects()->object(aNSDataLab);
147           if (!aNewContext.get() && aNSDataLab.Depth() == 7) {
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 std::string Model_SelectionNaming::namingName(ResultPtr& theContext,
260   std::shared_ptr<GeomAPI_Shape> theSubSh, const std::string& theDefaultName,
261   const bool theAnotherDoc)
262 {
263   std::string aName("Undefined name");
264   if(!theContext.get()
265       || !theContext->shape().get()
266       || theContext->shape()->isNull()) {
267     return !theDefaultName.empty() ? theDefaultName : aName;
268   }
269
270   // if it is in result of another part
271   std::shared_ptr<Model_Document> aDoc =
272     std::dynamic_pointer_cast<Model_Document>(theContext->document());
273   if (theContext->groupName() == ModelAPI_ResultPart::group()) {
274     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
275     int anIndex;
276     if (theSubSh.get())
277       return aPart->data()->name() + "/" + aPart->nameInPart(theSubSh, anIndex);
278     else
279       return aPart->data()->name();
280   }
281
282   if (!theSubSh.get() || theSubSh->isNull()) { // no subshape, so just the whole feature name
283     // but if it is in another Part, add this part name
284     std::string aPartName;
285     if (theAnotherDoc)
286       aPartName = theContext->document()->kind() + "/"; // PartSet
287     return aPartName + theContext->data()->name();
288   }
289   TopoDS_Shape aSubShape = theSubSh->impl<TopoDS_Shape>();
290   TopoDS_Shape aContext  = theContext->shape()->impl<TopoDS_Shape>();
291 #ifdef DEB_NAMING
292   if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
293     BRepTools::Write(aSubShape, "Selection.brep");
294     BRepTools::Write(aContext, "Context.brep");
295   }
296 #endif
297   aName = getShapeName(aDoc, aSubShape, theContext, theAnotherDoc,
298     theContext->shape()->isEqual(theSubSh));
299
300   if(aName.empty() ) { // not in the document!
301     TopAbs_ShapeEnum aType = aSubShape.ShapeType();
302     switch (aType) {
303     case TopAbs_FACE:
304       // the Face should be in DF. If it is not the case, it is an error ==> to be debugged
305       break;
306     case TopAbs_EDGE:
307       {
308         // name structure: F1 & F2 [& F3 & F4],
309         // where F1 & F2 the faces which gives the Edge in trivial case
310         // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces
311         if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
312           aName = "Degenerated_Edge";
313           break;
314         }
315         TopTools_IndexedDataMapOfShapeListOfShape aMap;
316         TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
317         TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
318         bool isTrivialCase(true);
319         if(aMap.Contains(aSubShape)) {
320           const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
321           // check that it is not a trivial case (F1 & F2: aNumber = 1)
322           isTrivialCase = isTrivial(anAncestors, aSMap);
323           if (!isTrivialCase) { // another try: check that common shape can be processed anyway
324             isTrivialCase = !findCommonShape(TopAbs_EDGE, anAncestors).IsNull();
325           }
326         } else
327           break;
328         TopTools_ListOfShape aListOfNbs;
329         if(!isTrivialCase) { // find Neighbors
330           TNaming_Localizer aLocalizer;
331           TopTools_MapOfShape aMap3;
332           aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
333           //int n = aMap3.Extent();
334           TopTools_MapIteratorOfMapOfShape it(aMap3);
335           for(;it.More();it.Next()) {
336             const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
337             //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
338             const TopTools_ListOfShape& aList  = aMap.FindFromKey(aNbShape);
339             TopTools_ListIteratorOfListOfShape it2(aList);
340             for(;it2.More();it2.Next()) {
341               if(aSMap.Contains(it2.Value())) continue; // skip this Face
342               aListOfNbs.Append(it2.Value());
343             }
344           }
345         }  // else a trivial case
346
347         // build name of the sub-shape Edge
348         for(int i=1; i <= aSMap.Extent(); i++) {
349           const TopoDS_Shape& aFace = aSMap.FindKey(i);
350           std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
351           if(i == 1)
352             aName = aFaceName;
353           else
354             aName += "&" + aFaceName;
355         }
356         TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
357         for (;itl.More();itl.Next()) {
358           std::string aFaceName = getShapeName(aDoc, itl.Value(), theContext, theAnotherDoc, false);
359           aName += "&" + aFaceName;
360         }
361       }
362       break;
363
364     case TopAbs_VERTEX:
365       // name structure (Monifold Topology):
366       // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
367       // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition,
368       //                               but it should be kept as is to obtain safe recomputation
369       // 2) F1 | F2      - intersection of 2 faces definses a vertex - applicable for case
370       //                   when 1 faces is cylindrical, conical, spherical or revolution and etc.
371       // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
372       //                   or compound of 2 open faces.
373       // 4) E1 | E2      - intesection of 2 edges defines a vertex - when we have a case of
374       //                   two independent edges (wire or compound)
375       // implemented 2 first cases
376       {
377         TopTools_IndexedDataMapOfShapeListOfShape aMap;
378         TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
379         TopTools_ListOfShape aList;
380         TopTools_MapOfShape aFMap;
381         // simetimes when group is moved in history, naming may be badly updated, so
382         // avoid crash in FindFromKey (issue 1842)
383         if (aMap.Contains(aSubShape)) {
384           const TopTools_ListOfShape& aList2  = aMap.FindFromKey(aSubShape);
385           // fix is below
386           TopTools_ListIteratorOfListOfShape itl2(aList2);
387           for (int i = 1;itl2.More();itl2.Next(),i++) {
388             if(aFMap.Add(itl2.Value()))
389               aList.Append(itl2.Value());
390           }
391         } else
392           break;
393         int n = aList.Extent();
394         bool isByFaces = n >= 3;
395         if (isByFaces) { // check that by faces vertex is identified uniquly (2317)
396           TopoDS_Shape aVertex = findCommonShape(TopAbs_VERTEX, aList);
397           isByFaces = !aVertex.IsNull() && aVertex.ShapeType() == TopAbs_VERTEX;
398         }
399         if(!isByFaces) { // open topology case or Compound case => via edges
400           TopTools_IndexedDataMapOfShapeListOfShape aMap;
401           TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
402           const TopTools_ListOfShape& aList22  = aMap.FindFromKey(aSubShape);
403           if(aList22.Extent() >= 2)  { // regular solution
404
405             // bug! duplication; fix is below
406             aFMap.Clear();
407             TopTools_ListOfShape aListE;
408             TopTools_ListIteratorOfListOfShape itl2(aList22);
409             for (int i = 1;itl2.More();itl2.Next(),i++) {
410               if(aFMap.Add(itl2.Value()))
411                 aListE.Append(itl2.Value());
412             }
413             n = aListE.Extent();
414             TopTools_ListIteratorOfListOfShape itl(aListE);
415             for (int i = 1;itl.More();itl.Next(),i++) {
416               const TopoDS_Shape& anEdge = itl.Value();
417               std::string anEdgeName = getShapeName(aDoc, anEdge, theContext, theAnotherDoc, false);
418               if (anEdgeName.empty()) { // edge is not in DS, trying by faces anyway
419                 isByFaces = true;
420                 aName.clear();
421                 break;
422               }
423               if(i == 1)
424                 aName = anEdgeName;
425               else
426                 aName += "&" + anEdgeName;
427             }
428           }//reg
429           else { // dangle vertex: if(aList22.Extent() == 1)
430             //it should be already in DF
431           }
432         }
433         if (isByFaces) {
434           TopTools_ListIteratorOfListOfShape itl(aList);
435           for (int i = 1;itl.More();itl.Next(),i++) {
436             const TopoDS_Shape& aFace = itl.Value();
437             std::string aFaceName = getShapeName(aDoc, aFace, theContext, theAnotherDoc, false);
438             if(i == 1)
439               aName = aFaceName;
440             else
441               aName += "&" + aFaceName;
442           }
443         }
444       }
445       break;
446     }
447   }
448
449   return aName;
450 }
451
452 TopAbs_ShapeEnum translateType (const std::string& theType)
453 {
454   // map from the textual shape types to OCCT enumeration
455   static std::map<std::string, TopAbs_ShapeEnum> aShapeTypes;
456
457   if(aShapeTypes.size() == 0) {
458     aShapeTypes["compound"]   = TopAbs_COMPOUND;
459     aShapeTypes["compounds"]  = TopAbs_COMPOUND;
460     aShapeTypes["compsolid"]  = TopAbs_COMPSOLID;
461     aShapeTypes["compsolids"] = TopAbs_COMPSOLID;
462     aShapeTypes["solid"]      = TopAbs_SOLID;
463     aShapeTypes["solids"]     = TopAbs_SOLID;
464     aShapeTypes["shell"]      = TopAbs_SHELL;
465     aShapeTypes["shells"]     = TopAbs_SHELL;
466     aShapeTypes["face"]       = TopAbs_FACE;
467     aShapeTypes["faces"]      = TopAbs_FACE;
468     aShapeTypes["wire"]       = TopAbs_WIRE;
469     aShapeTypes["wires"]      = TopAbs_WIRE;
470     aShapeTypes["edge"]       = TopAbs_EDGE;
471     aShapeTypes["edges"]      = TopAbs_EDGE;
472     aShapeTypes["vertex"]     = TopAbs_VERTEX;
473     aShapeTypes["vertices"]   = TopAbs_VERTEX;
474     aShapeTypes["COMPOUND"]   = TopAbs_COMPOUND;
475     aShapeTypes["COMPOUNDS"]  = TopAbs_COMPOUND;
476     aShapeTypes["COMPSOLID"]  = TopAbs_COMPSOLID;
477     aShapeTypes["COMPSOLIDS"] = TopAbs_COMPSOLID;
478     aShapeTypes["SOLID"]      = TopAbs_SOLID;
479     aShapeTypes["SOLIDS"]     = TopAbs_SOLID;
480     aShapeTypes["SHELL"]      = TopAbs_SHELL;
481     aShapeTypes["SHELLS"]     = TopAbs_SHELL;
482     aShapeTypes["FACE"]       = TopAbs_FACE;
483     aShapeTypes["FACES"]      = TopAbs_FACE;
484     aShapeTypes["WIRE"]       = TopAbs_WIRE;
485     aShapeTypes["WIRES"]      = TopAbs_WIRE;
486     aShapeTypes["EDGE"]       = TopAbs_EDGE;
487     aShapeTypes["EDGES"]      = TopAbs_EDGE;
488     aShapeTypes["VERTEX"]     = TopAbs_VERTEX;
489     aShapeTypes["VERTICES"]   = TopAbs_VERTEX;
490   }
491   if (aShapeTypes.find(theType) != aShapeTypes.end())
492     return aShapeTypes[theType];
493   Events_InfoMessage("Model_SelectionNaming",
494     "Shape type defined in XML is not implemented!").send();
495   return TopAbs_SHAPE;
496 }
497
498 const TopoDS_Shape getShapeFromNS(
499   const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
500 {
501   TopoDS_Shape aSelection;
502   std::string::size_type n = theSubShapeName.rfind('/');
503   if (n == std::string::npos) n = -1;
504   std::string aSubString = theSubShapeName.substr(n + 1);
505   n = aSubString.rfind('_');
506   int indx = 1;
507   if (n != std::string::npos) {// for primitives this is a first
508     // if we have here the same name as theSubShapeName, there is no index in compound, it is whole
509     Handle(TDataStd_Name) aName;
510     if (!theNS->Label().FindAttribute(TDataStd_Name::GetID(), aName) ||
511         aName->Get() != aSubString.c_str()) {
512       aSubString = aSubString.substr(n+1);
513       indx = atoi(aSubString.c_str());
514     }
515   }
516
517   TNaming_Iterator anItL(theNS);
518   for(int i = 1; anItL.More(); anItL.Next(), i++) {
519     if (i == indx) {
520       return anItL.NewShape();
521     }
522   }
523   return aSelection;
524 }
525
526 const TopoDS_Shape findFaceByName(
527   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
528   const ResultPtr theDetectedContext, bool theContextIsUnique)
529 {
530   TopoDS_Shape aFace;
531   std::string aSubString = theSubShapeName;
532
533   static const ResultPtr anEmpty;
534   TDF_Label aLabel = theDoc->findNamingName(aSubString,
535     theContextIsUnique ? theDetectedContext : anEmpty);
536   if (aLabel.IsNull()) { // try to remove additional artificial suffix
537     std::string::size_type n = aSubString.rfind('_');
538     if (n != std::string::npos) {
539       aSubString = aSubString.substr(0, n);
540       aLabel = theDoc->findNamingName(aSubString,
541         theContextIsUnique ? theDetectedContext : anEmpty);
542     }
543   }
544   if(aLabel.IsNull()) return aFace;
545   Handle(TNaming_NamedShape) aNS;
546   if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
547     aFace = getShapeFromNS(theSubShapeName, aNS);
548   }
549   return aFace;
550 }
551
552 size_t ParseName(const std::string& theSubShapeName,   std::list<std::string>& theList)
553 {
554   std::string aName = theSubShapeName;
555   std::string aLastName = aName;
556   size_t n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
557   while ((n2 = aName.find('&', n1)) != std::string::npos) {
558     const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
559     theList.push_back(aName1);
560     n1 = n2 + 1;
561     aLastName = aName.substr(n1);
562   }
563   if(!aLastName.empty())
564     theList.push_back(aLastName);
565   return theList.size();
566 }
567
568 std::string getContextName(const std::string& theSubShapeName)
569 {
570   std::string aName;
571   std::string::size_type n = theSubShapeName.find('/');
572   if (n == std::string::npos) return theSubShapeName;
573   aName = theSubShapeName.substr(0, n);
574   return aName;
575 }
576
577 /// Parses naming name of sketch sub-elements: takes indices and orientation
578 /// (if theOriented = true) from this name. Map theIDs constains indices ->
579 /// orientations and start/end vertices: negative is reversed, 2 - start, 3 - end
580 bool parseSubIndices(CompositeFeaturePtr theComp, //< to iterate names
581   const std::string& theName, const char* theShapeType,
582   std::map<int, int>& theIDs, const bool theOriented = false)
583 {
584   // collect all IDs in the name
585   std::map<std::string, int> aNames; // short name of sub -> ID of sub of theComp
586   const int aSubNum = theComp->numberOfSubs();
587   for(int a = 0; a < aSubNum; a++) {
588     FeaturePtr aSub = theComp->subFeature(a);
589     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
590     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
591     // there may be many shapes (circle and center)
592     for(; aRes != aResults.cend(); aRes++) {
593       ResultConstructionPtr aConstr =
594         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
595       if (aConstr.get()) {
596         aNames[Model_SelectionNaming::shortName(aConstr)] = theComp->subFeatureId(a);
597       }
598     }
599   }
600
601   size_t aPrevPos = theName.find("/") + 1, aLastNamePos;
602   bool isShape = false; // anyway the first world must be 'Vertex'
603   do {
604     aLastNamePos = theName.find('-', aPrevPos);
605     std::string anID = theName.substr(aPrevPos, aLastNamePos - aPrevPos);
606     if (!isShape) {
607       if (anID != theShapeType)
608         return false;
609       isShape = true;
610     } else {
611       int anOrientation = 1; // default
612       if (theOriented) { // here must be a symbol in the end of digit 'f' or 'r'
613         std::string::iterator aSymbol = anID.end() - 1;
614         if (*aSymbol == 'r') anOrientation = -1;
615         anID.erase(aSymbol); // remove last symbol
616       }
617       // check start/end symbols
618       std::string::iterator aBack = anID.end() - 1;
619       if (*aBack == 's') {
620         anOrientation *= 2;
621         anID.erase(aBack); // remove last symbol
622       } else if (*aBack == 'e') {
623         anOrientation *= 3;
624         anID.erase(aBack); // remove last symbol
625       }
626
627       if (aNames.find(anID) != aNames.end()) {
628         theIDs[aNames[anID]] = anOrientation;
629       }
630     }
631     aPrevPos = aLastNamePos + 1;
632   } while (aLastNamePos != std::string::npos);
633   return true;
634 }
635
636 /// produces theEdge orientation relatively to theContext face
637 int Model_SelectionNaming::edgeOrientation(const TopoDS_Shape& theContext, TopoDS_Edge& theEdge)
638 {
639   if (theContext.ShapeType() != TopAbs_FACE && theContext.ShapeType() != TopAbs_WIRE)
640     return 0;
641   if (theEdge.Orientation() == TopAbs_FORWARD)
642     return 1;
643   if (theEdge.Orientation() == TopAbs_REVERSED)
644     return -1;
645   return 0; // unknown
646 }
647
648 std::shared_ptr<GeomAPI_Shape> Model_SelectionNaming::findAppropriateFace(
649   std::shared_ptr<ModelAPI_Result>& theConstr,
650   NCollection_DataMap<Handle(Geom_Curve), int>& theCurves, const bool theIsWire)
651 {
652   int aBestFound = 0; // best number of found edges (not percentage: issue 1019)
653   int aBestOrient = 0; // for the equal "BestFound" additional parameter is orientation
654   std::shared_ptr<GeomAPI_Shape> aResult;
655   ResultConstructionPtr aConstructionContext =
656       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theConstr);
657   if (!aConstructionContext.get())
658     return aResult;
659   for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
660     int aFound = 0, aNotFound = 0, aSameOrientation = 0;
661     TopoDS_Face aFace =
662       TopoDS::Face(aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>());
663     std::list<TopoDS_Shape> aFacesWires; // faces or wires to iterate
664     if (theIsWire) {
665       for(TopExp_Explorer aWires(aFace, TopAbs_WIRE); aWires.More(); aWires.Next()) {
666         aFacesWires.push_back(aWires.Current());
667       }
668     } else {
669       aFacesWires.push_back(aFace);
670     }
671     std::list<TopoDS_Shape>::iterator aFW = aFacesWires.begin();
672     for(; aFW != aFacesWires.end(); aFW++) {
673       TopExp_Explorer anEdgesExp(*aFW, TopAbs_EDGE);
674       TColStd_MapOfTransient alreadyProcessed; // to avoid counting edges with same curved (841)
675       for(; anEdgesExp.More(); anEdgesExp.Next()) {
676         TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
677         if (!anEdge.IsNull()) {
678           Standard_Real aFirst, aLast;
679           Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
680           if (alreadyProcessed.Contains(aCurve))
681             continue;
682           alreadyProcessed.Add(aCurve);
683           if (theCurves.IsBound(aCurve)) {
684             aFound++;
685             int anOrient = theCurves.Find(aCurve);
686             if (anOrient != 0) {  // extra comparision score is orientation
687               if (edgeOrientation(aFace, anEdge) == anOrient)
688                 aSameOrientation++;
689             }
690           } else {
691             aNotFound++;
692           }
693         }
694       }
695       if (aFound + aNotFound != 0) {
696         if (aFound > aBestFound ||
697           (aFound == aBestFound && aSameOrientation > aBestOrient)) {
698             aBestFound = aFound;
699             aBestOrient = aSameOrientation;
700             if (theIsWire) {
701               std::shared_ptr<GeomAPI_Wire> aWire(new GeomAPI_Wire);
702               aWire->setImpl(new TopoDS_Shape(*aFW));
703               aResult = aWire;
704             } else {
705               aResult = aConstructionContext->face(aFaceIndex);
706             }
707         }
708       }
709     }
710   }
711   return aResult;
712 }
713
714 std::string Model_SelectionNaming::shortName(
715   std::shared_ptr<ModelAPI_ResultConstruction>& theConstr, const int theEdgeVertexPos)
716 {
717   std::string aName = theConstr->data()->name();
718   // remove "-", "/" and "&" command-symbols
719   aName.erase(std::remove(aName.begin(), aName.end(), '-'), aName.end());
720   aName.erase(std::remove(aName.begin(), aName.end(), '/'), aName.end());
721   aName.erase(std::remove(aName.begin(), aName.end(), '&'), aName.end());
722   // remove the last 's', 'e', 'f' and 'r' symbols:
723   // they are used as markers of start/end/forward/rewersed indicators
724   static const std::string aSyms("sefr");
725   std::string::iterator aSuffix = aName.end() - 1;
726   while(aSyms.find(*aSuffix) != std::string::npos) {
727     --aSuffix;
728   }
729   aName.erase(aSuffix + 1, aName.end());
730
731   if (theEdgeVertexPos == 1) {
732     aName += "s"; // start
733   } else if (theEdgeVertexPos == 2) {
734     aName += "e"; // end
735   }
736   return aName;
737 }
738
739 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
740 bool Model_SelectionNaming::selectSubShape(const std::string& theType,
741   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc,
742   std::shared_ptr<GeomAPI_Shape>& theShapeToBeSelected, std::shared_ptr<ModelAPI_Result>& theCont)
743 {
744   if(theSubShapeName.empty() || theType.empty()) return false;
745   TopAbs_ShapeEnum aType = translateType(theType);
746
747   // check that it was selected in another document
748   size_t aSlash = theSubShapeName.find("/");
749   std::string aSubShapeName = theSubShapeName;
750   std::shared_ptr<Model_Document> aDoc = theDoc;
751   if (aSlash != std::string::npos) {
752     std::string aDocName = theSubShapeName.substr(0, aSlash);
753     ResultPartPtr aFoundPart;
754     DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
755     if (aDocName == aRootDoc->kind()) {
756       aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
757     } else {
758       for (int a = aRootDoc->size(ModelAPI_ResultPart::group()) - 1; a >= 0; a--) {
759         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(
760             aRootDoc->object(ModelAPI_ResultPart::group(), a));
761         if (aPart.get() && aPart->isActivated() && aPart->data()->name() == aDocName) {
762           aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
763           aFoundPart = aPart;
764           break;
765         }
766       }
767     }
768     if (aDoc != theDoc) {
769       // so, the first word is the document name => reduce the string for the next manips
770       aSubShapeName = theSubShapeName.substr(aSlash + 1);
771       if (aSubShapeName.empty() && aFoundPart.get()) { // the whole Part result
772         theCont = aFoundPart;
773         return true;
774       }
775     }
776   }
777
778   std::string aContName = getContextName(aSubShapeName);
779   if(aContName.empty()) return false;
780   bool anUniqueContext = false;
781   ResultPtr aCont = aDoc->findByName(aContName, aSubShapeName, anUniqueContext);
782    // possible this is body where postfix is added to distinguish several shapes on the same label
783   int aSubShapeId = -1; // -1 means sub shape not found
784   // for result body the name wihtout "_" has higher priority than with it: it is always added
785   if ((!aCont.get()/* || (aCont->groupName() == ModelAPI_ResultBody::group())*/) &&
786        aContName == aSubShapeName) {
787     size_t aPostIndex = aContName.rfind('_');
788     if (aPostIndex != std::string::npos) {
789       std::string anEmpty, aSubContName = aContName.substr(0, aPostIndex);
790       ResultPtr aSubCont = aDoc->findByName(aSubContName, anEmpty, anUniqueContext);
791       if (aSubCont.get()) {
792         try {
793           std::string aNum = aContName.substr(aPostIndex + 1);
794           aSubShapeId = std::stoi(aNum);
795         } catch (std::invalid_argument&) {
796           aSubShapeId = -1;
797         }
798         if (aSubShapeId > 0) {
799           aContName = aSubContName;
800           aCont = aSubCont;
801         }
802       }
803     }
804   }
805
806
807   static const ResultPtr anEmpty;
808   TopoDS_Shape aSelection;
809   switch (aType)
810   {
811   case TopAbs_FACE:
812   case TopAbs_WIRE:
813     {
814       aSelection = findFaceByName(aSubShapeName, aDoc, aCont, anUniqueContext);
815     }
816     break;
817   case TopAbs_EDGE:
818     {
819       const TDF_Label& aLabel =
820         aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
821       if(!aLabel.IsNull()) {
822         Handle(TNaming_NamedShape) aNS;
823         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
824           aSelection = getShapeFromNS(aSubShapeName, aNS);
825         }
826       }
827     }
828     break;
829   case TopAbs_VERTEX:
830     {
831       const TDF_Label& aLabel =
832         aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
833       if(!aLabel.IsNull()) {
834         Handle(TNaming_NamedShape) aNS;
835         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
836           aSelection = getShapeFromNS(aSubShapeName, aNS);
837         }
838       }
839     }
840     break;
841   case TopAbs_COMPOUND:
842   case TopAbs_COMPSOLID:
843   case TopAbs_SOLID:
844   case TopAbs_SHELL:
845   default: {//TopAbs_SHAPE
846     /// case when the whole sketch is selected, so,
847     /// selection type is compound, but there is no value
848     if (aCont.get() && aCont->shape().get()) {
849       if (aCont->shape()->impl<TopoDS_Shape>().ShapeType() == aType) {
850         theCont = aCont;
851         return true;
852       } else if (aSubShapeId > 0) { // try to find sub-shape by the index
853         TopExp_Explorer anExp(aCont->shape()->impl<TopoDS_Shape>(), aType);
854         for(; aSubShapeId > 1 && anExp.More(); aSubShapeId--) {
855           anExp.Next();
856         }
857         if (anExp.More()) {
858           std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
859           aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
860           theShapeToBeSelected = aShapeToBeSelected;
861           theCont = aCont;
862           return true;
863         }
864       }
865     }
866     return false;
867     }
868   }
869   if (!aSelection.IsNull() &&
870       aSelection.ShapeType() != aType && aSelection.ShapeType() != TopAbs_COMPOUND)
871       aSelection.Nullify(); // to avoid selection of face instead of edge that is described by face
872   // another try to find edge or vertex by faces
873   std::list<std::string> aListofNames;
874   size_t aN = aSelection.IsNull() ? ParseName(aSubShapeName, aListofNames) : 0;
875   if ((aSelection.IsNull() && (aType == TopAbs_EDGE || aType == TopAbs_VERTEX)) ||
876       (!aSelection.IsNull() && aSelection.ShapeType() != aType)) { // edge by one face as example
877     if(aN >= 1) {
878       TopTools_ListOfShape aList;
879       std::list<std::string>::iterator it = aListofNames.begin();
880       for(; it != aListofNames.end(); it++) {
881         ResultPtr aFaceContext = aCont;
882         if (it != aListofNames.begin()) { // there may be other context for different sub-faces
883           std::string aContName = getContextName(*it);
884           if(!aContName.empty()) {
885             aFaceContext = aDoc->findByName(aContName, *it, anUniqueContext);
886           }
887         }
888         TopoDS_Shape aFace = findFaceByName(*it, aDoc, aFaceContext, anUniqueContext);
889         if (aFace.IsNull() && aFaceContext.get() &&
890             aFaceContext->groupName() == ModelAPI_ResultConstruction::group() ) {
891           // search the construction sub-elements for the intersection if they are in the tree
892           size_t aSlash = it->find("/");
893           if (aSlash != std::string::npos) {
894             std::string aSubShapeName = it->substr(aSlash + 1);
895             aFace = findFaceByName(aSubShapeName, aDoc, aFaceContext, true);
896           }
897         }
898         if(!aFace.IsNull())
899           aList.Append(aFace);
900       }
901       aSelection = findCommonShape(aType, aList);
902     }
903   }
904   // in case of construction, there is no registered names for all sub-elements,
905   // even for the main element; so, trying to find them by name (without "&" intersections)
906   if (aSelection.IsNull() && aN < 2) {
907     size_t aConstrNamePos = aSubShapeName.find("/");
908     bool isFullName = aConstrNamePos == std::string::npos;
909     std::string anEmpty, aContrName = aContName;
910     ResultPtr aConstr = aDoc->findByName(aContrName, anEmpty, anUniqueContext);
911     if (aConstr.get() && aConstr->groupName() == ModelAPI_ResultConstruction::group()) {
912       theCont = aConstr;
913       if (isFullName) {
914         // For the full construction selection shape must be empty.
915         //theShapeToBeSelected = aConstr->shape();
916         return true;
917       }
918       // for sketch sub-elements selected
919       CompositeFeaturePtr aComposite =
920         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aConstr));
921       if (aComposite.get()) {
922         if (aType == TopAbs_VERTEX || aType == TopAbs_EDGE) {
923           // collect all IDs in the name
924           bool isVertexByEdge = false;
925           std::map<int, int> anIDs;
926           if (!parseSubIndices(aComposite, aSubShapeName,
927               aType == TopAbs_EDGE ? "Edge" : "Vertex", anIDs)) {
928             // there is a case when vertex is identified by one circle-edge (2253)
929             if (aType == TopAbs_VERTEX &&
930                 parseSubIndices(aComposite, aSubShapeName, "Edge", anIDs))
931               isVertexByEdge = true;
932             else
933               return false;
934           }
935
936           const int aSubNum = aComposite->numberOfSubs();
937           for(int a = 0; a < aSubNum; a++) {
938             int aCompID = aComposite->subFeatureId(a);
939             if (anIDs.find(aCompID) != anIDs.end()) { // found the vertex/edge shape
940               FeaturePtr aSub = aComposite->subFeature(a);
941               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
942               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIt = aResults.cbegin();
943               // there may be many shapes (circle and center)
944               for(; aRIt != aResults.cend(); aRIt++) {
945                 ResultConstructionPtr aRes =
946                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRIt);
947                 if (aRes) {
948                   int anOrientation = abs(anIDs[aCompID]);
949                   TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
950                   if (anOrientation == 1) {
951                     if (!isVertexByEdge && aType == aShape.ShapeType()) {
952                       theShapeToBeSelected = aRes->shape();
953                       return true;
954                     } else if (isVertexByEdge && aType != aShape.ShapeType()) {
955                       // check that there is only one vertex produces by and circular edge
956                       TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
957                       TopExp_Explorer anExp(aShape, TopAbs_VERTEX);
958                       if (anExp.More())
959                         aShape = anExp.Current();
960                       anExp.Next();
961                       if (!anExp.More() || anExp.Current().IsSame(aShape)) {
962                         std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
963                         aShapeToBeSelected->setImpl(new TopoDS_Shape(aShape));
964                         theShapeToBeSelected = aShapeToBeSelected;
965                         return true;
966                       }
967                     }
968                   } else { // take first or second vertex of the edge
969                     TopoDS_Shape aShape = aRes->shape()->impl<TopoDS_Shape>();
970                     if (aShape.ShapeType() == TopAbs_VERTEX) continue;
971                     TopExp_Explorer anExp(aShape, aType);
972                     for(; anExp.More() && anOrientation != 2; anOrientation--)
973                       anExp.Next();
974                     if (anExp.More()) {
975                       std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
976                       aShapeToBeSelected->setImpl(new TopoDS_Shape(anExp.Current()));
977                       theShapeToBeSelected = aShapeToBeSelected;
978                       return true;
979                     }
980                   }
981                 }
982               }
983             }
984           }
985           // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
986         } else if (aType == TopAbs_FACE || aType == TopAbs_WIRE) {
987           std::map<int, int> anIDs;
988           if (!parseSubIndices(aComposite, aSubShapeName,
989               aType == TopAbs_FACE ? "Face" : "Wire", anIDs, true))
990             return false;
991
992           // curves and orientations of edges
993           NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
994           const int aSubNum = aComposite->numberOfSubs();
995           for(int a = 0; a < aSubNum; a++) {
996             int aSubID = aComposite->subFeatureId(a);
997             if (anIDs.find(aSubID) != anIDs.end()) {
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 aRes;
1001               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
1002                 ResultConstructionPtr aConstr =
1003                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
1004                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
1005                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
1006                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
1007                   if (!anEdge.IsNull()) {
1008                     Standard_Real aFirst, aLast;
1009                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
1010                     allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
1011                   }
1012                 }
1013               }
1014             }
1015           }
1016           std::shared_ptr<GeomAPI_Shape> aFoundFW =
1017             findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
1018           if (aFoundFW.get()) {
1019             theShapeToBeSelected = aFoundFW;
1020             return true;
1021           }
1022         } else if (aType == TopAbs_WIRE) {
1023           // sketch faces is identified by format "Sketch_1/Face-2f-8f-11r"
1024           std::map<int, int> anIDs;
1025           if (!parseSubIndices(aComposite, aSubShapeName, "Wire", anIDs))
1026             return false;
1027
1028            // curves and orientations of edges
1029           NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
1030           const int aSubNum = aComposite->numberOfSubs();
1031           for(int a = 0; a < aSubNum; a++) {
1032             int aSubID = aComposite->subFeatureId(a);
1033             if (anIDs.find(aSubID) != anIDs.end()) {
1034               FeaturePtr aSub = aComposite->subFeature(a);
1035               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
1036               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
1037               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
1038                 ResultConstructionPtr aConstr =
1039                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
1040                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
1041                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
1042                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
1043                   if (!anEdge.IsNull()) {
1044                     Standard_Real aFirst, aLast;
1045                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
1046                     allCurves.Bind(aCurve, anIDs[aSubID] > 0 ? 1 : -1);
1047                   }
1048                 }
1049               }
1050             }
1051           }
1052           std::shared_ptr<GeomAPI_Shape> aFoundFW =
1053             findAppropriateFace(aConstr, allCurves, aType == TopAbs_WIRE);
1054           if (aFoundFW.get()) {
1055             theShapeToBeSelected = aFoundFW;
1056             return true;
1057           }
1058         }
1059       }
1060     }
1061   }
1062   if (!aSelection.IsNull()) {
1063     // Select it (must be after N=0 checking,
1064     // since for simple constructions the shape must be null)
1065     std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1066     aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1067     theShapeToBeSelected = aShapeToBeSelected;
1068     theCont = aCont;
1069     return true;
1070   }
1071
1072   return false;
1073 }