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