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