Salome HOME
Issue #1860: fix end lines with spaces
[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 "Model_SelectionNaming.h"
13 #include <Model_Objects.h>
14 #include <ModelAPI_Feature.h>
15 #include <ModelAPI_ResultBody.h>
16 #include <ModelAPI_ResultConstruction.h>
17 #include <ModelAPI_ResultPart.h>
18 #include <ModelAPI_CompositeFeature.h>
19 #include <ModelAPI_Tools.h>
20 #include <GeomAPI_Shape.h>
21 #include <ModelAPI_Session.h>
22 #include <GeomAPI_PlanarEdges.h>
23 #include <Events_InfoMessage.h>
24
25 #include <TNaming_Selector.hxx>
26 #include <TNaming_NamedShape.hxx>
27 #include <TNaming_Tool.hxx>
28 #include <TNaming_Builder.hxx>
29 #include <TNaming_Localizer.hxx>
30 #include <TNaming_SameShapeIterator.hxx>
31 #include <TNaming_Iterator.hxx>
32 #include <TNaming_NewShapeIterator.hxx>
33 #include <TopoDS_Shape.hxx>
34 #include <TopoDS_Compound.hxx>
35 #include <TDataStd_IntPackedMap.hxx>
36 #include <TDataStd_Integer.hxx>
37 #include <TDataStd_UAttribute.hxx>
38 #include <TDataStd_Name.hxx>
39 #include <TopTools_MapOfShape.hxx>
40 #include <TopTools_IndexedMapOfShape.hxx>
41 #include <TopTools_MapIteratorOfMapOfShape.hxx>
42 #include <TopTools_ListOfShape.hxx>
43 #include <NCollection_DataMap.hxx>
44 #include <TopExp_Explorer.hxx>
45 #include <TDF_LabelMap.hxx>
46 #include <BRep_Tool.hxx>
47 #include <BRep_Builder.hxx>
48 #include <TopoDS_Edge.hxx>
49 #include <TopoDS.hxx>
50 #include <TopExp.hxx>
51 #include <TColStd_MapOfTransient.hxx>
52 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
53 #include <TopTools_ListIteratorOfListOfShape.hxx>
54 #include <TColStd_MapIteratorOfPackedMapOfInteger.hxx>
55 #include <gp_Pnt.hxx>
56 #include <Precision.hxx>
57 #include <TDF_ChildIterator.hxx>
58 #include <TDF_ChildIDIterator.hxx>
59 #include <TDataStd_Name.hxx>
60 #include <TopAbs_ShapeEnum.hxx>
61 #include <TopoDS_Iterator.hxx>
62 #include <BRep_Builder.hxx>
63
64 using namespace std;
65 //#define DEB_NAMING 1
66 #ifdef DEB_NAMING
67 #include <BRepTools.hxx>
68 #endif
69 /// added to the index in the packed map to signalize that the vertex of edge is selected
70 /// (multiplied by the index of the edge)
71 static const int kSTART_VERTEX_DELTA = 1000000;
72 // identifier that there is simple reference: selection equals to context
73 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
74 // simple reference in the construction
75 Standard_GUID kCONSTUCTION_SIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb28");
76 // reference to Part sub-object
77 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
78 // selection is invalid after recomputation
79 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
80
81 // on this label is stored:
82 // TNaming_NamedShape - selected shape
83 // TNaming_Naming - topological selection information (for the body)
84 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
85 // TDataStd_Integer - type of the selected shape (for construction)
86 // TDF_Reference - from ReferenceAttribute, the context
87 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
88   const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
89 {
90   if (theTemporarily) { // just keep the stored without DF update
91     myTmpContext = theContext;
92     myTmpSubShape = theSubShape;
93     owner()->data()->sendAttributeUpdated(this);
94     return;
95   } else {
96     myTmpContext.reset();
97     myTmpSubShape.reset();
98   }
99
100   const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
101   bool isOldContext = theContext == myRef.value();
102   bool isOldShape = isOldContext &&
103     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
104   if (isOldShape) return; // shape is the same, so context is also unchanged
105   // update the referenced object if needed
106   if (!isOldContext) {
107       myRef.setValue(theContext);
108   }
109
110   // do noth use naming if selected shape is result shape itself, but not sub-shape
111   TDF_Label aSelLab = selectionLabel();
112   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
113   aSelLab.ForgetAttribute(kCONSTUCTION_SIMPLE_REF_ID);
114   aSelLab.ForgetAttribute(kINVALID_SELECTION);
115
116   bool isDegeneratedEdge = false;
117   // do not use the degenerated edge as a shape, a null context and shape is used in the case
118   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
119     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
120     if (aSubShape.ShapeType() == TopAbs_EDGE)
121       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
122   }
123   if (!theContext.get() || isDegeneratedEdge) {
124     // to keep the reference attribute label
125     TDF_Label aRefLab = myRef.myRef->Label();
126     aSelLab.ForgetAllAttributes(true);
127     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
128     return;
129   }
130   if (theContext->groupName() == ModelAPI_ResultBody::group()) {
131     // do not select the whole shape for body:it is already must be in the data framework
132     // equal and null selected objects mean the same: object is equal to context,
133     if (theContext->shape().get() &&
134         (theContext->shape()->isEqual(theSubShape) || !theSubShape.get())) {
135       aSelLab.ForgetAllAttributes(true);
136       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
137     } else {
138       selectBody(theContext, theSubShape);
139     }
140   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
141     if (!theSubShape.get()) {
142       // to sub, so the whole result is selected
143       aSelLab.ForgetAllAttributes(true);
144       TDataStd_UAttribute::Set(aSelLab, kCONSTUCTION_SIMPLE_REF_ID);
145       ResultConstructionPtr aConstruction =
146         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
147       if (aConstruction->isInfinite()) {
148         // For correct naming selection, put the shape into the naming structure.
149         // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
150         TNaming_Builder aBuilder(aSelLab);
151         aBuilder.Generated(theContext->shape()->impl<TopoDS_Shape>());
152         std::shared_ptr<Model_Document> aMyDoc =
153           std::dynamic_pointer_cast<Model_Document>(owner()->document());
154         //std::string aName = contextName(theContext);
155         // for selection in different document, add the document name
156         //aMyDoc->addNamingName(aSelLab, aName);
157         //TDataStd_Name::Set(aSelLab, aName.c_str());
158       } else {  // for sketch the naming is needed in DS
159         BRep_Builder aCompoundBuilder;
160         TopoDS_Compound aComp;
161         aCompoundBuilder.MakeCompound(aComp);
162         for(int a = 0; a < aConstruction->facesNum(); a++) {
163           TopoDS_Shape aFace = aConstruction->face(a)->impl<TopoDS_Shape>();
164           aCompoundBuilder.Add(aComp, aFace);
165         }
166         std::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
167         aShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aComp));
168         selectConstruction(theContext, aShape);
169       }
170     } else {
171       selectConstruction(theContext, theSubShape);
172     }
173   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
174     aSelLab.ForgetAllAttributes(true);
175     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
176     selectPart(theContext, theSubShape);
177   }
178   //the attribute initialized state should be changed by sendAttributeUpdated only
179   //myIsInitialized = true;
180
181   owner()->data()->sendAttributeUpdated(this);
182 }
183
184 void Model_AttributeSelection::removeTemporaryValues()
185 {
186   if (myTmpContext.get() || myTmpSubShape.get()) {
187     myTmpContext.reset();
188     myTmpSubShape.reset();
189   }
190 }
191
192 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
193 {
194   GeomShapePtr aResult;
195   if (myTmpContext.get() || myTmpSubShape.get()) {
196     ResultConstructionPtr aResulConstruction =
197       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myTmpContext);
198     if(aResulConstruction.get()) {
199       // it is just reference to construction.
200       return myTmpSubShape;
201     }
202     return myTmpSubShape.get() ? myTmpSubShape : myTmpContext->shape();
203   }
204
205   TDF_Label aSelLab = selectionLabel();
206   if (aSelLab.IsAttribute(kINVALID_SELECTION))
207     return aResult;
208
209   if (myRef.isInitialized()) {
210     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
211       ResultPtr aContext = context();
212       if (!aContext.get())
213         return aResult; // empty result
214       return aContext->shape();
215     }
216     if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) {
217       // it is just reference to construction, nothing is in value
218         return aResult; // empty result
219     }
220     if (aSelLab.IsAttribute(kPART_REF_ID)) {
221       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
222       if (!aPart.get() || !aPart->isActivated())
223         return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
224       Handle(TDataStd_Integer) anIndex;
225       if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
226         if (anIndex->Get()) { // special selection attribute was created, use it
227           return aPart->selectionValue(anIndex->Get());
228         } else { // face with name is already in the data model, so try to take it by name
229           Handle(TDataStd_Name) aName;
230           if (selectionLabel().FindAttribute(TDataStd_Name::GetID(), aName)) {
231             std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
232             std::size_t aPartEnd = aSubShapeName.find('/');
233             if (aPartEnd != string::npos && aPartEnd != aSubShapeName.rfind('/')) {
234               string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
235               int anIndex;
236               std::string aType; // to reuse already existing selection the type is not needed
237               return aPart->shapeInPart(aNameInPart, aType, anIndex);
238             }
239           }
240         }
241       }
242     }
243
244     Handle(TNaming_NamedShape) aSelection;
245     if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
246       TopoDS_Shape aSelShape = aSelection->Get();
247       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
248       aResult->setImpl(new TopoDS_Shape(aSelShape));
249     } else { // for simple construction element: just shape of this construction element
250       ResultConstructionPtr aConstr =
251         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
252       if (aConstr) {
253         return aConstr->shape();
254       }
255     }
256   }
257   return aResult;
258 }
259
260 bool Model_AttributeSelection::isInvalid()
261 {
262   return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
263 }
264
265 bool Model_AttributeSelection::isInitialized()
266 {
267   if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
268     std::shared_ptr<GeomAPI_Shape> aResult;
269     if (myRef.isInitialized()) {
270       TDF_Label aSelLab = selectionLabel();
271       if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
272         ResultPtr aContext = context();
273         return aContext.get() != NULL;
274       }
275       if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) {
276         // it is just reference to construction, nothing is in value
277           return true;
278       }
279
280       Handle(TNaming_NamedShape) aSelection;
281       if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
282         return !aSelection->Get().IsNull();
283       } else { // for simple construction element: just shape of this construction element
284         ResultConstructionPtr aConstr =
285           std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(context());
286         if (aConstr.get()) {
287           return aConstr->shape().get() != NULL;
288         }
289       }
290     }
291   }
292   return false;
293 }
294
295 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
296   : myRef(theLabel)
297 {
298   myIsInitialized = myRef.isInitialized();
299 }
300
301 void Model_AttributeSelection::setID(const std::string theID)
302 {
303   myRef.setID(theID);
304   ModelAPI_AttributeSelection::setID(theID);
305 }
306
307 ResultPtr Model_AttributeSelection::context() {
308   if (myTmpContext.get() || myTmpSubShape.get()) {
309     return myTmpContext;
310   }
311
312   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
313   // for parts there could be same-data result, so take the last enabled
314   if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
315     int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
316     for(int a = aSize - 1; a >= 0; a--) {
317       ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
318       if (aPart.get() && aPart->data() == aResult->data()) {
319         ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
320         FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
321         // check that this result is not this-feature result (it is forbidden t oselect itself)
322         if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
323           return aPartResult;
324         }
325       }
326     }
327   }
328   return aResult;
329 }
330
331
332 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
333 {
334   ModelAPI_AttributeSelection::setObject(theObject);
335   myRef.setObject(theObject);
336 }
337
338 TDF_LabelMap& Model_AttributeSelection::scope()
339 {
340   if (myScope.IsEmpty()) { // create a new scope if not yet done
341     // gets all features with named shapes that are before this feature label (before in history)
342     DocumentPtr aMyDoc = owner()->document();
343     std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
344     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
345     bool aMePassed = false;
346     CompositeFeaturePtr aComposite =
347       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
348     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
349     CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
350     if (aFeature.get()) {
351       aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
352       if (aCompositeOwner.get()) {
353          aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
354       }
355     }
356     // for group Scope is not limitet: this is always up to date objects
357     bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
358     for(; aFIter != allFeatures.end(); aFIter++) {
359       if (*aFIter == owner()) {  // the left features are created later (except subs of composite)
360         aMePassed = true;
361         continue;
362       }
363       if (isGroup) aMePassed = false;
364       bool isInScope = !aMePassed;
365       if (!isInScope && aComposite.get()) {
366         // try to add sub-elements of composite if this is composite
367         if (aComposite->isSub(*aFIter))
368           isInScope = true;
369       }
370       // remove the composite-owner of this feature (sketch in extrusion-cut)
371       if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
372         isInScope = false;
373
374       if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
375         TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
376           (*aFIter)->data())->label().Father();
377         TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), 1);
378         for(; aNSIter.More(); aNSIter.Next()) {
379           Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
380           if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
381             myScope.Add(aNS->Label());
382           }
383         }
384       }
385     }
386   }
387   return myScope;
388 }
389
390 /// Sets the invalid flag if flag is false, or removes it if "true"
391 /// Returns theFlag
392 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
393   if (theFlag) {
394     theLab.ForgetAttribute(kINVALID_SELECTION);
395   } else {
396     TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
397   }
398   return theFlag;
399 }
400
401 bool Model_AttributeSelection::update()
402 {
403   TDF_Label aSelLab = selectionLabel();
404   ResultPtr aContext = context();
405   if (!aContext.get())
406     return setInvalidIfFalse(aSelLab, false);
407   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
408     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
409   }
410   if (aSelLab.IsAttribute(kCONSTUCTION_SIMPLE_REF_ID)) {
411     // it is just reference to construction, not sub-shape
412     // if there is a sketch, the sketch-naming must be updated
413     ResultConstructionPtr aConstruction =
414       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
415     if (!aConstruction->isInfinite()) {
416       BRep_Builder aCompoundBuilder;
417       TopoDS_Compound aComp;
418       aCompoundBuilder.MakeCompound(aComp);
419       for(int a = 0; a < aConstruction->facesNum(); a++) {
420         TopoDS_Shape aFace = aConstruction->face(a)->impl<TopoDS_Shape>();
421         aCompoundBuilder.Add(aComp, aFace);
422       }
423       std::shared_ptr<GeomAPI_Shape> aShape(new GeomAPI_Shape);
424       aShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aComp));
425       selectConstruction(aContext, aShape);
426     } else {
427       // For correct naming selection, put the shape into the naming structure.
428       // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
429       TNaming_Builder aBuilder(aSelLab);
430       aBuilder.Generated(aContext->shape()->impl<TopoDS_Shape>());
431       std::shared_ptr<Model_Document> aMyDoc =
432         std::dynamic_pointer_cast<Model_Document>(owner()->document());
433       //std::string aName = contextName(aContext);
434       //aMyDoc->addNamingName(aSelLab, aName);
435       //TDataStd_Name::Set(aSelLab, aName.c_str());
436     }
437     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
438   }
439
440   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
441     std::shared_ptr<GeomAPI_Shape> aNoSelection;
442     bool aResult = selectPart(aContext, aNoSelection, true);
443     aResult = setInvalidIfFalse(aSelLab, aResult);
444     if (aResult) {
445       owner()->data()->sendAttributeUpdated(this);
446     }
447     return aResult;
448   }
449
450   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
451     // body: just a named shape, use selection mechanism from OCCT
452     TNaming_Selector aSelector(aSelLab);
453     TopoDS_Shape anOldShape;
454     if (!aSelector.NamedShape().IsNull()) {
455       anOldShape = aSelector.NamedShape()->Get();
456     }
457     bool aResult = aSelector.Solve(scope()) == Standard_True;
458     // must be before sending of updated attribute (1556)
459     aResult = setInvalidIfFalse(aSelLab, aResult);
460     TopoDS_Shape aNewShape;
461     if (!aSelector.NamedShape().IsNull()) {
462       aNewShape = aSelector.NamedShape()->Get();
463     }
464     if (anOldShape.IsNull() || aNewShape.IsNull() ||
465         !anOldShape.IsEqual(aSelector.NamedShape()->Get())) // send updated if shape is changed
466       owner()->data()->sendAttributeUpdated(this);
467     return aResult;
468   } else if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
469     // construction: identification by the results indexes, recompute faces and
470     // take the face that more close by the indexes
471     ResultConstructionPtr aConstructionContext =
472       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aContext);
473     FeaturePtr aContextFeature = aContext->document()->feature(aContext);
474     // sketch sub-element
475     if (aConstructionContext &&
476         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature).get())
477     {
478       TDF_Label aLab = myRef.myRef->Label();
479       // getting a type of selected shape
480       Handle(TDataStd_Integer) aTypeAttr;
481       if (!aLab.FindAttribute(TDataStd_Integer::GetID(), aTypeAttr)) {
482         return setInvalidIfFalse(aSelLab, false);
483       }
484       TopAbs_ShapeEnum aShapeType = (TopAbs_ShapeEnum)(aTypeAttr->Get());
485       // selected indexes will be needed in each "if"
486       Handle(TDataStd_IntPackedMap) aSubIds;
487       std::shared_ptr<GeomAPI_Shape> aNewSelected;
488       bool aNoIndexes =
489         !aLab.FindAttribute(TDataStd_IntPackedMap::GetID(), aSubIds) || aSubIds->Extent() == 0;
490       // for now working only with composite features
491       CompositeFeaturePtr aComposite =
492         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
493       if (!aComposite.get() || aComposite->numberOfSubs() == 0) {
494         return setInvalidIfFalse(aSelLab, false);
495       }
496
497       if (aShapeType == TopAbs_FACE || aShapeType == TopAbs_WIRE) {
498         // compound is for the whole sketch selection
499         // If this is a wire with plane defined then it is a sketch-like object
500         if (!aConstructionContext->facesNum()) // no faces, update can not work correctly
501           return setInvalidIfFalse(aSelLab, false);
502         // if there is no edges indexes, any face can be used: take the first
503         std::shared_ptr<GeomAPI_Shape> aNewSelected;
504         if (aNoIndexes) {
505           aNewSelected = aConstructionContext->face(0);
506         } else { // searching for most looks-like initial face by the indexes
507           // prepare edges of the current result for the fast searching
508           // curves and orientations of edges
509           NCollection_DataMap<Handle(Geom_Curve), int> allCurves;
510           const int aSubNum = aComposite->numberOfSubs();
511           for(int a = 0; a < aSubNum; a++) {
512             int aSubID = aComposite->subFeatureId(a);
513             if (aSubIds->Contains(aSubID)) {
514               FeaturePtr aSub = aComposite->subFeature(a);
515               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
516               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes;
517               for(aRes = aResults.cbegin(); aRes != aResults.cend(); aRes++) {
518                 ResultConstructionPtr aConstr =
519                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
520                 if (aConstr->shape() && aConstr->shape()->isEdge()) {
521                   const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
522                   TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
523                   if (!anEdge.IsNull()) {
524                     Standard_Real aFirst, aLast;
525                     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
526                     // searching for orientation information
527                     int anOrient = 0;
528                     Handle(TDataStd_Integer) anInt;
529                     if (aSelLab.FindChild(aSubID).FindAttribute(TDataStd_Integer::GetID(), anInt)){
530                       anOrient = anInt->Get();
531                     }
532                     allCurves.Bind(aCurve, anOrient);
533                   }
534                 }
535               }
536             }
537           }
538           aNewSelected = Model_SelectionNaming::findAppropriateFace(
539             aContext, allCurves, aShapeType == TopAbs_WIRE);
540         }
541         if (aNewSelected) { // store this new selection
542           selectConstruction(aContext, aNewSelected);
543           setInvalidIfFalse(aSelLab, true);
544           owner()->data()->sendAttributeUpdated(this);
545           return true;
546         } else {
547           // if the selection is not found, put the empty shape:
548           // it's better to have disappeared shape, than the old, the lost one
549           TNaming_Builder anEmptyBuilder(selectionLabel());
550           return setInvalidIfFalse(aSelLab, false);
551         }
552       } else if (aShapeType == TopAbs_EDGE) {
553         // just reselect the edge by the id
554         const int aSubNum = aComposite->numberOfSubs();
555         for(int a = 0; a < aSubNum; a++) {
556           // if aSubIds take any, the first appropriate
557           if (aSubIds->IsEmpty() || aSubIds->Contains(aComposite->subFeatureId(a))) {
558             // found the appropriate feature
559             FeaturePtr aFeature = aComposite->subFeature(a);
560             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
561               aFeature->results().cbegin();
562             for(;aResIter != aFeature->results().cend(); aResIter++) {
563               ResultConstructionPtr aRes =
564                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
565               if (aRes && aRes->shape() && aRes->shape()->isEdge()) { // found!
566                 selectConstruction(aContext, aRes->shape());
567                 setInvalidIfFalse(aSelLab, true);
568                 owner()->data()->sendAttributeUpdated(this);
569                 return true;
570               }
571             }
572           }
573         }
574       } else if (aShapeType == TopAbs_VERTEX) {
575         // just reselect the vertex by the id of edge
576         const int aSubNum = aComposite->numberOfSubs();
577         for(int a = 0; a < aSubNum; a++) {
578           // if aSubIds take any, the first appropriate
579           int aFeatureID = aComposite->subFeatureId(a);
580           if (aSubIds->IsEmpty() || aSubIds->Contains(aFeatureID) ||
581             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA) ||
582             aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) {
583               // searching for deltas
584               int aVertexNum = 0;
585               if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA)) aVertexNum = 1;
586               else if (aSubIds->Contains(aFeatureID + kSTART_VERTEX_DELTA * 2)) aVertexNum = 2;
587               // found the feature with appropriate edge
588               FeaturePtr aFeature = aComposite->subFeature(a);
589               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter =
590                 aFeature->results().cbegin();
591               for(;aResIter != aFeature->results().cend(); aResIter++) {
592                 ResultConstructionPtr aRes =
593                   std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aResIter);
594                 if (aRes && aRes->shape()) {
595                   if (aRes->shape()->isVertex() && aVertexNum == 0) { // found!
596                     selectConstruction(aContext, aRes->shape());
597                     setInvalidIfFalse(aSelLab, true);
598                     owner()->data()->sendAttributeUpdated(this);
599                     return true;
600                   } else if (aRes->shape()->isEdge() && aVertexNum > 0) {
601                     const TopoDS_Shape& anEdge = aRes->shape()->impl<TopoDS_Shape>();
602                     int aVIndex = 1;
603                     for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
604                       if (aVIndex == aVertexNum) { // found!
605                         std::shared_ptr<GeomAPI_Shape> aVertex(new GeomAPI_Shape);
606                         aVertex->setImpl(new TopoDS_Shape(aVExp.Current()));
607                         selectConstruction(aContext, aVertex);
608                         setInvalidIfFalse(aSelLab, true);
609                         owner()->data()->sendAttributeUpdated(this);
610                         return true;
611                       }
612                       aVIndex++;
613                     }
614                   }
615                 }
616               }
617           }
618         }
619       }
620     } else { // simple construction element: the selected is that needed
621       selectConstruction(aContext, aContext->shape());
622       setInvalidIfFalse(aSelLab, true);
623       owner()->data()->sendAttributeUpdated(this);
624       return true;
625     }
626   }
627   return setInvalidIfFalse(aSelLab, false); // unknown case
628 }
629
630 void Model_AttributeSelection::selectBody(
631   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
632 {
633   // perform the selection
634   TNaming_Selector aSel(selectionLabel());
635   TopoDS_Shape aContext;
636
637   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(myRef.value());
638   if (aBody) {
639     aContext = aBody->shape()->impl<TopoDS_Shape>();
640   } else {
641     ResultPtr aResult =
642       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
643     if (aResult) {
644       aContext = aResult->shape()->impl<TopoDS_Shape>();
645     } else {
646       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
647       return;
648     }
649   }
650
651   // with "recover" feature the selected context may be not up to date (issue 1710)
652   Handle(TNaming_NamedShape) aResult;
653   TDF_Label aSelLab = selectionLabel();
654   TopoDS_Shape aNewContext = aContext;
655   bool isUpdated = true;
656   while(!aNewContext.IsNull() && isUpdated) {
657     // searching for the very last shape that was produced from this one
658     isUpdated = false;
659     if (!TNaming_Tool::HasLabel(aSelLab, aNewContext))
660       // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
661       break;
662     for(TNaming_SameShapeIterator anIter(aNewContext, aSelLab); anIter.More(); anIter.Next()) {
663       TDF_Label aNSLab = anIter.Label();
664       if (!scope().Contains(aNSLab))
665         continue;
666       Handle(TNaming_NamedShape) aNS;
667       if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
668         for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
669           if (aShapesIter.Evolution() == TNaming_SELECTED)
670             continue; // don't use the selection evolution
671           if (!aShapesIter.OldShape().IsNull() && aShapesIter.OldShape().IsSame(aNewContext)) {
672              // found the original shape
673             aNewContext = aShapesIter.NewShape(); // go to the newer shape
674             isUpdated = true;
675             break;
676           }
677         }
678       }
679     }
680   }
681   if (aNewContext.IsNull()) { // a context is already deleted
682     setInvalidIfFalse(aSelLab, false);
683     Events_InfoMessage("Model_AttributeSelection", "Failed to select shape already deleted").send();
684     return;
685   }
686
687   TopoDS_Shape aNewSub = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
688   if (!aNewSub.IsEqual(aContext)) { // searching for subshape in the new context
689     bool isFound = false;
690     TopExp_Explorer anExp(aNewContext, aNewSub.ShapeType());
691     for(; anExp.More(); anExp.Next()) {
692       if (anExp.Current().IsEqual(aNewSub)) {
693         isFound = true;
694         break;
695       }
696     }
697     if (!isFound) { // sub-shape is not found in the up-to-date instance of the context shape
698       setInvalidIfFalse(aSelLab, false);
699       Events_InfoMessage("Model_AttributeSelection",
700         "Failed to select sub-shape already modified").send();
701       return;
702     }
703   }
704
705
706   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
707   FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
708   if (aFeatureOwner.get())
709     aFeatureOwner->eraseResults();
710   if (!aContext.IsNull()) {
711     aSel.Select(aNewSub, aNewContext);
712   }
713 }
714
715 /// registers the name of the shape in the label (theID == 0) of sub label (theID is a tag)
716 /// if theID is zero,
717 /// theOrientation is additional information about the positioning of edge relatively to face
718 ///    it is stored in the integer attribute of the edge sub-label:
719 ///    -1 is out, 1 is in, 0 is not needed
720 static void registerSubShape(TDF_Label theMainLabel, TopoDS_Shape theShape,
721   const int theID, const FeaturePtr& theContextFeature, std::shared_ptr<Model_Document> theDoc,
722   std::map<int, int>& theOrientations,
723   // name of sub-elements by ID to be exported instead of indexes
724   std::map<int, std::string>& theSubNames,
725   Handle(TDataStd_IntPackedMap) theRefs = Handle(TDataStd_IntPackedMap)(),
726   const int theOrientation = 0)
727 {
728   TDF_Label aLab = theID == 0 ? theMainLabel : theMainLabel.FindChild(theID);
729   if (theOrientation != 0) { // store the orientation of edge relatively to face if needed
730     TDataStd_Integer::Set(aLab, theOrientation);
731   }
732   TNaming_Builder aBuilder(aLab);
733   aBuilder.Generated(theShape);
734   std::stringstream aName;
735   // #1839 : do not store name of the feature in the tree, since this name could be changed
736   //aName<<theContextFeature->name();
737   if (theShape.ShapeType() != TopAbs_COMPOUND) { // compound means the whole result for construction
738     //aName<<"/";
739     if (theShape.ShapeType() == TopAbs_FACE) aName<<"Face";
740     else if (theShape.ShapeType() == TopAbs_WIRE) aName<<"Wire";
741     else if (theShape.ShapeType() == TopAbs_EDGE) aName<<"Edge";
742     else if (theShape.ShapeType() == TopAbs_VERTEX) aName<<"Vertex";
743
744     if (theRefs.IsNull()) {
745       aName<<theID;
746       if (theOrientation == 1)
747         aName<<"f";
748       else if (theOrientation == -1)
749         aName<<"r";
750     } else { // make a composite name from all sub-elements indexes: "1_2_3_4"
751       TColStd_MapIteratorOfPackedMapOfInteger aRef(theRefs->GetMap());
752       for(; aRef.More(); aRef.Next()) {
753         aName<<"-"<<theSubNames[aRef.Key()];
754         if (theOrientations.find(aRef.Key()) != theOrientations.end()) {
755           if (theOrientations[aRef.Key()] == 1)
756             aName<<"f";
757           else if (theOrientations[aRef.Key()] == -1)
758             aName<<"r";
759         }
760       }
761     }
762   }
763
764   theDoc->addNamingName(aLab, aName.str());
765   TDataStd_Name::Set(aLab, aName.str().c_str());
766 }
767
768 void Model_AttributeSelection::selectConstruction(
769   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
770 {
771   std::shared_ptr<Model_Document> aMyDoc =
772     std::dynamic_pointer_cast<Model_Document>(owner()->document());
773   FeaturePtr aContextFeature = theContext->document()->feature(theContext);
774   CompositeFeaturePtr aComposite =
775     std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aContextFeature);
776   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
777   if (!aComposite || aComposite->numberOfSubs() == 0) {
778     // saving of context is enough: result construction contains exactly the needed shape
779     TNaming_Builder aBuilder(selectionLabel());
780     aBuilder.Generated(aSubShape);
781     //std::string aName = contextName(theContext);
782     //aMyDoc->addNamingName(selectionLabel(), aName);
783     //TDataStd_Name::Set(selectionLabel(), aName.c_str());
784     return;
785   }
786   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(owner()->data());
787   TDF_Label aLab = myRef.myRef->Label();
788   // identify the results of sub-object of the composite by edges
789   // save type of the selected shape in integer attribute
790   TopAbs_ShapeEnum aShapeType = aSubShape.ShapeType();
791   TDataStd_Integer::Set(aLab, (int)aShapeType);
792   gp_Pnt aVertexPos;
793   TColStd_MapOfTransient allCurves;
794   if (aShapeType == TopAbs_VERTEX) { // compare positions
795     aVertexPos = BRep_Tool::Pnt(TopoDS::Vertex(aSubShape));
796   } else {
797     for(TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE); anEdgeExp.More(); anEdgeExp.Next()) {
798       TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
799       Standard_Real aFirst, aLast;
800       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
801       allCurves.Add(aCurve);
802     }
803   }
804   // iterate and store the result ids of sub-elements and sub-elements to sub-labels
805   Handle(TDataStd_IntPackedMap) aRefs = TDataStd_IntPackedMap::Set(aLab);
806   std::map<int, int> anOrientations; //map from edges IDs to orientations of these edges in face
807   std::map<int, std::string> aSubNames; //map from edges IDs to names of edges
808   aRefs->Clear();
809   const int aSubNum = aComposite->numberOfSubs();
810   for(int a = 0; a < aSubNum; a++) {
811     FeaturePtr aSub = aComposite->subFeature(a);
812     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
813     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
814     // there may be many shapes (circle and center): register if at least one is in selection
815     for(; aRes != aResults.cend(); aRes++) {
816       ResultConstructionPtr aConstr =
817         std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
818       if (!aConstr->shape()) {
819         continue;
820       }
821       if (aShapeType == TopAbs_VERTEX) {
822         if (aConstr->shape()->isVertex()) { // compare vertices positions
823           const TopoDS_Shape& aVertex = aConstr->shape()->impl<TopoDS_Shape>();
824           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVertex));
825           if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
826             aRefs->Add(aComposite->subFeatureId(a));
827             aSubNames[aComposite->subFeatureId(a)] = Model_SelectionNaming::shortName(aConstr);
828           }
829         } else { // get first or last vertex of the edge: last is stored with additional delta
830           const TopoDS_Shape& anEdge = aConstr->shape()->impl<TopoDS_Shape>();
831           int aDelta = kSTART_VERTEX_DELTA;
832           for(TopExp_Explorer aVExp(anEdge, TopAbs_VERTEX); aVExp.More(); aVExp.Next()) {
833             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVExp.Current()));
834             if (aPnt.IsEqual(aVertexPos, Precision::Confusion())) {
835               aRefs->Add(aDelta + aComposite->subFeatureId(a));
836               aSubNames[aDelta + aComposite->subFeatureId(a)] =
837                 Model_SelectionNaming::shortName(aConstr, aDelta / kSTART_VERTEX_DELTA);
838               break;
839             }
840             aDelta += kSTART_VERTEX_DELTA;
841           }
842         }
843       } else {
844         if (aConstr->shape()->isEdge()) {
845           const TopoDS_Shape& aResShape = aConstr->shape()->impl<TopoDS_Shape>();
846           TopoDS_Edge anEdge = TopoDS::Edge(aResShape);
847           if (!anEdge.IsNull()) {
848             Standard_Real aFirst, aLast;
849             Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
850             if (allCurves.Contains(aCurve)) {
851               int anID = aComposite->subFeatureId(a);
852               aRefs->Add(anID);
853               aSubNames[anID] = Model_SelectionNaming::shortName(aConstr);
854               if (aShapeType != TopAbs_EDGE) { // face needs the sub-edges on sub-labels
855                 // add edges to sub-label to support naming for edges selection
856                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_EDGE);
857                 for(; anEdgeExp.More(); anEdgeExp.Next()) {
858                   TopoDS_Edge anEdge = TopoDS::Edge(anEdgeExp.Current());
859                   Standard_Real aFirst, aLast;
860                   Handle(Geom_Curve) aFaceCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
861                   if (aFaceCurve == aCurve) {
862                     int anOrient = Model_SelectionNaming::edgeOrientation(aSubShape, anEdge);
863                     anOrientations[anID] = anOrient;
864                     registerSubShape(
865                       selectionLabel(), anEdge, anID, aContextFeature, aMyDoc, anOrientations,
866                       aSubNames, Handle(TDataStd_IntPackedMap)(), anOrient);
867                   }
868                 }
869               } else { // put vertices of the selected edge to sub-labels
870                 // add edges to sub-label to support naming for edges selection
871                 TopExp_Explorer anEdgeExp(aSubShape, TopAbs_VERTEX);
872                 int aTagIndex = anID + kSTART_VERTEX_DELTA;
873                 for(; anEdgeExp.More(); anEdgeExp.Next(), aTagIndex += kSTART_VERTEX_DELTA) {
874                   TopoDS_Vertex aV = TopoDS::Vertex(anEdgeExp.Current());
875
876                   std::stringstream anAdditionalName;
877                   registerSubShape(
878                     selectionLabel(), aV, aTagIndex, aContextFeature, aMyDoc, anOrientations,
879                     aSubNames);
880                 }
881               }
882             }
883           }
884         }
885       }
886     }
887   }
888   // store the selected as primitive
889   TNaming_Builder aBuilder(selectionLabel());
890   aBuilder.Generated(aSubShape);
891     registerSubShape(
892       selectionLabel(), aSubShape, 0, aContextFeature, aMyDoc, anOrientations, aSubNames, aRefs);
893 }
894
895 bool Model_AttributeSelection::selectPart(
896   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
897   const bool theUpdate)
898 {
899   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
900   if (!aPart.get() || !aPart->isActivated())
901     return true; // postponed naming
902   if (theUpdate) {
903     Handle(TDataStd_Integer) anIndex;
904     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
905       // by internal selection
906       if (anIndex->Get() > 0) {
907         // update the selection by index
908         return aPart->updateInPart(anIndex->Get());
909       } else {
910         return true; // nothing to do, referencing just by name
911       }
912     }
913     return true; // nothing to do, referencing just by name
914   }
915   // store the shape (in case part is not loaded it should be useful
916   TopoDS_Shape aShape;
917   std::string aName = theContext->data()->name();
918   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
919     aShape = theContext->shape()->impl<TopoDS_Shape>();
920   } else {
921     aShape = theSubShape->impl<TopoDS_Shape>();
922     int anIndex;
923     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
924     TDataStd_Integer::Set(selectionLabel(), anIndex);
925   }
926   TNaming_Builder aBuilder(selectionLabel());
927   aBuilder.Select(aShape, aShape);
928   // identify by name in the part
929   TDataStd_Name::Set(selectionLabel(), aName.c_str());
930   return !aName.empty();
931 }
932
933 TDF_Label Model_AttributeSelection::selectionLabel()
934 {
935   return myRef.myRef->Label().FindChild(1);
936 }
937
938 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
939 {
940   std::string aName("");
941   if(!this->isInitialized())
942     return !theDefaultName.empty() ? theDefaultName : aName;
943
944   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
945   ResultPtr aCont = context();
946
947   Model_SelectionNaming aSelNaming(selectionLabel());
948   return aSelNaming.namingName(
949     aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
950 }
951
952 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
953 void Model_AttributeSelection::selectSubShape(
954   const std::string& theType, const std::string& theSubShapeName)
955 {
956   if(theSubShapeName.empty() || theType.empty()) return;
957
958   // check this is Part-name: 2 delimiters in the name
959   std::size_t aPartEnd = theSubShapeName.find('/');
960   if (aPartEnd != string::npos && aPartEnd != theSubShapeName.rfind('/')) {
961     std::string aPartName = theSubShapeName.substr(0, aPartEnd);
962     ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
963     if (aFound.get()) { // found such part, so asking it for the name
964       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
965       string aNameInPart = theSubShapeName.substr(aPartEnd + 1);
966       int anIndex;
967       std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, theType, anIndex);
968       if (aSelected.get()) {
969         setValue(aPart, aSelected);
970         TDataStd_Integer::Set(selectionLabel(), anIndex);
971         return;
972       }
973     }
974   }
975
976   Model_SelectionNaming aSelNaming(selectionLabel());
977   std::shared_ptr<Model_Document> aDoc =
978     std::dynamic_pointer_cast<Model_Document>(owner()->document());
979   std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
980   ResultPtr aCont;
981   if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
982     // try to find the last context to find the up to date shape
983     if (aCont->shape().get() && !aCont->shape()->isNull() &&
984       aCont->groupName() == ModelAPI_ResultBody::group() && aDoc == owner()->document()) {
985       const TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
986       if (!aConShape.IsNull()) {
987         Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
988         if (!aNS.IsNull()) {
989           aNS = TNaming_Tool::CurrentNamedShape(aNS);
990           if (!aNS.IsNull()) {
991             TDF_Label aLab = aNS->Label();
992             while(aLab.Depth() != 7 && aLab.Depth() > 5)
993               aLab = aLab.Father();
994             ObjectPtr anObj = aDoc->objects()->object(aLab);
995             if (anObj.get()) {
996               ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
997               if (aRes)
998                 aCont = aRes;
999             }
1000           }
1001         }
1002       }
1003     }
1004     setValue(aCont, aShapeToBeSelected);
1005   }
1006 }
1007
1008 int Model_AttributeSelection::Id()
1009 {
1010   int anID = 0;
1011   std::shared_ptr<GeomAPI_Shape> aSelection = value();
1012   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
1013   // support for compsolids:
1014   if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
1015     aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
1016
1017
1018   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1019   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1020   // searching for the latest main shape
1021   if (aSelection && !aSelection->isNull() &&
1022     aContext   && !aContext->isNull())
1023   {
1024     std::shared_ptr<Model_Document> aDoc =
1025       std::dynamic_pointer_cast<Model_Document>(context()->document());
1026     if (aDoc.get()) {
1027       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1028       if (!aNS.IsNull()) {
1029         aMainShape = TNaming_Tool::CurrentShape(aNS);
1030       }
1031     }
1032
1033     TopTools_IndexedMapOfShape aSubShapesMap;
1034     TopExp::MapShapes(aMainShape, aSubShapesMap);
1035     anID = aSubShapesMap.FindIndex(aSubShape);
1036   }
1037   return anID;
1038 }
1039
1040 void Model_AttributeSelection::setId(int theID)
1041 {
1042   const ResultPtr& aContext = context();
1043   std::shared_ptr<GeomAPI_Shape> aSelection;
1044
1045   std::shared_ptr<GeomAPI_Shape> aContextShape = aContext->shape();
1046   // support for compsolids:
1047   if (aContext.get() && ModelAPI_Tools::compSolidOwner(aContext).get())
1048     aContextShape = ModelAPI_Tools::compSolidOwner(aContext)->shape();
1049
1050   TopoDS_Shape aMainShape = aContextShape->impl<TopoDS_Shape>();
1051   // searching for the latest main shape
1052   if (theID > 0 &&
1053       aContextShape && !aContextShape->isNull())
1054   {
1055     std::shared_ptr<Model_Document> aDoc =
1056       std::dynamic_pointer_cast<Model_Document>(aContext->document());
1057     if (aDoc.get()) {
1058       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1059       if (!aNS.IsNull()) {
1060         aMainShape = TNaming_Tool::CurrentShape(aNS);
1061       }
1062     }
1063
1064     TopTools_IndexedMapOfShape aSubShapesMap;
1065     TopExp::MapShapes(aMainShape, aSubShapesMap);
1066     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1067
1068     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1069     aResult->setImpl(new TopoDS_Shape(aSelShape));
1070
1071     aSelection = aResult;
1072   }
1073
1074   setValue(aContext, aSelection);
1075 }
1076
1077 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1078 {
1079   std::string aResult;
1080   if (owner()->document() != theContext->document()) {
1081     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1082       aResult = theContext->document()->kind() + "/";
1083     } else {
1084       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1085         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1086       if (aDocRes.get()) {
1087         aResult = aDocRes->data()->name() + "/";
1088       }
1089     }
1090   }
1091   aResult += theContext->data()->name();
1092   return aResult;
1093 }
1094
1095 void Model_AttributeSelection::updateInHistory()
1096 {
1097   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1098   // only bodies may be modified later in the history, don't do anything otherwise
1099   if (!aContext.get() || aContext->groupName() != ModelAPI_ResultBody::group())
1100     return;
1101   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1102   if (!aContData.get() || !aContData->isValid())
1103     return;
1104   TDF_Label aContLab = aContData->label(); // named shape where the selected context is located
1105   Handle(TNaming_NamedShape) aContNS;
1106   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS))
1107     return;
1108   std::shared_ptr<Model_Document> aDoc =
1109     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1110   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1111   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1112   // iterate the context shape modifications in order to find a feature that is upper in history
1113   // that this one and is really modifies the referenced result to refer to it
1114   ResultPtr aModifierResFound;
1115   TNaming_Iterator aPairIter(aContNS);
1116   TopoDS_Shape aNewShape = aPairIter.NewShape();
1117   bool anIterate = true;
1118   // trying to update also the sub-shape selected
1119   GeomShapePtr aSubShape = value();
1120   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1121     aSubShape.reset();
1122
1123   while(anIterate) {
1124     anIterate = false;
1125     TNaming_SameShapeIterator aModifIter(aNewShape, aContLab);
1126     for(; aModifIter.More(); aModifIter.Next()) {
1127       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1128         (aDoc->objects()->object(aModifIter.Label().Father()));
1129       if (!aModifierObj.get())
1130         break;
1131       FeaturePtr aModifierFeat = aDoc->feature(aModifierObj);
1132       if (!aModifierFeat.get())
1133         break;
1134       if (aModifierFeat == aThisFeature || aDoc->objects()->isLater(aModifierFeat, aThisFeature))
1135         continue; // the modifier feature is later than this, so, should not be used
1136       if (aCurrentModifierFeat == aModifierFeat ||
1137         aDoc->objects()->isLater(aCurrentModifierFeat, aModifierFeat))
1138         continue; // the current modifier is later than the found, so, useless
1139       Handle(TNaming_NamedShape) aNewNS;
1140       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1141       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1142         aModifierResFound = aModifierObj;
1143         aCurrentModifierFeat = aModifierFeat;
1144         TNaming_Iterator aPairIter(aNewNS);
1145         aNewShape = aPairIter.NewShape();
1146         /*
1147         // searching for sub-shape equivalent on the sub-label of the new context result
1148         TDF_ChildIDIterator aNSIter(aNewNS->Label(), TNaming_NamedShape::GetID());
1149         for(; aNSIter.More(); aNSIter.Next()) {
1150           TNaming_Iterator aPairsIter(aNSIter.Value()->Label());
1151           for(; aPairsIter.More(); aPairsIter.Next()) {
1152             if (aSubShape->impl<TopoDS_Shape>().IsEqual()
1153           }
1154         }*/
1155         anIterate = true;
1156         break;
1157       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is null
1158         ResultPtr anEmptyContext;
1159         std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1160         setValue(anEmptyContext, anEmptyShape); // nullify the selection
1161         return;
1162       } else { // not-precessed modification => don't support it
1163         continue;
1164       }
1165     }
1166
1167     /*
1168     TNaming_NewShapeIterator aModifIter(aPairIter.NewShape(), aContLab);
1169     if (aModifIter.More()) aModifIter.Next(); // skip this shape result
1170     for(; aModifIter.More(); aModifIter.Next()) {
1171       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1172         (aDoc->objects()->object(aModifIter.Label().Father()));
1173       if (!aModifierObj.get())
1174         break;
1175       FeaturePtr aModifierFeat = aDoc->feature(aModifierObj);
1176       if (!aModifierFeat.get())
1177         break;
1178       if (aModifierFeat == aThisFeature || aDoc->objects()->isLater(aModifierFeat, aThisFeature))
1179         break; // the modifier feature is later than this, so, should not be used
1180       Handle(TNaming_NamedShape) aNewNS = aModifIter.NamedShape();
1181       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1182         aModifierResFound = aModifierObj;
1183       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is null
1184         ResultPtr anEmptyContext;
1185         std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1186         setValue(anEmptyContext, anEmptyShape); // nullify the selection
1187         return;
1188       } else { // not-precessed modification => don't support it
1189         break;
1190       }
1191     }
1192     // already found what is needed, don't iterate the next pair since normally
1193     if (aModifierResFound.get()) //  there must be only one pair in the result-shape
1194       break;
1195     */
1196   }
1197   if (aModifierResFound.get()) {
1198     // update scope to reset to a new one
1199     myScope.Clear();
1200     myRef.setValue(aModifierResFound);
1201     update(); // it must recompute a new sub-shape automatically
1202   }
1203   /*
1204   if (aModifierResFound.get()) {
1205     // update scope to reset to a new one
1206     myScope.Clear();
1207     if (!aSubShape.get() || aSubShape->isNull()) { // no sub-shape, so, just update a context
1208       setValue(aModifierResFound, aSubShape);
1209       return;
1210     }
1211     // seaching for the same sub-shape: the old topology stays the same
1212     TopoDS_Shape anOldShape = aSubShape->impl<TopoDS_Shape>();
1213     TopAbs_ShapeEnum aSubType = anOldShape.ShapeType();
1214     TopoDS_Shape aNewContext = aModifierResFound->shape()->impl<TopoDS_Shape>();
1215     TopExp_Explorer anExp(aNewContext, aSubType);
1216     for(; anExp.More(); anExp.Next()) {
1217       if (anExp.Current().IsEqual(anOldShape))
1218         break;
1219     }
1220     if (anExp.More()) { // found
1221       setValue(aModifierResFound, aSubShape);
1222       return;
1223     }
1224     // seaching for the same sub-shape: equal geometry
1225     for(anExp.Init(aNewContext, aSubType); anExp.More(); anExp.Next()) {
1226       if (aSubType == TopAbs_VERTEX) {
1227
1228       }
1229     }
1230   }*/
1231   // if sub-shape selection exists, search also sub-shape new instance
1232   /*
1233   GeomShapePtr aSubShape = value();
1234   if (aSubShape.get() && aSubShape != aContext->shape()) {
1235
1236   }*/
1237 }