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