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