Salome HOME
864975b2e420376c6e57cdaf72d97e2de995c274
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_AttributeSelection.h
4 // Created:     2 Oct 2014
5 // Author:      Mikhail PONIKAROV
6
7 #include "Model_AttributeSelection.h"
8 #include "Model_Application.h"
9 #include "Model_Events.h"
10 #include "Model_Data.h"
11 #include "Model_Document.h"
12 #include <ModelAPI_Feature.h>
13 #include <ModelAPI_ResultBody.h>
14 #include <ModelAPI_ResultConstruction.h>
15 #include <ModelAPI_ResultPart.h>
16 #include <ModelAPI_CompositeFeature.h>
17 #include <GeomAPI_Shape.h>
18 #include <GeomAPI_PlanarEdges.h>
19 #include <Events_Error.h>
20
21 #include <TNaming_Selector.hxx>
22 #include <TNaming_NamedShape.hxx>
23 #include <TNaming_Tool.hxx>
24 #include <TNaming_Builder.hxx>
25 #include <TNaming_Localizer.hxx>
26 #include <TopoDS_Shape.hxx>
27 #include <TopoDS_Compound.hxx>
28 #include <TDataStd_IntPackedMap.hxx>
29 #include <TDataStd_Integer.hxx>
30 #include <TDataStd_UAttribute.hxx>
31 #include <TDataStd_Name.hxx>
32 #include <TopTools_MapOfShape.hxx>
33 #include <TopTools_IndexedMapOfShape.hxx>
34 #include <TopTools_MapIteratorOfMapOfShape.hxx>
35 #include <TopTools_ListOfShape.hxx>
36 #include <TopExp_Explorer.hxx>
37 #include <TDF_LabelMap.hxx>
38 #include <BRep_Tool.hxx>
39 #include <BRep_Builder.hxx>
40 #include <TopoDS_Edge.hxx>
41 #include <TopoDS.hxx>
42 #include <TopExp.hxx>
43 #include <TColStd_MapOfTransient.hxx>
44 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
45 #include <TopTools_ListIteratorOfListOfShape.hxx>
46 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
47 #include <gp_Pnt.hxx>
48 #include <Precision.hxx>
49 #include <TDF_ChildIterator.hxx>
50 #include <TDF_ChildIDIterator.hxx>
51 #include <TDataStd_Name.hxx>
52 #include <TopAbs_ShapeEnum.hxx>
53 #include <TopoDS_Iterator.hxx>
54 #include <TNaming_Iterator.hxx>
55 using namespace std;
56 //#define DEB_NAMING 1
57 #ifdef DEB_NAMING
58 #include <BRepTools.hxx>
59 #endif
60 /// adeed to the index in the packed map to signalize that the vertex of edge is seleted
61 /// (multiplied by the index of the edge)
62 static const int kSTART_VERTEX_DELTA = 1000000;
63 // identifier that there is simple reference: selection equals to context
64 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
65 // simple reference in the construction
66 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
67 // reference to Part sub-object
68 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
69
70 // on this label is stored:
71 // TNaming_NamedShape - selected shape
72 // TNaming_Naming - topological selection information (for the body)
73 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
74 // TDataStd_Integer - type of the selected shape (for construction)
75 // TDF_Reference - from ReferenceAttribute, the context
76 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
77   const std::shared_ptr<GeomAPI_Shape>& theSubShape)
78 {
79   const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
80   bool isOldContext = theContext == myRef.value();
81   bool isOldShape = isOldContext &&
82     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
83   if (isOldShape) return; // shape is the same, so context is also unchanged
84   // update the referenced object if needed
85   if (!isOldContext)
86     myRef.setValue(theContext);
87
88   // do noth use naming if selected shape is result shape itself, but not sub-shape
89   TDF_Label aSelLab = selectionLabel();
90   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
91   aSelLab.ForgetAttribute(kCONSTUCTION_SIMPLE_REF_ID);
92
93   bool isDegeneratedEdge = false;
94   // do not use the degenerated edge as a shape, a null context and shape is used in the case
95   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
96     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
97     if (aSubShape.ShapeType() == TopAbs_EDGE)
98       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
99   }
100   if (!theContext.get() || isDegeneratedEdge) {
101     // to keep the reference attribute label
102     TDF_Label aRefLab = myRef.myRef->Label();
103     aSelLab.ForgetAllAttributes(true);
104     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
105     return;
106   }
107   if (theContext->groupName() == ModelAPI_ResultBody::group()) {
108     // do not select the whole shape for body:it is already must be in the data framework
109     // equal and null selected objects mean the same: object is equal to context,
110     // TODO: synchronize with GUI later that it must be null always
111     if (theContext->shape().get() && 
112         (theContext->shape()->isEqual(theSubShape) || !theSubShape.get())) {
113       aSelLab.ForgetAllAttributes(true);
114       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
115     } else {
116       selectBody(theContext, theSubShape);
117     }
118   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
119     if (!theSubShape.get()) {
120       // to sub, so the whole result is selected
121       aSelLab.ForgetAllAttributes(true);
122       TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
123     } else {
124       selectConstruction(theContext, theSubShape);
125     }
126   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
127     aSelLab.ForgetAllAttributes(true);
128     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
129     selectPart(theContext, theSubShape);
130   }
131   //the attribute initialized state should be changed by sendAttributeUpdated only
132   //myIsInitialized = true;
133
134   owner()->data()->sendAttributeUpdated(this);
135
136   std::string aSelName = namingName();
137   if(!aSelName.empty())
138     TDataStd_Name::Set(selectionLabel(), aSelName.c_str()); //set name
139 }
140
141 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
142 {
143   std::shared_ptr<GeomAPI_Shape> aResult;
144   if (myRef.isInitialized()) {
145     TDF_Label aSelLab = selectionLabel();
146     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
147       ResultPtr aContext = context();
148       if (!aContext.get()) 
149         return aResult; // empty result
150       return aContext->shape();
151     }
152     if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
153         return aResult; // empty result
154     }
155     if (aSelLab.IsAttribute(kPART_REF_ID)) {
156       /* TODO: implement used text here
157       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
158       if (!aPart.get() || !aPart->isActivated())
159         return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
160       Handle(TDataStd_Integer) anIndex;
161       if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
162         return aPart->selectionValue(anIndex->Get());
163       }
164       Handle(TDataStd_Name) aName;
165       if (!selectionLabel().FindAttribute(TDataStd_Name::GetID(), aName)) {
166         return std::shared_ptr<GeomAPI_Shape>(); // something is wrong
167       }
168       return aPart->shapeInPart(TCollection_AsciiString(aName).ToCString());
169       */
170     }
171
172     Handle(TNaming_NamedShape) aSelection;
173     if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
174       TopoDS_Shape aSelShape = aSelection->Get();
175       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
176       aResult->setImpl(new TopoDS_Shape(aSelShape));
177     } else { // for simple construction element: just shape of this construction element
178       ResultConstructionPtr aConstr = 
179         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
180       if (aConstr) {
181         return aConstr->shape();
182       }
183     }
184   }
185   return aResult;
186 }
187
188 bool Model_AttributeSelection::isInitialized()
189 {
190   if (ModelAPI_AttributeSelection::isInitialized()) { // additional checkings if it is initialized
191     std::shared_ptr<GeomAPI_Shape> aResult;
192     if (myRef.isInitialized()) {
193       TDF_Label aSelLab = selectionLabel();
194       if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
195         ResultPtr aContext = context();
196         return aContext.get();
197       }
198       if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, nothing is in value
199           return true;
200       }
201
202       Handle(TNaming_NamedShape) aSelection;
203       if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
204         return !aSelection->Get().IsNull();
205       } else { // for simple construction element: just shape of this construction element
206         ResultConstructionPtr aConstr = 
207           std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
208         if (aConstr.get()) {
209           return aConstr->shape().get();
210         }
211       }
212     }
213   }
214   return false;
215 }
216
217 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
218   : myRef(theLabel)
219 {
220   myIsInitialized = myRef.isInitialized();
221 }
222
223 void Model_AttributeSelection::setID(const std::string theID)
224 {
225   myRef.setID(theID);
226   ModelAPI_AttributeSelection::setID(theID);
227 }
228
229 ResultPtr Model_AttributeSelection::context() {
230   return std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
231 }
232
233
234 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
235 {
236   ModelAPI_AttributeSelection::setObject(theObject);
237   myRef.setObject(theObject);
238 }
239
240 TDF_LabelMap& Model_AttributeSelection::scope()
241 {
242   if (myScope.IsEmpty()) { // create a new scope if not yet done
243     // gets all labels with named shapes that are bofore this feature label (before in history)
244     TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
245       owner()->data())->label().Father();
246     int aFeatureID = aFeatureLab.Tag();
247     TDF_ChildIterator aFeaturesIter(aFeatureLab.Father());
248     for(; aFeaturesIter.More(); aFeaturesIter.Next()) {
249       if (aFeaturesIter.Value().Tag() >= aFeatureID) // the left labels are created later
250         break;
251       TDF_ChildIDIterator aNSIter(aFeaturesIter.Value(), TNaming_NamedShape::GetID(), 1);
252       for(; aNSIter.More(); aNSIter.Next()) {
253         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
254         if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
255           myScope.Add(aNS->Label());
256         }
257       }
258     }
259   }
260   return myScope;
261 }
262
263 bool Model_AttributeSelection::update()
264 {
265   ResultPtr aContext = context();
266   if (!aContext.get()) return false;
267   TDF_Label aSelLab = selectionLabel();
268   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
269     return aContext->shape() && !aContext->shape()->isNull();
270   }
271   if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) { // it is just reference to construction, not sub-shape
272     return aContext->shape() && !aContext->shape()->isNull();
273   }
274
275   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
276     std::shared_ptr<GeomAPI_Shape> aNoSelection;
277     return selectPart(aContext, aNoSelection, true);
278   }
279
280   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
281     // body: just a named shape, use selection mechanism from OCCT
282     TNaming_Selector aSelector(aSelLab);
283     bool aResult = aSelector.Solve(scope()) == Standard_True;
284     owner()->data()->sendAttributeUpdated(this);
285     return aResult;
286   } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
287     // construction: identification by the results indexes, recompute faces and
288     // take the face that more close by the indexes
289     ResultConstructionPtr aConstructionContext = 
290       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
291     FeaturePtr aContextFeature = aContext->document()->feature(aContext);
292     // sketch sub-element
293     if (aConstructionContext && 
294         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
295     {
296       TDF_Label aLab = myRef.myRef->Label();
297       // getting a type of selected shape
298       Handle(TDataStd_Integer) aTypeAttr;
299       if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
300         return false;
301       }
302       TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
303       // selected indexes will be needed in each "if"
304       Handle(TDataStd_IntPackedMap) aSubIds;
305       std::shared_ptr<GeomAPI_Shape> aNewSelected;
306       bool aNoIndexes = 
307         !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
308       // for now working only with composite features
309       CompositeFeaturePtr aComposite = 
310         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
311       if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
312         return false;
313       }
314
315       if (aShapeType == TopAbs_FACE) { // compound is for the whole sketch selection
316         // If this is a wire with plane defined thin it is a sketch-like object
317         if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
318           return false;
319         // if there is no edges indexes, any face can be used: take the first
320         std::shared_ptr<GeomAPI_Shape> aNewSelected;
321         if (aNoIndexes) {
322           aNewSelected = aConstructionContext->face(0);
323         } else { // searching for most looks-like initial face by the indexes
324           // prepare edges of the current resut for the fast searching
325           TColStd_MapOfTransient allCurves;
326           const int aSubNum = aComposite->numberOfSubs();
327           for(int a = 0; a < aSubNum; a++) {
328             if (aSubIds->Contains(aComposite->subFeatureId(a))) {
329               FeaturePtr aSub = aComposite->subFeature(a);
330               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
331               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
332               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
333                 ResultConstructionPtr aConstr = 
334                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
335                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
336                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
337                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
338                   if (!anEdge.IsNull()) {
339                     Standard_Real aFirst, aLast;
340                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
341                     allCurves.Add(aCurve);
342                   }
343                 }
344               }
345             }
346           }
347           double aBestFound = 0; // best percentage of found edges
348           for(int aFaceIndex = 0; aFaceIndex < aConstructionContext->facesNum(); aFaceIndex++) {
349             int aFound = 0, aNotFound = 0;
350             TopExp_Explorer anEdgesExp(
351               aConstructionContext->face(aFaceIndex)->impl<TopoDS_Shape>(), TopAbs_EDGE);
352             for(; anEdgesExp.More(); anEdgesExp.Next()) {
353               TopoDS_Edge anEdge = TopoDS::Edge(anEdgesExp.Current());
354               if (!anEdge.IsNull()) {
355                 Standard_Real aFirst, aLast;
356                 Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
357                 if (allCurves.Contains(aCurve)) {
358                   aFound++;
359                 } else {
360                   aNotFound++;
361                 }
362               }
363             }
364             if (aFound + aNotFound != 0) {
365               double aPercentage = double(aFound) / double(aFound + aNotFound);
366               if (aPercentage > aBestFound) {
367                 aBestFound = aPercentage;
368                 aNewSelected = aConstructionContext->face(aFaceIndex);
369               }
370             }
371           }
372         }
373         if (aNewSelected) { // store this new selection
374           selectConstruction(aContext, aNewSelected);
375           owner()->data()->sendAttributeUpdated(this);
376           return true;
377         }
378       } else if (aShapeType == TopAbs_EDGE) {
379         // just reselect the edge by the id
380         const int aSubNum = aComposite->numberOfSubs();
381         for(int a = 0; a < aSubNum; a++) {
382           // if aSubIds take any, the first appropriate
383           if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
384             // found the appropriate feature
385             FeaturePtr aFeature = aComposite->subFeature(a);
386             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
387               aFeature->results().cbegin();
388             for(;aResIter != aFeature->results().cend(); aResIter++) {
389               ResultConstructionPtr aRes = 
390                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
391               if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
392                 selectConstruction(aContext, aRes->shape());
393                 owner()->data()->sendAttributeUpdated(this);
394                 return true;
395               }
396             }
397           }
398         }
399       } else if (aShapeType == TopAbs_VERTEX) {
400         // just reselect the vertex by the id of edge
401         const int aSubNum = aComposite->numberOfSubs();
402         for(int a = 0; a < aSubNum; a++) {
403           // if aSubIds take any, the first appropriate
404           int aFeatureID = aComposite->subFeatureId(a);
405           if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
406             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
407             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
408               // searching for deltas
409               int aVertexNum = 0;
410               if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
411               else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
412               // found the feature with appropriate edge
413               FeaturePtr aFeature = aComposite->subFeature(a);
414               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
415                 aFeature->results().cbegin();
416               for(;aResIter != aFeature->results().cend(); aResIter++) {
417                 ResultConstructionPtr aRes = 
418                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
419                 if (aRes && aRes->shape()) {
420                   if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
421                     selectConstruction(aContext, aRes->shape());
422                     owner()->data()->sendAttributeUpdated(this);
423                     return true;
424                   } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
425                     const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
426                     int aVIndex = 1;
427                     for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
428                       if (aVIndex == aVertexNum) { // found!
429                         std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
430                         aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
431                         selectConstruction(aContext, aVertex);
432                         owner()->data()->sendAttributeUpdated(this);
433                         return true;
434                       }
435                       aVIndex++;
436                     }
437                   }
438                 }
439               }
440           }
441         }
442       }
443     } else { // simple construction element: the selected is that needed
444       selectConstruction(aContext, aContext->shape());
445       owner()->data()->sendAttributeUpdated(this);
446       return true;
447     }
448   }
449   return false; // unknown case
450 }
451
452
453 void Model_AttributeSelection::selectBody(
454   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
455 {
456   // perform the selection
457   TNaming_Selector aSel(selectionLabel());
458   TopoDS_Shape aContext;
459
460   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
461   if (aBody) {
462     aContext = aBody->shape()->impl<TopoDS_Shape>();
463   } else {
464     ResultPtr aResult = 
465       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
466     if (aResult) {
467       aContext = aResult->shape()->impl<TopoDS_Shape>();
468     } else {
469       Events_Error::send("A result with shape is expected");
470       return;
471     }
472   }
473   TopoDS_Shape aNewShape = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
474   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
475   /*
476   FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
477   if (aFeatureOwner.get())
478     aFeatureOwner->eraseResults();
479     */
480   if (!aContext.IsNull()) {
481     aSel.Select(aNewShape, aContext); 
482   }
483 }
484
485 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
486 /// if theID is zero, 
487 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
488   const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
489   std::string theAdditionalName,
490   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)())
491 {
492   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
493   TNaming_Builder aBuilder(aLab);
494   aBuilder.Generated(theShape);
495   std::stringstream aName;
496   aName<<theContextFeature->name()<<"/";
497   if (!theAdditionalName.empty())
498     aName<<theAdditionalName<<"/";
499   if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
500   else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
501   else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
502
503   if (theRefs.IsNull()) {
504     aName<<theID;
505   } else { // make a compisite name from all sub-elements indexes: "1_2_3_4"
506     TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
507     for(; aRef.More(); aRef.Next()) {
508       aName<<"-"<<aRef.Key();
509     }
510   }
511
512   theDoc->addNamingName(aLab, aName.str());
513   TDataStd_Name::Set(aLab, aName.str().c_str());
514 }
515
516 void Model_AttributeSelection::selectConstruction(
517   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
518 {
519   std::shared_ptr<Model_Document> aMyDoc = 
520     std::dynamic_pointer_cast<Model_Document>(owner()->document());
521   FeaturePtr aContextFeature = theContext->document()->feature(theContext);
522   CompositeFeaturePtr aComposite = 
523     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
524   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
525   if (!aComposite || aComposite->numberOfSubs() == 0) {
526     // saving of context is enough: result construction contains exactly the needed shape
527     TNaming_Builder aBuilder(selectionLabel());
528     aBuilder.Generated(aSubShape);
529     aMyDoc->addNamingName(selectionLabel(), theContext->data()->name());
530     TDataStd_Name::Set(selectionLabel(), theContext->data()->name().c_str());
531     return;
532   }
533   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
534   TDF_Label aLab = myRef.myRef->Label();
535   // identify the reuslts of sub-object of the composite by edges
536   // save type of the selected shape in integer attribute
537   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
538   TDataStd_Integer::Set(aLab, (int)aShapeType);
539   gp_Pnt aVertexPos;
540   TColStd_MapOfTransient allCurves;
541   if (aShapeType == TopAbs_VERTEX) { // compare positions
542     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
543   } else { 
544     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
545       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
546       Standard_Real aFirst, aLast;
547       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
548       allCurves.Add(aCurve);
549     }
550   }
551   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
552   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
553   aRefs->Clear();
554   const int aSubNum = aComposite->numberOfSubs();
555   for(int a = 0; a < aSubNum; a++) {
556     FeaturePtr aSub = aComposite->subFeature(a);
557     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
558     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
559     // there may be many shapes (circle and center): register if at least one is in selection
560     for(; aRes != aResults.cend(); aRes++) {
561       ResultConstructionPtr aConstr = 
562         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
563       if (!aConstr->shape()) {
564         continue;
565       }
566       if (aShapeType == TopAbs_VERTEX) {
567         if (aConstr->shape()->isVertex()) { // compare vertices positions
568           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
569           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
570           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
571             aRefs->Add(aComposite->subFeatureId(a));
572           }
573         } else { // get first or last vertex of the edge: last is stored with negative sign
574           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
575           int aDelta = kSTART_VERTEX_DELTA;
576           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
577             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
578             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
579               aRefs->Add(aDelta + aComposite->subFeatureId(a));
580               break;
581             }
582             aDelta += kSTART_VERTEX_DELTA;
583           }
584         }
585       } else {
586         if (aConstr->shape()->isEdge()) {
587           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
588           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
589           if (!anEdge.IsNull()) {
590             Standard_Real aFirst, aLast;
591             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
592             if (allCurves.Contains(aCurve)) {
593               int anID = aComposite->subFeatureId(a);
594               aRefs->Add(anID);
595               if (aShapeType != TopAbs_EDGE) { // edge do not need the sub-edges on sub-labels
596                 // add edges to sub-label to support naming for edges selection
597                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
598                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
599                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
600                   Standard_Real aFirst, aLast;
601                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
602                   if (aFaceCurve == aCurve) {
603                     registerSubShape(selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, "");
604                   }
605                 }
606               } else { // put vertices of the selected edge to sub-labels
607                 // add edges to sub-label to support naming for edges selection
608                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
609                 int aTagIndex = anID + kSTART_VERTEX_DELTA;
610                 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
611                   TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
612
613                   std::stringstream anAdditionalName; 
614                   registerSubShape(selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc,
615                     "");
616                 }
617               }
618             }
619           }
620         }
621       }
622     }
623   }
624   // store the selected as primitive
625   TNaming_Builder aBuilder(selectionLabel());
626   aBuilder.Generated(aSubShape);
627   registerSubShape(selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, "", aRefs);
628 }
629
630 bool Model_AttributeSelection::selectPart(
631   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
632   const bool theUpdate)
633 {
634   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
635   if (!aPart.get() || !aPart->isActivated())
636     return true; // postponed naming
637   if (theUpdate) {
638     Handle(TDataStd_Integer) anIndex;
639     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) { // by internal selection
640       if (anIndex->Get() > 0) {
641         // update the selection by index
642         return aPart->updateInPart(anIndex->Get());
643       } else {
644         return true; // nothing to do, referencing just by name
645       }
646     }
647     return true; // nothing to do, referencing just by name
648   }
649   // store the shape (in case part is not loaded it should be usefull
650   TopoDS_Shape aShape;
651   std::string aName = theContext->data()->name();
652   if (theSubShape->isNull()) {// the whole part shape is selected
653     aShape = theContext->shape()->impl<TopoDS_Shape>();
654   } else {
655     aShape = theSubShape->impl<TopoDS_Shape>();
656     int anIndex;
657     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
658     TDataStd_Integer::Set(selectionLabel(), anIndex);
659   }
660   TNaming_Builder aBuilder(selectionLabel());
661   aBuilder.Select(aShape, aShape);
662   // identify by name in the part
663   TDataStd_Name::Set(selectionLabel(), aName.c_str());
664   return !aName.empty();
665 }
666
667 TDF_Label Model_AttributeSelection::selectionLabel()
668 {
669   return myRef.myRef->Label().FindChild(1);
670 }
671
672 #define FIX_BUG1 1
673 std::string GetShapeName(std::shared_ptr<Model_Document> theDoc, const TopoDS_Shape& theShape, 
674   const TDF_Label& theLabel)
675 {
676   std::string aName;
677   // check if the subShape is already in DF
678   Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(theShape, theLabel);
679   Handle(TDataStd_Name) anAttr;
680   if(!aNS.IsNull() && !aNS->IsEmpty()) { // in the document    
681     if(aNS->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
682       aName = TCollection_AsciiString(anAttr->Get()).ToCString();
683       if(!aName.empty()) {          
684         const TDF_Label& aLabel = theDoc->findNamingName(aName);
685         /* MPV: the same shape with the same name may be duplicated on different labels (selection of the same construction object)
686         if(!aLabel.IsEqual(aNS->Label())) {
687         //aName.erase(); //something is wrong, to be checked!!!
688         aName += "_SomethingWrong";
689         return aName;
690         }*/
691
692         static const std::string aPostFix("_");
693         TNaming_Iterator anItL(aNS);
694         for(int i = 1; anItL.More(); anItL.Next(), i++) {
695           if(anItL.NewShape() == theShape) {
696             aName += aPostFix;
697             aName += TCollection_AsciiString (i).ToCString();
698             break;
699           }
700         }
701         /* MPV: the code below does not work because of TNaming_Tool.cxx line 145: aNS->Get() uses maps
702         const TopoDS_Shape& aShape = aNS->Get();
703         if(aShape.ShapeType() == TopAbs_COMPOUND) {
704         std::string aPostFix("_");
705         TopoDS_Iterator it(aShape);                     
706         for (int i = 1;it.More();it.Next(), i++) {
707         if(it.Value() == theShape) {
708         aPostFix += TCollection_AsciiString (i).ToCString();
709         aName    += aPostFix;
710         break;
711         }
712         else continue;                                          
713         }
714         }
715         */
716       } 
717     }
718   }
719   return aName;
720 }
721
722 bool isTrivial (const TopTools_ListOfShape& theAncestors, TopTools_IndexedMapOfShape& theSMap)
723 {
724   // a trivial case: F1 & F2,  aNumber = 1, i.e. intersection gives 1 edge.
725   TopoDS_Compound aCmp;
726   BRep_Builder BB;
727   BB.MakeCompound(aCmp);
728   TopTools_ListIteratorOfListOfShape it(theAncestors);
729   for(;it.More();it.Next()) {
730     BB.Add(aCmp, it.Value());
731     theSMap.Add(it.Value());
732   }
733   int aNumber(0);
734   TopTools_IndexedDataMapOfShapeListOfShape aMap2;
735   TopExp::MapShapesAndAncestors(aCmp, TopAbs_EDGE, TopAbs_FACE, aMap2);
736   for (int i = 1; i <= aMap2.Extent(); i++) {
737     const TopoDS_Shape& aKey = aMap2.FindKey(i);
738     const TopTools_ListOfShape& anAncestors = aMap2.FindFromIndex(i);
739     if(anAncestors.Extent() > 1) aNumber++;
740   }
741   if(aNumber > 1) return false;
742   return true;
743 }
744 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
745 {
746   std::string aName("");
747   if(!this->isInitialized())
748     return !theDefaultName.empty() ? theDefaultName : aName;
749   Handle(TDataStd_Name) anAtt;
750   if(selectionLabel().FindAttribute(TDataStd_Name::GetID(), anAtt)) {
751     aName = TCollection_AsciiString(anAtt->Get()).ToCString();
752     return aName;
753   }
754
755   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
756   ResultPtr aCont = context();
757   aName = "Undefined name";
758   if(!aCont.get() || aCont->shape()->isNull()) 
759     return !theDefaultName.empty() ? theDefaultName : aName;
760   if (!aSubSh.get() || aSubSh->isNull()) { // no subshape, so just the whole feature name
761     return aCont->data()->name();
762   }
763   TopoDS_Shape aSubShape = aSubSh->impl<TopoDS_Shape>();
764   TopoDS_Shape aContext  = aCont->shape()->impl<TopoDS_Shape>();
765 #ifdef DEB_NAMING
766   if(aSubShape.ShapeType() == TopAbs_COMPOUND) {
767   BRepTools::Write(aSubShape, "Selection.brep");
768   BRepTools::Write(aContext, "Context.brep");
769   }
770 #endif
771   std::shared_ptr<Model_Document> aDoc = 
772     std::dynamic_pointer_cast<Model_Document>(aCont->document());
773
774   // check if the subShape is already in DF
775   aName = GetShapeName(aDoc, aSubShape, selectionLabel());
776   if(aName.empty() ) { // not in the document!
777     TopAbs_ShapeEnum aType = aSubShape.ShapeType();
778     switch (aType) {
779     case TopAbs_FACE:
780       // the Face should be in DF. If it is not the case, it is an error ==> to be debugged             
781                 break;
782           case TopAbs_EDGE:
783                   {
784                   // name structure: F1 | F2 [| F3 | F4], where F1 & F2 the faces which gives the Edge in trivial case
785                   // if it is not atrivial case we use localization by neighbours. F3 & F4 - neighbour faces    
786                   if (BRep_Tool::Degenerated(TopoDS::Edge(aSubShape))) {
787                           aName = "Degenerated_Edge";
788                           break;
789                   }    
790                   TopTools_IndexedDataMapOfShapeListOfShape aMap;
791                   TopExp::MapShapesAndAncestors(aContext, TopAbs_EDGE, TopAbs_FACE, aMap);
792                   TopTools_IndexedMapOfShape aSMap; // map for ancestors of the sub-shape
793                   bool isTrivialCase(true);
794 /*                for (int i = 1; i <= aMap.Extent(); i++) {
795                         const TopoDS_Shape& aKey = aMap.FindKey(i);
796                         //if (aKey.IsNotEqual(aSubShape)) continue; // find exactly the selected key
797                         if (aKey.IsSame(aSubShape)) continue;
798             const TopTools_ListOfShape& anAncestors = aMap.FindFromIndex(i);
799                         // check that it is not a trivial case (F1 & F2: aNumber = 1)
800                         isTrivialCase = isTrivial(anAncestors, aSMap);                  
801                         break;
802                   }*/
803                   if(aMap.Contains(aSubShape)) {
804                         const TopTools_ListOfShape& anAncestors = aMap.FindFromKey(aSubShape);
805                         // check that it is not a trivial case (F1 & F2: aNumber = 1)
806                         isTrivialCase = isTrivial(anAncestors, aSMap);          
807                   } else 
808                           break;
809                   TopTools_ListOfShape aListOfNbs;
810                   if(!isTrivialCase) { // find Neighbors
811                         TNaming_Localizer aLocalizer;
812                         TopTools_MapOfShape aMap3;
813                         aLocalizer.FindNeighbourg(aContext, aSubShape, aMap3);
814                         //int n = aMap3.Extent();
815                         TopTools_MapIteratorOfMapOfShape it(aMap3);
816                         for(;it.More();it.Next()) {
817                           const TopoDS_Shape& aNbShape = it.Key(); // neighbor edge
818                           //TopAbs_ShapeEnum aType = aNbShape.ShapeType();
819                           const TopTools_ListOfShape& aList  = aMap.FindFromKey(aNbShape);
820                           TopTools_ListIteratorOfListOfShape it2(aList);
821                           for(;it2.More();it2.Next()) {
822                                 if(aSMap.Contains(it2.Value())) continue; // skip this Face
823                                 aListOfNbs.Append(it2.Value());
824                           }
825                         }
826                   }  // else a trivial case
827                   
828                   // build name of the sub-shape Edge
829                   for(int i=1; i <= aSMap.Extent(); i++) {
830                         const TopoDS_Shape& aFace = aSMap.FindKey(i);
831                         std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
832                         if(i == 1)
833                           aName = aFaceName;
834                         else 
835                           aName += "|" + aFaceName;
836                   }
837                   TopTools_ListIteratorOfListOfShape itl(aListOfNbs);
838                   for (;itl.More();itl.Next()) {
839                         std::string aFaceName = GetShapeName(aDoc, itl.Value(), selectionLabel());
840                         aName += "|" + aFaceName;
841                   }               
842                   }
843                   break;
844
845     case TopAbs_VERTEX:
846       // name structure (Monifold Topology): 
847       // 1) F1 | F2 | F3 - intersection of 3 faces defines a vertex - trivial case.
848       // 2) F1 | F2 | F3 [|F4 [|Fn]] - redundant definition, but it should be kept as is to obtain safe recomputation
849       // 2) F1 | F2      - intersection of 2 faces definses a vertex - applicable for case
850       //                   when 1 faces is cylindrical, conical, spherical or revolution and etc.
851       // 3) E1 | E2 | E3 - intersection of 3 edges defines a vertex - when we have case of a shell
852       //                   or compound of 2 open faces.
853       // 4) E1 | E2      - intesection of 2 edges defines a vertex - when we have a case of 
854       //                   two independent edges (wire or compound)
855       // implemented 2 first cases
856       {
857         TopTools_IndexedDataMapOfShapeListOfShape aMap;
858         TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_FACE, aMap);
859         const TopTools_ListOfShape& aList2  = aMap.FindFromKey(aSubShape);
860         TopTools_ListOfShape aList;
861         TopTools_MapOfShape aFMap;
862 #ifdef FIX_BUG1
863         //int n = aList2.Extent(); //bug! duplication
864         // fix is below
865         TopTools_ListIteratorOfListOfShape itl2(aList2);
866         for (int i = 1;itl2.More();itl2.Next(),i++) {
867           if(aFMap.Add(itl2.Value()))
868             aList.Append(itl2.Value());
869         }
870         //n = aList.Extent();
871 #endif
872         int n = aList.Extent();
873         if(n < 3) { // open topology case or Compound case => via edges
874           TopTools_IndexedDataMapOfShapeListOfShape aMap;
875           TopExp::MapShapesAndAncestors(aContext, TopAbs_VERTEX, TopAbs_EDGE, aMap);
876           const TopTools_ListOfShape& aList22  = aMap.FindFromKey(aSubShape);
877           if(aList22.Extent() >= 2)  { // regular solution
878 #ifdef FIX_BUG1
879
880             // bug! duplication; fix is below
881             aFMap.Clear();
882             TopTools_ListOfShape aListE;
883             TopTools_ListIteratorOfListOfShape itl2(aList22);
884             for (int i = 1;itl2.More();itl2.Next(),i++) {
885               if(aFMap.Add(itl2.Value()))
886                 aListE.Append(itl2.Value());
887             }
888             n = aListE.Extent();
889 #endif
890             TopTools_ListIteratorOfListOfShape itl(aListE);
891             for (int i = 1;itl.More();itl.Next(),i++) {
892               const TopoDS_Shape& anEdge = itl.Value();
893               std::string anEdgeName = GetShapeName(aDoc, anEdge, selectionLabel());
894               if(i == 1)
895                 aName = anEdgeName;
896               else 
897                 aName += "|" + anEdgeName;
898             }
899           }//reg
900           else { // dangle vertex: if(aList22.Extent() == 1)
901             //it should be already in DF
902           }
903         } 
904         else {
905           TopTools_ListIteratorOfListOfShape itl(aList);
906           for (int i = 1;itl.More();itl.Next(),i++) {
907             const TopoDS_Shape& aFace = itl.Value();
908             std::string aFaceName = GetShapeName(aDoc, aFace, selectionLabel());
909             if(i == 1)
910               aName = aFaceName;
911             else 
912               aName += "|" + aFaceName;
913           }
914         }
915       }
916       break;
917     }
918     // register name                    
919     // aDoc->addNamingName(selectionLabel(), aName);
920     // the selected sub-shape will not be shared and as result it will not require registration
921   }
922   return aName;
923 }
924
925 TopAbs_ShapeEnum translateType (const std::string& theType)
926 {
927   // map from the textual shape types to OCCT enumeration
928   static std::map<std::string, TopAbs_ShapeEnum> MyShapeTypes;
929   if (MyShapeTypes.size() == 0) {
930     MyShapeTypes["face"] = TopAbs_FACE;
931     MyShapeTypes["faces"] = TopAbs_FACE;
932     MyShapeTypes["vertex"] = TopAbs_VERTEX;
933     MyShapeTypes["vertices"] = TopAbs_VERTEX;
934     MyShapeTypes["wire"] = TopAbs_WIRE;
935     MyShapeTypes["edge"] = TopAbs_EDGE;
936     MyShapeTypes["edges"] = TopAbs_EDGE;
937     MyShapeTypes["shell"] = TopAbs_SHELL;
938     MyShapeTypes["solid"] = TopAbs_SOLID;
939     MyShapeTypes["solids"] = TopAbs_SOLID;
940     MyShapeTypes["FACE"] = TopAbs_FACE;
941     MyShapeTypes["FACES"] = TopAbs_FACE;
942     MyShapeTypes["VERTEX"] = TopAbs_VERTEX;
943     MyShapeTypes["VERTICES"] = TopAbs_VERTEX;
944     MyShapeTypes["WIRE"] = TopAbs_WIRE;
945     MyShapeTypes["EDGE"] = TopAbs_EDGE;
946     MyShapeTypes["EDGES"] = TopAbs_EDGE;
947     MyShapeTypes["SHELL"] = TopAbs_SHELL;
948     MyShapeTypes["SOLID"] = TopAbs_SOLID;
949     MyShapeTypes["SOLIDS"] = TopAbs_SOLID;
950   }
951   if (MyShapeTypes.find(theType) != MyShapeTypes.end())
952     return MyShapeTypes[theType];
953   Events_Error::send("Shape type defined in XML is not implemented!");
954   return TopAbs_SHAPE;
955 }
956
957 const TopoDS_Shape getShapeFromNS(
958   const std::string& theSubShapeName, Handle(TNaming_NamedShape) theNS)
959 {
960   TopoDS_Shape aSelection;
961   std::string::size_type n = theSubShapeName.rfind('/');                        
962   if (n == std::string::npos) n = 0;
963   std::string aSubString = theSubShapeName.substr(n + 1);
964   n = aSubString.rfind('_');
965   if (n == std::string::npos) return aSelection;
966   aSubString = aSubString.substr(n+1);
967   int indx = atoi(aSubString.c_str());
968
969   TNaming_Iterator anItL(theNS);
970   for(int i = 1; anItL.More(); anItL.Next(), i++) {
971     if (i == indx) {
972       return anItL.NewShape();
973     }
974   }
975   return aSelection;    
976 }
977
978 const TopoDS_Shape findFaceByName(
979   const std::string& theSubShapeName, std::shared_ptr<Model_Document> theDoc)
980 {
981   TopoDS_Shape aFace;
982   std::string::size_type n, nb = theSubShapeName.rfind('/');                    
983   if (nb == std::string::npos) nb = 0;
984   std::string aSubString = theSubShapeName.substr(nb + 1);
985   n = aSubString.rfind('_');
986   if (n != std::string::npos) {
987     std::string aSubStr2 = aSubString.substr(0, n);
988     aSubString  = theSubShapeName.substr(0, nb + 1);
989     aSubString = aSubString + aSubStr2; 
990   } else
991     aSubString = theSubShapeName;
992
993   const TDF_Label& aLabel = theDoc->findNamingName(aSubString);
994   if(aLabel.IsNull()) return aFace;
995   Handle(TNaming_NamedShape) aNS;
996   if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
997     aFace = getShapeFromNS(theSubShapeName, aNS);
998   }
999   return aFace;
1000 }
1001
1002 int ParseName(const std::string& theSubShapeName,   std::list<std::string>& theList)
1003 {
1004   std::string aName = theSubShapeName;
1005   std::string aLastName;
1006   int n1(0), n2(0); // n1 - start position, n2 - position of the delimiter
1007   while ((n2 = aName.find('|', n1)) != std::string::npos) {
1008     const std::string aName1 = aName.substr(n1, n2 - n1); //name of face
1009     theList.push_back(aName1);  
1010     n1 = n2 + 1;
1011     aLastName = aName.substr(n1);
1012   }
1013   if(!aLastName.empty())
1014     theList.push_back(aLastName);
1015   return theList.size();
1016 }
1017
1018 const TopoDS_Shape findCommonShape(
1019   const TopAbs_ShapeEnum theType, const TopTools_ListOfShape& theList)
1020 {
1021   TopoDS_Shape aShape;
1022   std::vector<TopTools_MapOfShape> aVec;
1023   TopTools_MapOfShape aMap1, aMap2, aMap3, aMap4;
1024   if(theList.Extent() > 1) {
1025     aVec.push_back(aMap1);
1026     aVec.push_back(aMap2);
1027   }
1028   if(theList.Extent() > 2)
1029     aVec.push_back(aMap3);
1030   if(theList.Extent() == 4)
1031     aVec.push_back(aMap4);
1032
1033   //fill maps
1034   TopTools_ListIteratorOfListOfShape it(theList);
1035   for(int i = 0;it.More();it.Next(),i++) {
1036     const TopoDS_Shape& aFace = it.Value();             
1037     if(i < 2) {
1038       TopExp_Explorer anExp (aFace, theType);
1039       for(;anExp.More();anExp.Next()) {
1040         const TopoDS_Shape& anEdge = anExp.Current();
1041         if (!anEdge.IsNull())
1042           aVec[i].Add(anExp.Current());
1043       }
1044     } else {
1045       TopExp_Explorer anExp (aFace, TopAbs_VERTEX);
1046       for(;anExp.More();anExp.Next()) {
1047         const TopoDS_Shape& aVertex = anExp.Current();
1048         if (!aVertex.IsNull())
1049           aVec[i].Add(anExp.Current());
1050       }
1051     }
1052   }
1053   //trivial case: 2 faces
1054   TopTools_ListOfShape aList;
1055   TopTools_MapIteratorOfMapOfShape it2(aVec[0]);
1056   for(;it2.More();it2.Next()) {
1057     if(aVec[1].Contains(it2.Key())) {
1058       aShape = it2.Key();
1059       if(theList.Extent() == 2)
1060         break;
1061       else 
1062         aList.Append(it2.Key());
1063     }
1064   }
1065   if(aList.Extent() && aVec.size() > 3) {// list of common edges ==> search ny neighbors 
1066     if(aVec[2].Extent() && aVec[3].Extent()) {
1067       TopTools_ListIteratorOfListOfShape it(aList);
1068       for(;it.More();it.Next()) {
1069         const TopoDS_Shape& aCand = it.Value();
1070         // not yet completelly implemented, to be rechecked
1071         TopoDS_Vertex aV1, aV2;
1072         TopExp::Vertices(TopoDS::Edge(aCand), aV1, aV2);
1073         int aNum(0);
1074         if(aVec[2].Contains(aV1)) aNum++;
1075         else if(aVec[2].Contains(aV2)) aNum++;
1076         if(aVec[3].Contains(aV1)) aNum++;
1077         else if(aVec[3].Contains(aV2)) aNum++;
1078         if(aNum == 2) {
1079           aShape = aCand;
1080           break;
1081         }
1082       }
1083     }
1084   }
1085
1086   if(aList.Extent() && aVec.size() == 3) {
1087
1088     TopTools_ListIteratorOfListOfShape it(aList);
1089     for(;it.More();it.Next()) {
1090       const TopoDS_Shape& aCand = it.Value();
1091       if(aVec[2].Contains(aCand)) {
1092         aShape = aCand;
1093         break;
1094       }
1095     }
1096   }
1097   return aShape;
1098 }
1099
1100 std::string getContextName(const std::string& theSubShapeName)
1101 {
1102   std::string aName;
1103   std::string::size_type n = theSubShapeName.find('/');                 
1104   if (n == std::string::npos) return aName;
1105   aName = theSubShapeName.substr(0, n);
1106   return aName;
1107 }
1108 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
1109 void Model_AttributeSelection::selectSubShape(
1110   const std::string& theType, const std::string& theSubShapeName)
1111 {
1112   if(theSubShapeName.empty() || theType.empty()) return;
1113   TopAbs_ShapeEnum aType = translateType(theType);
1114   std::shared_ptr<Model_Document> aDoc = 
1115     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1116   std::string aContName = getContextName(theSubShapeName);
1117   if(aContName.empty()) return;
1118   //ResultPtr aCont = context();
1119   ResultPtr aCont = aDoc->findByName(aContName);
1120   if(!aCont.get() || aCont->shape()->isNull()) return;
1121   TopoDS_Shape aContext  = aCont->shape()->impl<TopoDS_Shape>();
1122   TopAbs_ShapeEnum aContType = aContext.ShapeType();
1123   if(aType <= aContType) return; // not applicable
1124
1125
1126   TopoDS_Shape aSelection;
1127   switch (aType) 
1128   {
1129   case TopAbs_COMPOUND:
1130     break;
1131   case TopAbs_COMPSOLID:
1132     break;
1133   case TopAbs_SOLID:
1134     break;
1135   case TopAbs_SHELL:
1136     break;
1137   case TopAbs_FACE:
1138     {
1139       const TopoDS_Shape aSelection = findFaceByName(theSubShapeName, aDoc);
1140       if(!aSelection.IsNull()) {// Select it
1141         std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1142         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1143         setValue(aCont, aShapeToBeSelected);
1144       }
1145     }
1146     break;
1147   case TopAbs_WIRE:
1148     break;
1149   case TopAbs_EDGE:
1150     {  
1151       TopoDS_Shape aSelection;// = findFaceByName(theSubShapeName, aDoc);
1152       const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1153       if(!aLabel.IsNull()) {
1154         Handle(TNaming_NamedShape) aNS;
1155         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1156           aSelection = getShapeFromNS(theSubShapeName, aNS);
1157         }
1158       }
1159       if(aSelection.IsNull()) {
1160         std::list<std::string> aListofNames;
1161         int n = ParseName(theSubShapeName, aListofNames);
1162         if(n > 1 && n < 5) {
1163           TopTools_ListOfShape aList;
1164           std::list<std::string>::iterator it =aListofNames.begin();
1165           for(;it != aListofNames.end();it++){
1166             const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1167             aList.Append(aFace);                
1168           }
1169           aSelection = findCommonShape(TopAbs_EDGE, aList);
1170         }
1171       }
1172       if(!aSelection.IsNull()) {// Select it
1173         std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1174         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1175         setValue(aCont, aShapeToBeSelected);
1176       }
1177     }
1178     break;
1179   case TopAbs_VERTEX:
1180     {
1181       TopoDS_Shape aSelection;
1182       const TDF_Label& aLabel = aDoc->findNamingName(theSubShapeName);
1183       if(!aLabel.IsNull()) {
1184         Handle(TNaming_NamedShape) aNS;
1185         if(aLabel.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
1186           aSelection = getShapeFromNS(theSubShapeName, aNS);
1187         }
1188       }
1189       if(aSelection.IsNull()) {
1190         std::list<std::string> aListofNames;
1191         int n = ParseName(theSubShapeName, aListofNames);
1192         if(n > 1 && n < 4) { // 2 || 3
1193           TopTools_ListOfShape aList;
1194           std::list<std::string>::iterator it = aListofNames.begin();
1195           for(; it != aListofNames.end(); it++){
1196             const TopoDS_Shape aFace = findFaceByName(*it, aDoc);
1197             if(!aFace.IsNull())
1198               aList.Append(aFace);              
1199           }
1200           aSelection = findCommonShape(TopAbs_VERTEX, aList);
1201         }
1202       }
1203       if(!aSelection.IsNull()) {// Select it
1204         std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected(new GeomAPI_Shape());
1205         aShapeToBeSelected->setImpl(new TopoDS_Shape(aSelection));
1206         setValue(aCont, aShapeToBeSelected);
1207       }
1208     }
1209     break;
1210   default: //TopAbs_SHAPE
1211     return;
1212   }
1213
1214 }
1215
1216 int Model_AttributeSelection::Id()
1217 {
1218   std::shared_ptr<GeomAPI_Shape> aSelection = value();
1219   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
1220   const TopoDS_Shape& aMainShape = aContext->impl<TopoDS_Shape>();
1221   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1222   int anID = 0;
1223   if (aSelection && !aSelection->isNull() &&
1224     aContext   && !aContext->isNull())
1225   {
1226     TopTools_IndexedMapOfShape aSubShapesMap;
1227     TopExp::MapShapes(aMainShape, aSubShapesMap);
1228     anID = aSubShapesMap.FindIndex(aSubShape);
1229   }
1230   return anID;
1231 }