]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
b1e9281c88ebf21ac9d907bbf35ffaf799d111c9
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "Model_AttributeSelection.h"
22 #include "Model_Application.h"
23 #include "Model_Events.h"
24 #include "Model_Data.h"
25 #include "Model_Document.h"
26 #include "Model_SelectionNaming.h"
27 #include <Model_Objects.h>
28 #include <Model_AttributeSelectionList.h>
29 #include <Model_ResultConstruction.h>
30 #include <ModelAPI_Feature.h>
31 #include <ModelAPI_ResultBody.h>
32 #include <ModelAPI_ResultBody.h>
33 #include <ModelAPI_ResultConstruction.h>
34 #include <ModelAPI_ResultPart.h>
35 #include <ModelAPI_CompositeFeature.h>
36 #include <ModelAPI_Tools.h>
37 #include <ModelAPI_Session.h>
38 #include <ModelAPI_Validator.h>
39 #include <ModelGeomAlgo_Shape.h>
40 #include <Events_InfoMessage.h>
41 #include <GeomAPI_Edge.h>
42 #include <GeomAPI_Pnt.h>
43 #include <GeomAPI_Vertex.h>
44 #include <GeomAlgoAPI_CompoundBuilder.h>
45 #include <GeomAlgoAPI_NExplode.h>
46 #include <Selector_Selector.h>
47
48 #include <TNaming_Selector.hxx>
49 #include <TNaming_NamedShape.hxx>
50 #include <TNaming_Tool.hxx>
51 #include <TNaming_Builder.hxx>
52 #include <TNaming_SameShapeIterator.hxx>
53 #include <TNaming_Iterator.hxx>
54 #include <TDataStd_Integer.hxx>
55 #include <TDataStd_UAttribute.hxx>
56 #include <TDataStd_Name.hxx>
57 #include <TopTools_ListOfShape.hxx>
58 #include <TopTools_DataMapOfShapeShape.hxx>
59 #include <TopTools_MapOfShape.hxx>
60 #include <TopExp_Explorer.hxx>
61 #include <BRep_Tool.hxx>
62 #include <TopoDS.hxx>
63 #include <TopExp.hxx>
64 #include <TDF_ChildIterator.hxx>
65 #include <TDF_ChildIDIterator.hxx>
66 #include <TopoDS_Iterator.hxx>
67 #include <TDF_ChildIDIterator.hxx>
68 #include <Geom_Circle.hxx>
69 #include <Geom_Ellipse.hxx>
70 #include <BRep_Builder.hxx>
71
72 //#define DEB_NAMING 1
73 #ifdef DEB_NAMING
74 #include <BRepTools.hxx>
75 #endif
76 /// added to the index in the packed map to signalize that the vertex of edge is selected
77 /// (multiplied by the index of the edge)
78 static const int kSTART_VERTEX_DELTA = 1000000;
79 // identifier that there is simple reference: selection equals to context
80 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
81 // reference to Part sub-object
82 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
83 // selection is invalid after recomputation
84 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
85
86 // identifier of the selection of the center of circle on edge
87 Standard_GUID kCIRCLE_CENTER("d0d0e0f1-217a-4b95-8fbb-0c4132f23718");
88 // identifier of the selection of the first focus point of ellipse on edge
89 Standard_GUID kELLIPSE_CENTER1("f70df04c-3168-4dc9-87a4-f1f840c1275d");
90 // identifier of the selection of the second focus point of ellipse on edge
91 Standard_GUID kELLIPSE_CENTER2("1395ae73-8e02-4cf8-b204-06ff35873a32");
92 // identifier of the weak naming index
93 Standard_GUID kWEAK_NAMING("9dcdd9be-a3a9-46eb-9b16-1c957ab20142");
94 // identifier of the weak naming sub-shape type
95 Standard_GUID kWEAK_NAMING_SHAPETYPE("6b9cc709-e320-4a1f-9c42-df5622369ea7");
96
97 // prefix for the whole feature context identification
98 const static std::string kWHOLE_FEATURE = "all-in-";
99
100 // on this label is stored:
101 // TNaming_NamedShape - selected shape
102 // TNaming_Naming - topological selection information (for the body)
103 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
104 // TDataStd_Integer - type of the selected shape (for construction)
105 // TDF_Reference - from ReferenceAttribute, the context
106 bool Model_AttributeSelection::setValue(const ObjectPtr& theContext,
107   const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
108 {
109   if (theTemporarily &&
110       (!theContext.get() || theContext->groupName() != ModelAPI_Feature::group())) {
111     // just keep the stored without DF update
112     myTmpContext = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
113     myTmpSubShape = theSubShape;
114     owner()->data()->sendAttributeUpdated(this);
115     return true;
116   } else {
117     myTmpContext.reset();
118     myTmpSubShape.reset();
119     myTmpCenterType = NOT_CENTER;
120   }
121
122   CenterType aType;
123   const std::shared_ptr<GeomAPI_Shape>& anOldShape = internalValue(aType);
124   bool isOldContext = theContext == myRef.value();
125   bool isOldShape = isOldContext &&
126     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
127   if (isOldShape) return false; // shape is the same, so context is also unchanged
128   bool aToUnblock = false;
129   // update the referenced object if needed
130   if (!isOldContext) {
131     aToUnblock = !owner()->data()->blockSendAttributeUpdated(true);
132     myRef.setValue(theContext);
133   }
134
135   // do noth use naming if selected shape is result shape itself, but not sub-shape
136   TDF_Label aSelLab = selectionLabel();
137   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
138   aSelLab.ForgetAttribute(kINVALID_SELECTION);
139   aSelLab.ForgetAttribute(kCIRCLE_CENTER);
140   aSelLab.ForgetAttribute(kELLIPSE_CENTER1);
141   aSelLab.ForgetAttribute(kELLIPSE_CENTER2);
142   aSelLab.ForgetAttribute(kWEAK_NAMING);
143   aSelLab.ForgetAttribute(kWEAK_NAMING_SHAPETYPE);
144
145   bool isDegeneratedEdge = false;
146   // do not use the degenerated edge as a shape, a null context and shape is used in the case
147   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
148     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
149     if (aSubShape.ShapeType() == TopAbs_EDGE)
150       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
151   }
152   if (!theContext.get() || isDegeneratedEdge) {
153     // to keep the reference attribute label
154     TDF_Label aRefLab = myRef.myRef->Label();
155     aSelLab.ForgetAllAttributes(true);
156     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
157     if (aToUnblock)
158       owner()->data()->blockSendAttributeUpdated(false);
159     return false;
160   }
161   bool isSelectBody = theContext->groupName() == ModelAPI_ResultBody::group();
162   if (!isSelectBody) {
163     ResultConstructionPtr aContextConstruction =
164       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
165     isSelectBody = aContextConstruction.get() && !aContextConstruction->isInfinite();
166   }
167   if (isSelectBody) {
168     ResultPtr aContextResult = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
169     GeomShapePtr aContextShape = aContextResult->shape();
170     // do not select the whole shape for body:it is already must be in the data framework
171     // equal and null selected objects mean the same: object is equal to context,
172     if (aContextShape.get() && (aContextShape->isEqual(theSubShape) || !theSubShape.get())) {
173       aSelLab.ForgetAllAttributes(true);
174       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
175     } else {
176       selectBody(aContextResult, theSubShape);
177     }
178   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
179     aSelLab.ForgetAllAttributes(true); // to remove old selection data
180     std::shared_ptr<Model_ResultConstruction> aConstruction =
181       std::dynamic_pointer_cast<Model_ResultConstruction>(theContext);
182     std::shared_ptr<GeomAPI_Shape> aSubShape;
183     if (theSubShape.get() && !aConstruction->shape()->isEqual(theSubShape))
184       aSubShape = theSubShape; // the whole context
185     if (aConstruction->isInfinite()) {
186       // For correct naming selection, put the shape into the naming structure.
187       // It seems sub-shapes are not needed: only this shape is (and can be) selected.
188       TNaming_Builder aBuilder(aSelLab);
189       aBuilder.Generated(aConstruction->shape()->impl<TopoDS_Shape>());
190     }
191   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
192     aSelLab.ForgetAllAttributes(true);
193     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
194     selectPart(std::dynamic_pointer_cast<ModelAPI_Result>(theContext), theSubShape);
195   } else { // check the feature context: parent-Part of this feature should not be used
196     FeaturePtr aFeatureContext = std::dynamic_pointer_cast<ModelAPI_Feature>(theContext);
197     if (aFeatureContext.get()) {
198       if (owner()->document() != aFeatureContext->document()) {
199         aSelLab.ForgetAllAttributes(true);
200         myRef.setValue(ObjectPtr());
201         if (aToUnblock)
202           owner()->data()->blockSendAttributeUpdated(false);
203         return false;
204       }
205     }
206   }
207
208   owner()->data()->sendAttributeUpdated(this);
209
210   if (aToUnblock)
211     owner()->data()->blockSendAttributeUpdated(false);
212
213   return true;
214 }
215
216 void Model_AttributeSelection::setValueCenter(
217     const ObjectPtr& theContext, const std::shared_ptr<GeomAPI_Edge>& theEdge,
218     const CenterType theCenterType, const bool theTemporarily)
219 {
220   bool anUpdated = setValue(theContext, theEdge, theTemporarily);
221   if (theTemporarily) {
222     myTmpCenterType = theCenterType;
223   } else { // store in the data structure
224     TDF_Label aSelLab = selectionLabel();
225     switch(theCenterType) {
226     case CIRCLE_CENTER:
227       if (!anUpdated)
228         anUpdated = !aSelLab.IsAttribute(kCIRCLE_CENTER);
229       TDataStd_UAttribute::Set(aSelLab, kCIRCLE_CENTER);
230       break;
231     case ELLIPSE_FIRST_FOCUS:
232       if (!anUpdated)
233         anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER1);
234       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER1);
235       break;
236     case ELLIPSE_SECOND_FOCUS:
237       if (!anUpdated)
238         anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER2);
239       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER2);
240       break;
241     }
242     if (anUpdated)
243       owner()->data()->sendAttributeUpdated(this);
244   }
245 }
246
247 void Model_AttributeSelection::selectValue(
248     const std::shared_ptr<ModelAPI_AttributeSelection>& theSource)
249 {
250   CenterType aType;
251   std::shared_ptr<GeomAPI_Shape> aValue =
252     std::dynamic_pointer_cast<Model_AttributeSelection>(theSource)->internalValue(aType);
253   if (!aValue.get() || aType == NOT_CENTER) {
254     setValue(theSource->context(), aValue);
255   } else {
256     std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge);
257     anEdge->setImpl(new TopoDS_Shape(aValue->impl<TopoDS_Shape>()));
258     setValueCenter(theSource->context(), anEdge, aType);
259   }
260 }
261
262 void Model_AttributeSelection::removeTemporaryValues()
263 {
264   if (myTmpContext.get() || myTmpSubShape.get()) {
265     myTmpContext.reset();
266     myTmpSubShape.reset();
267   }
268 }
269
270 // returns the center of the edge: circular or elliptical
271 GeomShapePtr centerByEdge(GeomShapePtr theEdge, ModelAPI_AttributeSelection::CenterType theType)
272 {
273   if (theType != ModelAPI_AttributeSelection::NOT_CENTER && theEdge.get() != NULL) {
274     TopoDS_Shape aShape = theEdge->impl<TopoDS_Shape>();
275     if (!aShape.IsNull() && aShape.ShapeType() == TopAbs_EDGE) {
276       TopoDS_Edge anEdge = TopoDS::Edge(aShape);
277       double aFirst, aLast;
278       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
279       if (!aCurve.IsNull()) {
280         TopoDS_Vertex aVertex;
281         BRep_Builder aBuilder;
282         if (theType == ModelAPI_AttributeSelection::CIRCLE_CENTER) {
283           Handle(Geom_Circle) aCirc = Handle(Geom_Circle)::DownCast(aCurve);
284           if (!aCirc.IsNull()) {
285             aBuilder.MakeVertex(aVertex, aCirc->Location(), Precision::Confusion());
286           }
287         } else { // ellipse
288           Handle(Geom_Ellipse) anEll = Handle(Geom_Ellipse)::DownCast(aCurve);
289           if (!anEll.IsNull()) {
290             aBuilder.MakeVertex(aVertex,
291               theType == ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS ?
292               anEll->Focus1() : anEll->Focus2(), Precision::Confusion());
293           }
294         }
295         if (!aVertex.IsNull()) {
296           std::shared_ptr<GeomAPI_Vertex> aResult(new GeomAPI_Vertex);
297           aResult->setImpl(new TopoDS_Vertex(aVertex));
298           return aResult;
299         }
300       }
301     }
302   }
303   return theEdge; // no vertex, so, return the initial edge
304 }
305
306 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
307 {
308   if (!ModelAPI_AttributeSelection::isInitialized() && !myTmpContext.get() && !myTmpSubShape.get())
309     return std::shared_ptr<GeomAPI_Shape>();
310   CenterType aType = NOT_CENTER;
311   std::shared_ptr<GeomAPI_Shape> aResult = internalValue(aType);
312   return centerByEdge(aResult, aType);
313 }
314
315 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::internalValue(CenterType& theType)
316 {
317   theType = NOT_CENTER;
318   GeomShapePtr aResult;
319   if (myTmpContext.get() || myTmpSubShape.get()) {
320     theType = myTmpCenterType;
321     ResultConstructionPtr aResulConstruction =
322       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myTmpContext);
323     if(aResulConstruction.get()) {
324       // it is just reference to construction.
325       return myTmpSubShape;
326     }
327     return myTmpSubShape.get() ? myTmpSubShape : myTmpContext->shape();
328   }
329
330   TDF_Label aSelLab = selectionLabel();
331   if (aSelLab.IsAttribute(kINVALID_SELECTION))
332     return aResult;
333
334   if (aSelLab.IsAttribute(kCIRCLE_CENTER))
335     theType = CIRCLE_CENTER;
336   else if (aSelLab.IsAttribute(kELLIPSE_CENTER1))
337     theType = ELLIPSE_FIRST_FOCUS;
338   else if (aSelLab.IsAttribute(kELLIPSE_CENTER2))
339     theType = ELLIPSE_SECOND_FOCUS;
340
341
342   if (myRef.isInitialized()) {
343     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
344       ResultPtr aContext = context();
345       if (!aContext.get() || aContext->groupName() == ModelAPI_ResultConstruction::group())
346         return aResult; // empty result, for whole construction selection also
347       return aContext->shape();
348     }
349     if (aSelLab.IsAttribute(kPART_REF_ID)) {
350       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
351       if (!aPart.get() || !aPart->isActivated())
352         return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
353       Handle(TDataStd_Integer) anIndex;
354       if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
355         if (anIndex->Get()) { // special selection attribute was created, use it
356           return aPart->selectionValue(anIndex->Get());
357         } else { // face with name is already in the data model, so try to take it by name
358           Handle(TDataStd_Name) aName;
359           if (aSelLab.FindAttribute(TDataStd_Name::GetID(), aName)) {
360             std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
361             std::size_t aPartEnd = aSubShapeName.find('/');
362             if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
363               std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
364               int anIndex;
365               std::string aType; // to reuse already existing selection the type is not needed
366               return aPart->shapeInPart(aNameInPart, aType, anIndex);
367             }
368           }
369         }
370       }
371     }
372
373     std::shared_ptr<Model_ResultConstruction> aConstr =
374       std::dynamic_pointer_cast<Model_ResultConstruction>(context());
375     if (aConstr) {
376       if (aConstr->isInfinite())
377         return aResult; // empty result
378     }
379     if (!aConstr.get()) { // for construction context, return empty result as usual even
380       // the whole feature is selected
381       FeaturePtr aFeature = contextFeature();
382       if (aFeature.get()) {
383         std::list<GeomShapePtr> allShapes;
384         std::list<ResultPtr>::const_iterator aRes = aFeature->results().cbegin();
385         for (; aRes != aFeature->results().cend(); aRes++) {
386           if (aRes->get() && !(*aRes)->isDisabled()) {
387             GeomShapePtr aShape = (*aRes)->shape();
388             if (aShape.get() && !aShape->isNull()) {
389               allShapes.push_back(aShape);
390             }
391           }
392         }
393         return GeomAlgoAPI_CompoundBuilder::compound(allShapes);
394       }
395     }
396
397     if (aSelLab.IsAttribute(kWEAK_NAMING)) { // a weak naming is used
398       Handle(TDataStd_Integer) aWeakId;
399       aSelLab.FindAttribute(kWEAK_NAMING, aWeakId);
400       // get the context shape
401       GeomShapePtr aContextShape;
402       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(context());
403       if (aBody.get()) {
404         aContextShape = aBody->shape();
405       } else {
406         ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
407         if (aResult) {
408           aContextShape = aResult->shape();
409         }
410       }
411       if (!aContextShape.get())
412         return GeomShapePtr();
413       Handle(TDataStd_Integer) aWeakShapeType;
414       aSelLab.FindAttribute(kWEAK_NAMING_SHAPETYPE, aWeakShapeType);
415       GeomAlgoAPI_NExplode aNExplode(
416         aContextShape, GeomAPI_Shape::ShapeType(aWeakShapeType->Get()));
417       GeomShapePtr aValue = aNExplode.shape(aWeakId->Get());
418       return aValue;
419     }
420
421     Handle(TNaming_NamedShape) aSelection;
422     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
423       TopoDS_Shape aSelShape = aSelection->Get();
424       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
425       aResult->setImpl(new TopoDS_Shape(aSelShape));
426     } else if (aConstr) { // simple construction element: just shape of this construction element
427       aResult = aConstr->shape();
428     }
429   }
430   return aResult;
431 }
432
433 bool Model_AttributeSelection::isInvalid()
434 {
435   return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
436 }
437
438 bool Model_AttributeSelection::isInitialized()
439 {
440   if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
441     std::shared_ptr<GeomAPI_Shape> aResult;
442     if (myRef.isInitialized()) {
443       TDF_Label aSelLab = selectionLabel();
444       if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
445         ResultPtr aContext = context();
446         return aContext.get() != NULL;
447       }
448       Handle(TNaming_NamedShape) aSelection;
449       if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
450         return !aSelection->Get().IsNull();
451       } else { // for simple construction element: just shape of this construction element
452         std::shared_ptr<Model_ResultConstruction> aConstr =
453           std::dynamic_pointer_cast<Model_ResultConstruction>(context());
454         if (aConstr.get()) {
455             return true;
456         }
457         // for the whole feature, a feature object
458         FeaturePtr aFeat = contextFeature();
459         if (aFeat.get())
460           return true;
461       }
462     }
463   }
464   return false;
465 }
466
467 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
468   : myRef(theLabel)
469 {
470   myIsInitialized = myRef.isInitialized();
471   myParent = NULL;
472 }
473
474 void Model_AttributeSelection::setID(const std::string theID)
475 {
476   myRef.setID(theID);
477   ModelAPI_AttributeSelection::setID(theID);
478 }
479
480 ResultPtr Model_AttributeSelection::context()
481 {
482   if (!ModelAPI_AttributeSelection::isInitialized() && !myTmpContext.get() && !myTmpSubShape.get())
483     return ResultPtr();
484
485   if (myTmpContext.get() || myTmpSubShape.get()) {
486     return myTmpContext;
487   }
488
489   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
490   // for parts there could be same-data result, so take the last enabled
491   if (aResult.get()) {
492     if(aResult->groupName() == ModelAPI_ResultPart::group()) {
493       int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
494       for(int a = aSize - 1; a >= 0; a--) {
495         ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
496         if(aPart.get() && aPart->data() == aResult->data()) {
497           ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
498           FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
499           // check that this result is not this-feature result (it is forbidden t oselect itself)
500           if(anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
501             return aPartResult;
502           }
503         }
504       }
505     }
506   } else { // if feature - construction is selected, it has only one result, return this result
507     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
508     if (aFeature.get() && aFeature->results().size() == 1 &&
509         aFeature->firstResult()->groupName() == ModelAPI_ResultConstruction::group())
510       return aFeature->firstResult();
511   }
512   return aResult;
513 }
514
515 FeaturePtr Model_AttributeSelection::contextFeature() {
516   if (myTmpContext.get() || myTmpSubShape.get()) {
517     return FeaturePtr(); // feature can not be selected temporarily
518   }
519   return std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
520 }
521 ObjectPtr Model_AttributeSelection::contextObject() {
522   FeaturePtr aRes = contextFeature();
523   if (aRes.get())
524     return aRes;
525   return context();
526 }
527
528
529 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
530 {
531   ModelAPI_AttributeSelection::setObject(theObject);
532   myRef.setObject(theObject);
533 }
534
535 TDF_LabelMap& Model_AttributeSelection::scope()
536 {
537   if (myScope.IsEmpty()) { // create a new scope if not yet done
538     // gets all features with named shapes that are before this feature label (before in history)
539     DocumentPtr aMyDoc = owner()->document();
540     std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
541     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
542     bool aMePassed = false;
543     CompositeFeaturePtr aComposite =
544       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
545     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
546     CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
547     if (aFeature.get()) {
548       aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
549       if (aCompositeOwner.get()) {
550          aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
551       }
552     }
553     // for group Scope is not limitet: this is always up to date objects
554     // this causes problem in galeries.py
555     //bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
556     for(; aFIter != allFeatures.end(); aFIter++) {
557       if (*aFIter == owner()) {  // the left features are created later (except subs of composite)
558         aMePassed = true;
559         continue;
560       }
561       //if (isGroup) aMePassed = false;
562       bool isInScope = !aMePassed;
563       if (!isInScope && aComposite.get()) {
564         // try to add sub-elements of composite if this is composite
565         if (aComposite->isSub(*aFIter))
566           isInScope = true;
567       }
568       // remove the composite-owner of this feature (sketch in extrusion-cut)
569       if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
570         isInScope = false;
571
572       if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
573         TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
574           (*aFIter)->data())->label().Father();
575         TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), true);
576         for(; aNSIter.More(); aNSIter.Next()) {
577           Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
578           if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
579             myScope.Add(aNS->Label());
580           }
581         }
582       }
583     }
584     // also add all naming labels created for external constructions
585     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(aMyDoc);
586     TDF_Label anExtDocLab = aDoc->extConstructionsLabel();
587     TDF_ChildIDIterator aNSIter(anExtDocLab, TNaming_NamedShape::GetID(), true);
588     for(; aNSIter.More(); aNSIter.Next()) {
589       Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
590       if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
591         myScope.Add(aNS->Label());
592       }
593     }
594   }
595   return myScope;
596 }
597
598 /// Sets the invalid flag if flag is false, or removes it if "true"
599 /// Returns theFlag
600 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
601   if (theFlag) {
602     theLab.ForgetAttribute(kINVALID_SELECTION);
603   } else {
604     TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
605   }
606   return theFlag;
607 }
608
609 void Model_AttributeSelection::split(
610   ResultPtr theContext, TopoDS_Shape theNewShape, TopAbs_ShapeEnum theType)
611 {
612   TopTools_ListOfShape aSubs;
613   for(TopoDS_Iterator anExplorer(theNewShape); anExplorer.More(); anExplorer.Next()) {
614     if (!anExplorer.Value().IsNull() &&
615       anExplorer.Value().ShapeType() == theType) {
616         aSubs.Append(anExplorer.Value());
617     } else { // invalid case; bad result shape, so, impossible to split easily
618       aSubs.Clear();
619       break;
620     }
621   }
622   if (aSubs.Extent() > 1) { // ok to split
623     TopTools_ListIteratorOfListOfShape aSub(aSubs);
624     GeomShapePtr aSubSh(new GeomAPI_Shape);
625     aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
626     setValue(theContext, aSubSh);
627     for(aSub.Next(); aSub.More(); aSub.Next()) {
628       GeomShapePtr aSubSh(new GeomAPI_Shape);
629       aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
630       myParent->append(theContext, aSubSh);
631     }
632   }
633 }
634
635 bool Model_AttributeSelection::update()
636 {
637   FeaturePtr aContextFeature = contextFeature();
638   if (aContextFeature.get()) {
639     return true;
640   }
641   TDF_Label aSelLab = selectionLabel();
642   ResultPtr aContext = context();
643   if (!aContext.get())
644     return setInvalidIfFalse(aSelLab, false);
645   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
646     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
647   }
648
649   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
650     std::shared_ptr<GeomAPI_Shape> aNoSelection;
651     bool aResult = selectPart(aContext, aNoSelection, true);
652     aResult = setInvalidIfFalse(aSelLab, aResult);
653     if (aResult) {
654       owner()->data()->sendAttributeUpdated(this);
655     }
656     return aResult;
657   }
658
659   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
660     if (aSelLab.IsAttribute(kWEAK_NAMING)) { // a weak naming is used
661       Handle(TDataStd_Integer) aWeakId;
662       aSelLab.FindAttribute(kWEAK_NAMING, aWeakId);
663       // get the context shape
664       GeomShapePtr aContextShape;
665       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aContext);
666       if (aBody.get()) {
667         aContextShape = aBody->shape();
668       } else {
669         ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
670         if (aResult) {
671           aContextShape = aResult->shape();
672         }
673       }
674       if (!setInvalidIfFalse(aSelLab, aContextShape.get() != NULL)) // context shape not found
675         return false;
676       Handle(TDataStd_Integer) aWeakShapeType;
677       aSelLab.FindAttribute(kWEAK_NAMING_SHAPETYPE, aWeakShapeType);
678       GeomAlgoAPI_NExplode aNExplode(
679         aContextShape, GeomAPI_Shape::ShapeType(aWeakShapeType->Get()));
680       GeomShapePtr aValue = aNExplode.shape(aWeakId->Get());
681       return setInvalidIfFalse(aSelLab, aValue.get() != NULL);
682     }
683     // body: just a named shape, use topological selection mechanism
684     bool aResult = false;
685     TopoDS_Shape anOldShape;
686     Handle(TNaming_NamedShape) aNS;
687     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
688       anOldShape = aNS->Get();
689
690     Selector_Selector aSelector(aSelLab);
691     if (!aSelector.restore()) { // it is stored in old OCCT format, use TNaming_Selector
692       TNaming_Selector aSelector(aSelLab);
693       if (!aSelector.NamedShape().IsNull()) {
694         anOldShape = aSelector.NamedShape()->Get();
695       }
696       aResult = aSelector.Solve(scope()) == Standard_True;
697     } else {
698       TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
699       aResult = aSelector.solve(aContextShape);
700     }
701     aResult = setInvalidIfFalse(aSelLab, aResult);
702
703     TopoDS_Shape aNewShape;
704     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
705       aNewShape = aNS->Get();
706
707     if (anOldShape.IsNull() || aNewShape.IsNull() || !anOldShape.IsEqual(aNewShape)) {
708       // shape type shoud not not changed: if shape becomes compound of such shapes, then split
709       if (myParent && !anOldShape.IsNull() && !aNewShape.IsNull() &&
710           anOldShape.ShapeType() != aNewShape.ShapeType() &&
711           (aNewShape.ShapeType() == TopAbs_COMPOUND || aNewShape.ShapeType() == TopAbs_COMPSOLID))
712       {
713         split(aContext, aNewShape, anOldShape.ShapeType());
714       }
715       owner()->data()->sendAttributeUpdated(this);  // send updated if shape is changed
716     }
717     return aResult;
718   }
719
720   if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
721     bool aResult = true;
722     std::shared_ptr<Model_ResultConstruction> aConstructionContext =
723       std::dynamic_pointer_cast<Model_ResultConstruction>(aContext);
724     if (!aConstructionContext->isInfinite()) {
725       Selector_Selector aSelector(aSelLab);
726       aResult = aSelector.restore();
727       if (aResult) {
728         TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
729         aResult = aSelector.solve(aContextShape);
730       }
731       aResult = setInvalidIfFalse(aSelLab, aResult);
732     }
733     return aResult;
734   }
735   return setInvalidIfFalse(aSelLab, false); // unknown case
736 }
737
738 void Model_AttributeSelection::selectBody(
739   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
740 {
741   // perform the selection
742   TopoDS_Shape aContext;
743
744   ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);//myRef.value()
745   if (aBody) {
746     aContext = aBody->shape()->impl<TopoDS_Shape>();
747   } else {
748     ResultPtr aResult =
749       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
750     if (aResult) {
751       aContext = aResult->shape()->impl<TopoDS_Shape>();
752     } else {
753       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
754       return;
755     }
756   }
757
758   // with "recover" feature the selected context may be not up to date (issue 1710)
759   TDF_Label aSelLab = selectionLabel();
760   TopoDS_Shape aNewSub = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
761
762   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
763   if (!aContext.IsNull()) {
764     FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
765     bool aEraseResults = false;
766     if (aFeatureOwner.get()) {
767       aEraseResults = !aFeatureOwner->results().empty();
768       if (aEraseResults) // erase results without flash deleted and redisplay: do it after Select
769         aFeatureOwner->removeResults(0, false, false);
770     }
771     bool aSelectorOk = true;
772     //TNaming_Selector aSel(aSelLab);
773     Selector_Selector aSel(aSelLab);
774     try {
775       //aSel.Select(aNewSub, aNewContext);
776       aSelectorOk = aSel.select(aContext, aNewSub);
777       if (aSelectorOk) {
778         aSel.store();
779         aSelectorOk = aSel.solve(aContext);
780       }
781     } catch(...) {
782       aSelectorOk = false;
783     }
784     // face may become divided after the model update, so, new labels may be added to the scope
785     myScope.Clear();
786
787     // check that selection is correct, otherwise use weak naming solution
788     TDF_Label aSelLab = selectionLabel();
789     aSelLab.ForgetAttribute(kWEAK_NAMING);
790     Handle(TNaming_NamedShape) aSelectorShape;
791     if (aSelectorOk && aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aSelectorShape))
792     {
793       TopoDS_Shape aShape = aSelectorShape->Get();
794       if (aShape.IsNull() || aShape.ShapeType() != aNewSub.ShapeType())
795         aSelectorOk = false;
796     }
797     if (!aSelectorOk) { // weak naming identifier instead
798       GeomShapePtr aContextShape(new GeomAPI_Shape);
799       aContextShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aContext));
800       GeomShapePtr aValueShape(new GeomAPI_Shape);
801       aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewSub));
802
803       GeomAlgoAPI_NExplode aNExplode(aContextShape, aValueShape->shapeType());
804       int anId = aNExplode.index(aValueShape);
805       if (anId) {
806         TDataStd_Integer::Set(aSelLab, kWEAK_NAMING, anId);
807         TDataStd_Integer::Set(aSelLab, kWEAK_NAMING_SHAPETYPE, int(aValueShape->shapeType()));
808       }
809     }
810
811     if (aEraseResults) { // flash after Select : in Groups it makes selection with shift working
812       static Events_Loop* aLoop = Events_Loop::loop();
813       static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
814       aLoop->flush(kDeletedEvent);
815     }
816   }
817 }
818
819 bool Model_AttributeSelection::selectPart(
820   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
821   const bool theUpdate)
822 {
823   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
824   if (!aPart.get() || !aPart->isActivated())
825     return true; // postponed naming
826   if (theUpdate) {
827     Handle(TDataStd_Integer) anIndex;
828     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
829       // by internal selection
830       if (anIndex->Get() > 0) {
831         // update the selection by index
832         return aPart->updateInPart(anIndex->Get());
833       } else {
834         return true; // nothing to do, referencing just by name
835       }
836     }
837     return true; // nothing to do, referencing just by name
838   }
839   // store the shape (in case part is not loaded it should be useful
840   TopoDS_Shape aShape;
841   std::string aName = theContext->data()->name();
842   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
843     aShape = theContext->shape()->impl<TopoDS_Shape>();
844   } else {
845     aShape = theSubShape->impl<TopoDS_Shape>();
846     int anIndex;
847     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
848     TDataStd_Integer::Set(selectionLabel(), anIndex);
849   }
850   TNaming_Builder aBuilder(selectionLabel());
851   aBuilder.Select(aShape, aShape);
852   // identify by name in the part
853   TDataStd_Name::Set(selectionLabel(), aName.c_str());
854   return !aName.empty();
855 }
856
857 TDF_Label Model_AttributeSelection::selectionLabel()
858 {
859   return myRef.myRef->Label().FindChild(1);
860 }
861
862 /// prefixes of the shape names with centers defined
863 static std::map<ModelAPI_AttributeSelection::CenterType, std::string> kCENTERS_PREFIX;
864
865 /// returns the map that contains all possible prefixes of the center-names
866 static std::map<ModelAPI_AttributeSelection::CenterType, std::string>& centersMap()
867 {
868   if (kCENTERS_PREFIX.empty()) { // fill map by initial values
869     kCENTERS_PREFIX[ModelAPI_AttributeSelection::CIRCLE_CENTER] = "__cc";
870     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS] = "__eff";
871     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_SECOND_FOCUS] = "__esf";
872   }
873   return kCENTERS_PREFIX;
874 }
875
876 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
877 {
878   std::string aName("");
879   if(!this->isInitialized())
880     return !theDefaultName.empty() ? theDefaultName : aName;
881
882   CenterType aCenterType = NOT_CENTER;
883   std::shared_ptr<GeomAPI_Shape> aSubSh = internalValue(aCenterType);
884   ResultPtr aCont = context();
885
886   if (!aCont.get() ||
887       (aCont->groupName() == ModelAPI_ResultConstruction::group() && contextFeature().get())) {
888     // selection of a full feature
889     FeaturePtr aFeatureCont = contextFeature();
890     if (aFeatureCont.get()) {
891       return kWHOLE_FEATURE + aFeatureCont->name();
892     }
893     // in case of selection of removed result
894     return "";
895   }
896
897   TDF_Label aSelLab = selectionLabel();
898   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // whole context, no value
899     return contextName(aCont);
900   }
901
902   Handle(TDataStd_Integer) aWeakId;
903   if (aSelLab.FindAttribute(kWEAK_NAMING, aWeakId)) { // a weak naming is used
904     std::ostringstream aNameStream;
905     aNameStream<<contextName(aCont)<<"/weak_name_"<<aWeakId->Get();
906     return aNameStream.str();
907   }
908
909   // whole infinitive construction
910   if (aCont->groupName() == ModelAPI_ResultConstruction::group()) {
911     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<Model_ResultConstruction>(aCont);
912     if (aConstr->isInfinite()) {
913       return contextName(aCont);
914     }
915   }
916
917   Selector_Selector aSelector(aSelLab);
918   std::string aResult;
919   if (aSelector.restore())
920     aResult = aSelector.name(this);
921   /*
922   Model_SelectionNaming aSelNaming(aSelLab);
923   std::string aResult = aSelNaming.namingName(
924     aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
925     */
926   if (aCenterType != NOT_CENTER) {
927     aResult += centersMap()[aCenterType];
928   }
929   return aResult;
930 }
931
932 // returns the center type and modifies the shape name if this name is center-name
933 static ModelAPI_AttributeSelection::CenterType centerTypeByName(std::string& theShapeName)
934 {
935   std::map<ModelAPI_AttributeSelection::CenterType, std::string>::iterator aPrefixIter =
936     centersMap().begin();
937   for(; aPrefixIter != centersMap().end(); aPrefixIter++) {
938     std::size_t aFound = theShapeName.find(aPrefixIter->second);
939     if (aFound != std::string::npos &&
940         aFound == theShapeName.size() - aPrefixIter->second.size()) {
941       theShapeName = theShapeName.substr(0, aFound);
942       return aPrefixIter->first;
943     }
944   }
945   return ModelAPI_AttributeSelection::NOT_CENTER;
946 }
947
948 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
949 void Model_AttributeSelection::selectSubShape(
950   const std::string& theType, const std::string& theSubShapeName)
951 {
952   if(theSubShapeName.empty() || theType.empty()) return;
953
954   std::string aSubShapeName = theSubShapeName;
955   CenterType aCenterType = theType[0] == 'v' || theType[0] == 'V' ? // only for vertex-type
956     centerTypeByName(aSubShapeName) : NOT_CENTER;
957   std::string aType = aCenterType == NOT_CENTER ? theType : "EDGE"; // search for edge now
958   TopAbs_ShapeEnum aShapeType =  TopAbs_ShapeEnum(GeomAPI_Shape::shapeTypeByStr(theType));
959   static const GeomShapePtr anEmptyShape;
960
961   // first iteration is selection by name without center prefix, second - in case of problem,
962   // try with initial name
963   for(int aUseCenter = 1; aUseCenter >= 0; aUseCenter--)  {
964     std::string aSubShapeName = theSubShapeName;
965     if (aUseCenter == 0 && aCenterType != NOT_CENTER) {
966       aCenterType = NOT_CENTER;
967       aType = theType;
968     } else if (aUseCenter != 1) continue;
969
970     std::shared_ptr<Model_Document> aDoc =
971       std::dynamic_pointer_cast<Model_Document>(owner()->document());
972     // check this is Part-name: 2 delimiters in the name
973     std::size_t aPartEnd = aSubShapeName.find('/');
974     if (aPartEnd != std::string::npos) {
975       std::string aPartName = aSubShapeName.substr(0, aPartEnd);
976       DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
977       if (aPartName == aRootDoc->kind()) {
978         aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
979         aSubShapeName = aSubShapeName.substr(aPartEnd + 1);
980       } else {
981         ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
982         if (aFound.get()) { // found such part, so asking it for the name
983           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
984           aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
985           aSubShapeName = aSubShapeName.substr(aPartEnd +1);
986         }
987       }
988     }
989
990     // check this is a whole feature context
991     if (aSubShapeName.size() > kWHOLE_FEATURE.size() &&
992       aSubShapeName.substr(0, kWHOLE_FEATURE.size()) == kWHOLE_FEATURE) {
993       std::string aFeatureName = aSubShapeName.substr(kWHOLE_FEATURE.size());
994       ObjectPtr anObj = aDoc->objectByName(ModelAPI_Feature::group(), aFeatureName);
995       if (anObj.get()) {
996         setValue(anObj, anEmptyShape);
997         return;
998       }
999     }
1000
1001     // the whole result selection check
1002     if (aSubShapeName.find('/') == std::string::npos) {
1003       ObjectPtr aRes = aDoc->objectByName(ModelAPI_ResultConstruction::group(), aSubShapeName);
1004       if (!aRes.get())
1005         aRes = aDoc->objectByName(ModelAPI_ResultBody::group(), aSubShapeName);
1006       if (aRes.get()) {
1007         setValue(aRes, anEmptyShape);
1008         return;
1009       }
1010     }
1011
1012     Selector_Selector aSelector(aDoc->generalLabel());
1013     myRestoreDocument = aDoc;
1014     TDF_Label aContextLabel = aSelector.restoreByName(aSubShapeName, aShapeType, this);
1015     myRestoreDocument.reset();
1016     if (!aContextLabel.IsNull()) {
1017       ResultPtr aContext = aDoc->resultByLab(aContextLabel); // any label for document access
1018       if (aContext.get() && aContext->shape().get()) {
1019         TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
1020         if (aSelector.solve(aContextShape)) {
1021           GeomShapePtr aShapeToBeSelected(new GeomAPI_Shape);
1022           aShapeToBeSelected->setImpl<TopoDS_Shape>(new TopoDS_Shape(aSelector.value()));
1023           if (aCenterType != NOT_CENTER) {
1024             if (!aShapeToBeSelected->isEdge())
1025               continue;
1026             std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aShapeToBeSelected));
1027             setValueCenter(aContext, aSelectedEdge, aCenterType);
1028           }
1029           else
1030             setValue(aContext, aShapeToBeSelected);
1031           return;
1032         }
1033       }
1034     }
1035     aSubShapeName = theSubShapeName;
1036   }
1037   // invalid
1038   TDF_Label aSelLab = selectionLabel();
1039   setInvalidIfFalse(aSelLab, false);
1040   reset();
1041 }
1042
1043 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1044                                               const GeomPointPtr& thePoint)
1045 {
1046   if (theType.empty() || !thePoint)
1047     return;
1048
1049   // list of parent features
1050   FeaturePtr anOwner = ModelAPI_Feature::feature(owner());
1051   std::set<FeaturePtr> aParents = ModelAPI_Tools::getParents(anOwner);
1052
1053   int aSelectionIndex = 0;
1054   GeomAPI_Shape::ShapeType aType = GeomAPI_Shape::shapeTypeByStr(theType);
1055   if (aType == GeomAPI_Shape::SHAPE) {
1056     // possibly, the string consists of the type and the index,
1057     // thus, try to separate them
1058     size_t aUndersporePos = theType.find_first_of('_');
1059     if (aUndersporePos != std::string::npos)
1060       aType = GeomAPI_Shape::shapeTypeByStr(theType.substr(0, aUndersporePos));
1061
1062     if (aType != GeomAPI_Shape::SHAPE) {
1063       for (std::string::const_iterator aChar = theType.begin() + aUndersporePos + 1;
1064            aChar != theType.end(); ++aChar) {
1065         if (std::isdigit(*aChar))
1066           aSelectionIndex = aSelectionIndex * 10 + (*aChar - '0');
1067         else {
1068           aSelectionIndex = 1;
1069           break;
1070         }
1071       }
1072       aSelectionIndex -= 1;
1073     }
1074   }
1075
1076   std::list<ModelGeomAlgo_Shape::SubshapeOfResult> anAppropriate;
1077
1078   // collect features from PartSet and the current part
1079   SessionPtr aSession = ModelAPI_Session::get();
1080   std::list<FeaturePtr> aFeatures = aSession->moduleDocument()->allFeatures();
1081   if (aSession->moduleDocument() != owner()->document()) {
1082     std::list<FeaturePtr> aPartFeatures = owner()->document()->allFeatures();
1083     aFeatures.insert(aFeatures.end(), aPartFeatures.begin(), aPartFeatures.end());
1084   }
1085   // Process results of all features from the last to the first
1086   // to find appropriate sub-shape
1087   for (std::list<FeaturePtr>::const_reverse_iterator anIt = aFeatures.rbegin();
1088        anIt != aFeatures.rend(); ++anIt) {
1089     // selection cannot be linked to the parent features
1090     if (aParents.find(*anIt) != aParents.end())
1091       continue;
1092     // check the feature is a part of composite feature (like sketch elements),
1093     // then do not process it, it will be processed in scope of composite feature
1094     bool isSubOfComposite = false;
1095     const std::set<AttributePtr>& aRefs = (*anIt)->data()->refsToMe();
1096     for (std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
1097          aRefIt != aRefs.end() && !isSubOfComposite; ++aRefIt) {
1098       FeaturePtr aFeature = ModelAPI_Feature::feature((*aRefIt)->owner());
1099       CompositeFeaturePtr aCompFeature =
1100           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
1101       isSubOfComposite = aCompFeature && aCompFeature->isSub(*anIt);
1102     }
1103     if (isSubOfComposite)
1104       continue;
1105
1106     // process results of the current feature to find appropriate sub-shape
1107     if (ModelGeomAlgo_Shape::findSubshapeByPoint(*anIt, thePoint, aType, anAppropriate)) {
1108       std::list<ModelGeomAlgo_Shape::SubshapeOfResult>::iterator anApIt = anAppropriate.begin();
1109       for (; aSelectionIndex > 0 && anApIt != anAppropriate.end(); --aSelectionIndex)
1110         ++anApIt; // skip this shape, because one of the previous is selected
1111
1112       if (anApIt != anAppropriate.end()) {
1113         if (anApIt->myCenterType == (int)ModelAPI_AttributeSelection::NOT_CENTER)
1114           setValue(anApIt->myResult, anApIt->mySubshape);
1115         else
1116           setValueCenter(anApIt->myResult, anApIt->mySubshape->edge(),
1117                          (ModelAPI_AttributeSelection::CenterType)anApIt->myCenterType);
1118         return;
1119       }
1120     }
1121   }
1122
1123   TDF_Label aSelLab = selectionLabel();
1124   setInvalidIfFalse(aSelLab, false);
1125   reset();
1126 }
1127
1128 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1129   const std::string& theContextName, const int theIndex)
1130 {
1131   // selection of context by name
1132   //std::string aNamingContextName = theContextName + "/";
1133   //selectSubShape(theType, aNamingContextName);
1134   std::shared_ptr<Model_Document> aDoc =
1135     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1136   if (aDoc.get()) {
1137     bool aUnique = true;
1138     std::string aContextName = theContextName;
1139     std::string anEmptySub = "";
1140     ResultPtr aContext = aDoc->findByName(aContextName, anEmptySub, aUnique);
1141     //ResultPtr aContext = context();
1142     if (aContext.get()) {
1143       GeomShapePtr aContShape = aContext->shape();
1144       if (aContShape.get()) {
1145         GeomAlgoAPI_NExplode aNExp(aContShape, GeomAPI_Shape::shapeTypeByStr(theType));
1146         GeomShapePtr aValue = aNExp.shape(theIndex);
1147         if (aValue.get())
1148           setValue(aContext, aValue);
1149       }
1150     }
1151   }
1152 }
1153
1154 int Model_AttributeSelection::Id()
1155 {
1156   int anID = 0;
1157   std::shared_ptr<GeomAPI_Shape> aSelection = value();
1158   ResultPtr aContextRes = context();
1159   // support for compsolids:
1160   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1161     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1162   }
1163   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1164
1165
1166   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1167   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1168   // searching for the latest main shape
1169   if (aSelection && !aSelection->isNull() && aContext && !aContext->isNull())
1170   {
1171     std::shared_ptr<Model_Document> aDoc =
1172       std::dynamic_pointer_cast<Model_Document>(context()->document());
1173     if (aDoc.get()) {
1174       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1175       if (!aNS.IsNull()) {
1176         aMainShape = TNaming_Tool::CurrentShape(aNS);
1177       }
1178     }
1179
1180     TopTools_IndexedMapOfShape aSubShapesMap;
1181     TopExp::MapShapes(aMainShape, aSubShapesMap);
1182     anID = aSubShapesMap.FindIndex(aSubShape);
1183   }
1184   return anID;
1185 }
1186
1187 void Model_AttributeSelection::setId(int theID)
1188 {
1189   std::shared_ptr<GeomAPI_Shape> aSelection;
1190
1191   ResultPtr aContextRes = context();
1192   // support for compsolids:
1193   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1194     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1195   }
1196   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1197
1198   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1199   // searching for the latest main shape
1200   if (theID > 0 && aContext && !aContext->isNull())
1201   {
1202     std::shared_ptr<Model_Document> aDoc =
1203       std::dynamic_pointer_cast<Model_Document>(aContextRes->document());
1204     if (aDoc.get()) {
1205       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1206       if (!aNS.IsNull()) {
1207         aMainShape = TNaming_Tool::CurrentShape(aNS);
1208       }
1209     }
1210
1211     TopTools_IndexedMapOfShape aSubShapesMap;
1212     TopExp::MapShapes(aMainShape, aSubShapesMap);
1213     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1214
1215     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1216     aResult->setImpl(new TopoDS_Shape(aSelShape));
1217
1218     aSelection = aResult;
1219   }
1220
1221   setValue(aContextRes, aSelection);
1222 }
1223
1224 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1225 {
1226   std::string aResult;
1227   if (owner()->document() != theContext->document()) {
1228     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1229       aResult = theContext->document()->kind() + "/";
1230     } else {
1231       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1232         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1233       if (aDocRes.get()) {
1234         aResult = aDocRes->data()->name() + "/";
1235       }
1236     }
1237   }
1238   aResult += theContext->data()->name();
1239   return aResult;
1240 }
1241
1242 void Model_AttributeSelection::computeValues(
1243   ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
1244   TopTools_ListOfShape& theShapes)
1245 {
1246   bool aWasWholeContext = theValShape.IsNull();
1247   if (aWasWholeContext) {
1248     //theShapes.Append(theValShape);
1249     //return;
1250     theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
1251   }
1252   //TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
1253   TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
1254   //if (anOldContShape.IsSame(theValShape)) { // full context shape substituted by new full context
1255     //theShapes.Append(aNewContShape);
1256     //return;
1257   //}
1258   // if a new value is unchanged in the new context, do nothing: value is correct
1259   TopExp_Explorer aSubExp(aNewContShape, theValShape.ShapeType());
1260   for(; aSubExp.More(); aSubExp.Next()) {
1261     if (aSubExp.Current().IsSame(theValShape)) {
1262       theShapes.Append(theValShape);
1263       return;
1264     }
1265   }
1266   // if new context becomes compsolid, the resulting sub may be in sub-solids
1267   std::list<ResultPtr> aNewToIterate;
1268   aNewToIterate.push_back(theNewContext);
1269   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theNewContext);
1270   if (aComp.get()) {
1271     std::list<ResultPtr> allNewContextSubs;
1272     ModelAPI_Tools::allSubs(aComp, allNewContextSubs);
1273     std::list<ResultPtr>::iterator aSub = allNewContextSubs.begin();
1274     for(; aSub != allNewContextSubs.end(); aSub++) {
1275       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aSub);
1276       if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1277         aNewToIterate.push_back(aBody);
1278     }
1279   }
1280
1281   // first iteration: searching for the whole shape appearance (like face of the box)
1282   // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
1283   int aToFindPart = 0;
1284   TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
1285   TopTools_MapOfShape anOlds; // to know how many olds produced new containers
1286   for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
1287     std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
1288     for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
1289       std::shared_ptr<Model_Data> aNewData =
1290         std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
1291       TDF_Label aNewLab = aNewData->label();
1292       // searching for produced sub-shape fully on some label
1293       TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID(), Standard_True);
1294       for(; aNSIter.More(); aNSIter.Next()) {
1295         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1296         for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
1297           if (aToFindPart == 0) { // search shape is fully inside
1298             if (aPairIter.OldShape().IsSame(theValShape)) {
1299               if (aPairIter.NewShape().IsNull()) {// value was removed
1300                 theShapes.Clear();
1301                 return;
1302               }
1303               theShapes.Append(aPairIter.NewShape());
1304             }
1305           } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
1306             TopExp_Explorer anExp(aPairIter.OldShape(), theValShape.ShapeType());
1307             for(; anExp.More(); anExp.Next()) {
1308               if (anExp.Current().IsSame(theValShape)) { // found a new container
1309                 if (aPairIter.NewShape().IsNull()) {// value was removed
1310                   theShapes.Clear();
1311                   return;
1312                 }
1313                 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
1314                 anOlds.Add(aPairIter.OldShape());
1315                 break;
1316               }
1317             }
1318           }
1319         }
1320       }
1321     }
1322   }
1323   if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
1324     // map of sub-shapes -> number of occurences of these shapes in containers
1325     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
1326     TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
1327     for(; aContIter.More(); aContIter.Next()) {
1328       TopExp_Explorer aSubExp(aContIter.Key(), theValShape.ShapeType());
1329       for(; aSubExp.More(); aSubExp.Next()) {
1330         if (!aSubs.IsBound(aSubExp.Current())) {
1331           aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
1332         }
1333         // store old to know how many olds produced this shape
1334         aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
1335       }
1336     }
1337     // if sub is appeared same times in containers as the number of old shapes that contain it
1338     int aCountInOld = anOlds.Size();
1339     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
1340       aSubsIter(aSubs);
1341     for(; aSubsIter.More(); aSubsIter.Next()) {
1342       if (aSubsIter.Value().Size() == aCountInOld) {
1343         theShapes.Append(aSubsIter.Key());
1344       }
1345     }
1346   }
1347   if (theShapes.IsEmpty()) { // nothing was changed
1348     theShapes.Append(aWasWholeContext ? TopoDS_Shape() : theValShape);
1349   }
1350 }
1351
1352 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
1353   const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
1354   TDF_Label theAccessLabel,
1355   std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
1356 {
1357   std::set<ResultPtr> aResults; // to avoid duplicates, new context, null if deleted
1358   TopTools_ListOfShape aResContShapes;
1359   // iterate context and shape, but also if it is sub-shape of main shape, check also it
1360   TopTools_ListOfShape aContextList;
1361   aContextList.Append(theContShape);
1362   if (theContext.get()) {
1363     ResultPtr aComposite = ModelAPI_Tools::bodyOwner(theContext);
1364     if (aComposite.get() && aComposite->shape().get() && !aComposite->shape()->isNull())
1365       aContextList.Append(aComposite->shape()->impl<TopoDS_Shape>());
1366   }
1367   for(TopTools_ListOfShape::Iterator aContIter(aContextList); aContIter.More(); aContIter.Next()) {
1368     TNaming_SameShapeIterator aModifIter(aContIter.ChangeValue(), theAccessLabel);
1369     for(; aModifIter.More(); aModifIter.Next()) {
1370       TDF_Label anObjLab = aModifIter.Label().Father();
1371       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1372         (theDoc->objects()->object(anObjLab));
1373       if (!aModifierObj.get()) {
1374         // #2241: shape may be sub-element of new object, not main (shell created from faces)
1375         if (!anObjLab.IsRoot())
1376           aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1377           (theDoc->objects()->object(anObjLab.Father()));
1378         if (!aModifierObj.get())
1379           continue;
1380       }
1381       FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
1382       if (!aModifierFeat.get())
1383         continue;
1384       FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1385       if (aModifierFeat == aThisFeature || theDoc->objects()->isLater(aModifierFeat, aThisFeature))
1386         continue; // the modifier feature is later than this, so, should not be used
1387       FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
1388       if (aCurrentModifierFeat == aModifierFeat ||
1389         theDoc->objects()->isLater(aCurrentModifierFeat, aModifierFeat))
1390         continue; // the current modifier is later than the found, so, useless
1391       Handle(TNaming_NamedShape) aNewNS;
1392       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1393       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1394         aResults.insert(aModifierObj);
1395         //TNaming_Iterator aPairIter(aNewNS);
1396         //aResContShapes.Append(aPairIter.NewShape());
1397         aResContShapes.Append(aModifierObj->shape()->impl<TopoDS_Shape>());
1398       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
1399         aResults.insert(ResultPtr());
1400       } else { // not-precessed modification => don't support it
1401         continue;
1402       }
1403     }
1404   }
1405   if (aResults.empty())
1406     return false; // no modifications found, must stay the same
1407   // iterate all results to find futher modifications
1408   std::set<ResultPtr>::iterator aResIter = aResults.begin();
1409   for(; aResIter != aResults.end(); aResIter++) {
1410     if (aResIter->get() != NULL) {
1411       // compute new values by two contextes: the old and the new
1412       TopTools_ListOfShape aValShapes;
1413       computeValues(theContext, *aResIter, theValShape, aValShapes);
1414
1415       TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
1416       for(; aNewVal.More(); aNewVal.Next()) {
1417         std::list<ResultPtr> aNewRes;
1418         TopTools_ListOfShape aNewUpdatedVal;
1419         TopoDS_Shape aNewValSh = aNewVal.Value();
1420         TopoDS_Shape aNewContShape = (*aResIter)->shape()->impl<TopoDS_Shape>();
1421         if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
1422           aNewValSh.Nullify();
1423         if (searchNewContext(theDoc, aNewContShape, *aResIter, aNewValSh,
1424                              theAccessLabel, aNewRes, aNewUpdatedVal))
1425         {
1426           // appeand new results instead of the current ones
1427           std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1428           TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1429           for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1430             theResults.push_back(*aNewIter);
1431             theValShapes.Append(aNewUpdVal.Value());
1432           }
1433         } else { // the current result is good
1434           theResults.push_back(*aResIter);
1435           theValShapes.Append(aNewValSh);
1436         }
1437       }
1438     }
1439   }
1440   return true; // theResults must be empty: everything is deleted
1441 }
1442
1443 void Model_AttributeSelection::updateInHistory()
1444 {
1445   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1446   // only bodies and parts may be modified later in the history, don't do anything otherwise
1447   if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
1448       aContext->groupName() != ModelAPI_ResultPart::group()))
1449     return;
1450   std::shared_ptr<Model_Document> aDoc =
1451     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1452   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1453   if (!aContData.get() || !aContData->isValid())
1454     return;
1455   TDF_Label aContLab = aContData->label(); // named shape where the selected context is located
1456   Handle(TNaming_NamedShape) aContNS;
1457   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
1458     bool aFoundNewContext = true;
1459     ResultPtr aNewContext = aContext;
1460     while(aFoundNewContext) {
1461       aFoundNewContext = false;
1462       // parts have no shape in result, so, trace references using the Part info
1463       if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
1464         ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
1465         if (aPartContext.get()) { // searching for the up to date references to the referenced cont
1466           const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
1467           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1468           for(; aRef != aRefs.end(); aRef++) {
1469             // to avoid detection of part changes by local selection only
1470             AttributeSelectionPtr aSel =
1471               std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1472             if (aSel.get() && !aSel->value()->isSame(aSel->context()->shape()))
1473               continue;
1474
1475             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1476             if (aRefFeat.get() && aRefFeat != owner()) {
1477               FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1478               if (aDoc->objects()->isLater(aThisFeature, aRefFeat)) { // found better feature
1479                 aFoundNewContext = true;
1480                 aNewContext = aRefFeat->firstResult();
1481               }
1482             }
1483           }
1484         }
1485       }
1486     }
1487     if (aNewContext != aContext) {
1488       setValue(aNewContext, value());
1489     }
1490     return;
1491   }
1492   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1493   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1494   // iterate the context shape modifications in order to find a feature that is upper in history
1495   // that this one and is really modifies the referenced result to refer to it
1496   ResultPtr aModifierResFound;
1497   TNaming_Iterator aPairIter(aContNS);
1498   if (!aPairIter.More())
1499     return;
1500   TopoDS_Shape aNewCShape = aPairIter.NewShape();
1501   bool anIterate = true;
1502   // trying to update also the sub-shape selected
1503   GeomShapePtr aSubShape = value();
1504   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1505     aSubShape.reset();
1506   TopoDS_Shape aValShape;
1507   if (aSubShape.get()) {
1508     aValShape = aSubShape->impl<TopoDS_Shape>();
1509   }
1510
1511   std::list<ResultPtr> aNewContexts;
1512   TopTools_ListOfShape aValShapes;
1513   if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1514   {
1515     // update scope to reset to a new one
1516     myScope.Clear();
1517
1518     std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1519     TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1520     if (aNewCont == aNewContexts.end()) { // all results were deleted
1521       ResultPtr anEmptyContext;
1522       std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1523       setValue(anEmptyContext, anEmptyShape); // nullify the selection
1524       return;
1525     }
1526
1527     GeomShapePtr aValueShape;
1528     if (!aNewValues.Value().IsNull()) {
1529       aValueShape = std::make_shared<GeomAPI_Shape>();
1530       aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1531     }
1532     setValue(*aNewCont, aValueShape);
1533     // if there are more than one result, put them by "append" into "parent" list
1534     if (myParent) {
1535       for(aNewCont++, aNewValues.Next(); aNewCont != aNewContexts.end();
1536           aNewCont++, aNewValues.Next()) {
1537         GeomShapePtr aValueShape;
1538         if (!aNewValues.Value().IsNull()) {
1539           aValueShape = std::make_shared<GeomAPI_Shape>();
1540           aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1541         }
1542
1543         // Check that list has the same type of shape selection before adding.
1544         GeomAPI_Shape::ShapeType aListShapeType = GeomAPI_Shape::SHAPE;
1545         if (myParent->selectionType() == "VERTEX") aListShapeType = GeomAPI_Shape::VERTEX;
1546         else if (myParent->selectionType() == "EDGE") aListShapeType = GeomAPI_Shape::EDGE;
1547         else if (myParent->selectionType() == "FACE") aListShapeType = GeomAPI_Shape::FACE;
1548
1549         GeomAPI_Shape::ShapeType aShapeShapeType = GeomAPI_Shape::SHAPE;
1550         if (aValueShape.get()) {
1551           aShapeShapeType = aValueShape->shapeType();
1552         } else {
1553           (*aNewCont)->shape()->shapeType();
1554         }
1555
1556         if (aListShapeType != GeomAPI_Shape::SHAPE && aListShapeType != aShapeShapeType) {
1557           continue;
1558         }
1559
1560         myParent->append(*aNewCont, aValueShape);
1561       }
1562     }
1563   }
1564 }
1565
1566 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1567 {
1568   myParent = theParent;
1569 }
1570
1571 bool Model_AttributeSelection::isWeakNaming()
1572 {
1573   return selectionLabel().IsAttribute(kWEAK_NAMING);
1574 }
1575
1576 std::string Model_AttributeSelection::contextName(const TDF_Label theSelectionLab)
1577 {
1578   DocumentPtr aMyDoc = owner()->document();
1579   std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(aMyDoc);
1580   FeaturePtr aFeatureOwner = aDoc->featureByLab(theSelectionLab);
1581   if (aFeatureOwner.get()) {
1582     // if it is sub-element of the sketch, the context name is the name of the sketch
1583     // searching also for result - real context
1584     ResultPtr aResult;
1585     FeaturePtr aComposite = ModelAPI_Tools::compositeOwner(aFeatureOwner);
1586     if (aComposite.get() && aComposite->results().size() == 1 &&
1587         aComposite->firstResult()->groupName() == ModelAPI_ResultConstruction::group()) {
1588       aFeatureOwner = aComposite;
1589       aResult = aFeatureOwner->firstResult();
1590     } else {
1591       aResult = aDoc->resultByLab(theSelectionLab);
1592     }
1593     if (aResult.get()) {
1594       // this is to avoid duplicated names of results problem
1595       std::string aContextName = aResult->data()->name();
1596       // myLab corresponds to the current time
1597       TDF_Label aCurrentLab = selectionLabel();
1598       while(aCurrentLab.Depth() > 3)
1599         aCurrentLab = aCurrentLab.Father();
1600
1601       int aNumInHistoryNames =
1602         aDoc->numberOfNameInHistory(aResult, aCurrentLab);
1603       while(aNumInHistoryNames > 1) { // add "_" before name the needed number of times
1604         aContextName = "_" + aContextName;
1605         aNumInHistoryNames--;
1606       }
1607       return aContextName;
1608     }
1609   }
1610   return ""; // invalid case
1611 }
1612
1613 /// This method restores by the context and value name the context label and
1614 /// sub-label where the value is. Returns true if it is valid.
1615 bool Model_AttributeSelection::restoreContext(std::string theName,
1616   TDF_Label& theContext, TDF_Label& theValue)
1617 {
1618   static const GeomShapePtr anEmptyShape; // to store context only
1619   std::string aName = theName;
1620   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1621     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1622
1623   // remove the sub-value part if exists
1624   std::string aSubShapeName = aName;
1625   std::string::size_type n = aName.find('/');
1626   if (n != std::string::npos) {
1627     aName = aName.substr(0, n);
1628   }
1629
1630   if (aName.empty()) return false;
1631   bool anUniqueContext = false;
1632   ResultPtr aCont = aDoc->findByName(aName, aSubShapeName, anUniqueContext);
1633   if (!aCont.get() || !aCont->shape().get() || aCont->shape()->isNull())
1634     return false;
1635
1636   // searching the sub-shape
1637   static const ResultPtr anEmpty;
1638   theValue = aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
1639
1640   // sketch sub-component shape and name is located in separated feature label, try the sub-name
1641   if (theValue.IsNull() && aCont->groupName() == ModelAPI_ResultConstruction::group()) {
1642     std::string::size_type aSlash = aSubShapeName.rfind('/');
1643     if (aSlash != std::string::npos) {
1644       std::string aCompName = aSubShapeName.substr(aSlash + 1);
1645       CompositeFeaturePtr aComposite =
1646         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aCont));
1647       if (aComposite.get() && aComposite->numberOfSubs()) {
1648         const int aSubNum = aComposite->numberOfSubs();
1649         for (int a = 0; a < aSubNum; a++) {
1650           FeaturePtr aSub = aComposite->subFeature(a);
1651           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
1652           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
1653           for (; aRes != aResults.cend(); aRes++) {
1654             if ((*aRes)->data()->name() == aCompName) {
1655               theValue = std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->shapeLab();
1656             }
1657           }
1658         }
1659       }
1660     }
1661   }
1662
1663   /* to find the latest lower result that keeps given shape
1664   bool aFindNewContext = true;
1665   while(aFindNewContext && aCont.get()) {
1666     aFindNewContext = false;
1667     // try to find the last context to find the up to date shape
1668     TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
1669     Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
1670     if (!aNS.IsNull()) {
1671       aNS = TNaming_Tool::CurrentNamedShape(aNS);
1672       if (!aNS.IsNull() && isOlderThanMe(aNS->Label())) { // scope check is for 2228
1673         TDF_Label aLab = aNS->Label();
1674         if (aLab.Depth() % 2 == 0)
1675           aLab = aLab.Father();
1676         ObjectPtr anObj = aDoc->objects()->object(aLab);
1677         while (!anObj.get() && aLab.Depth() > 5) {
1678           aLab = aLab.Father().Father();
1679           anObj = aDoc->objects()->object(aLab);
1680         }
1681
1682         if (anObj.get()) {
1683           ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1684           if (aRes) {
1685             aCont = aRes;
1686             aFindNewContext = true;
1687           }
1688         }
1689       }
1690     } else if (aCont->groupName() == ModelAPI_ResultBody::group()) {
1691       // try to search newer context by the concealment references
1692       // take references to all results: root one, any sub
1693       std::list<ResultPtr> allRes;
1694       ResultPtr aCompContext;
1695       if (aCont->groupName() == ModelAPI_ResultBody::group()) {
1696         ResultBodyPtr aCompBody = ModelAPI_Tools::bodyOwner(aCont, true);
1697         if (aCompBody.get()) {
1698           ModelAPI_Tools::allSubs(aCompBody, allRes);
1699           allRes.push_back(aCompBody);
1700           aCompContext = aCompBody;
1701         }
1702       }
1703       if (allRes.empty())
1704         allRes.push_back(aCont);
1705
1706       for(std::list<ResultPtr>::iterator aSub = allRes.begin(); aSub != allRes.end(); aSub++) {
1707         ResultPtr aResCont = *aSub;
1708         ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResCont);
1709         if (aResBody.get() && aResBody->numberOfSubs() > 0 && aResBody != aCompContext)
1710           continue; // only lower and higher level subs are counted
1711         const std::set<AttributePtr>& aRefs = aResCont->data()->refsToMe();
1712         std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1713         for(; !aFindNewContext && aRef != aRefs.end(); aRef++) {
1714           if (!aRef->get() || !(*aRef)->owner().get())
1715             continue;
1716           // concealed attribute only
1717           FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1718           if (!ModelAPI_Session::get()->validators()->isConcealed(
1719             aRefFeat->getKind(), (*aRef)->id()))
1720             continue;
1721           // search the feature result that contains sub-shape selected
1722           std::list<std::shared_ptr<ModelAPI_Result> > aResults;
1723
1724           // take all sub-results or one result
1725           std::list<ResultPtr> aRefFeatResults;
1726           ModelAPI_Tools::allResults(aRefFeat, aRefFeatResults);
1727           std::list<ResultPtr>::iterator aRefResIter = aRefFeatResults.begin();
1728           for(; aRefResIter != aRefFeatResults.end(); aRefResIter++) {
1729             ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRefResIter);
1730             if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1731               aResults.push_back(aBody);
1732           }
1733           std::list<std::shared_ptr<ModelAPI_Result> >::iterator aResIter = aResults.begin();
1734           for(; aResIter != aResults.end(); aResIter++) {
1735             if (!aResIter->get() || !(*aResIter)->data()->isValid() || (*aResIter)->isDisabled())
1736               continue;
1737             GeomShapePtr aShape = (*aResIter)->shape();
1738             GeomShapePtr aSelectedShape =
1739               aShapeToBeSelected.get() ? aShapeToBeSelected : aCont->shape();
1740             if (aShape.get() && aShape->isSubShape(aSelectedShape, false)) {
1741               aCont = *aResIter; // found new context (produced from this) with same subshape
1742               aFindNewContext = true; // continue searching futher
1743               break;
1744             }
1745           }
1746         }
1747       }
1748     }
1749   }
1750   // if compsolid is context, try to take sub-solid as context: like in GUI and scripts
1751   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aCont);
1752   if (aComp && aComp->numberOfSubs()) {
1753     std::list<ResultPtr> allSubs;
1754     ModelAPI_Tools::allSubs(aComp, allSubs);
1755     std::list<ResultPtr>::iterator aS = allSubs.begin();
1756     for (; aS != allSubs.end(); aS++) {
1757       ResultBodyPtr aSub = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aS);
1758       if (aSub && aSub->numberOfSubs() == 0 && aSub->shape().get() &&
1759         aSub->shape()->isSubShape(aShapeToBeSelected)) {
1760         aCont = aSub;
1761         break;
1762       }
1763     }
1764   }
1765   */
1766   if (aCont.get()) {
1767     theContext = std::dynamic_pointer_cast<Model_Data>(aCont->data())->label();
1768   }
1769   return true;
1770 }
1771
1772 bool Model_AttributeSelection::isLater(
1773   const TDF_Label theResult1, const TDF_Label theResult2) const
1774 {
1775   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1776     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1777   FeaturePtr aFeat1 = aDoc->featureByLab(theResult1);
1778   if (!aFeat1.get())
1779     return false;
1780   FeaturePtr aFeat2 = aDoc->featureByLab(theResult2);
1781   if (!aFeat2.get())
1782     return false;
1783   return aDoc->isLater(aFeat1, aFeat2);
1784 }