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