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