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