]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
Fix for the issue #19932 : Fillet fails in python with all in features Fuse inputs
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // Copyright (C) 2014-2020  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 email : webmaster.salome@opencascade.com
18 //
19
20 #include "Model_AttributeSelection.h"
21 #include "Model_Application.h"
22 #include "Model_Events.h"
23 #include "Model_Data.h"
24 #include "Model_Document.h"
25 #include <Model_Objects.h>
26 #include <Model_AttributeSelectionList.h>
27 #include <Model_ResultConstruction.h>
28 #include <ModelAPI_Feature.h>
29 #include <ModelAPI_ResultBody.h>
30 #include <ModelAPI_ResultBody.h>
31 #include <ModelAPI_ResultConstruction.h>
32 #include <ModelAPI_ResultGroup.h>
33 #include <ModelAPI_ResultPart.h>
34 #include <ModelAPI_CompositeFeature.h>
35 #include <ModelAPI_Tools.h>
36 #include <ModelAPI_Session.h>
37 #include <ModelAPI_Validator.h>
38 #include <ModelGeomAlgo_Shape.h>
39 #include <Events_InfoMessage.h>
40 #include <GeomAPI_Edge.h>
41 #include <GeomAPI_Pnt.h>
42 #include <GeomAPI_ShapeIterator.h>
43 #include <GeomAPI_Vertex.h>
44 #include <GeomAPI_ShapeExplorer.h>
45 #include <GeomAlgoAPI_CompoundBuilder.h>
46 #include <GeomAlgoAPI_NExplode.h>
47 #include <Selector_Selector.h>
48
49 #include <Locale_Convert.h>
50
51 #include <TNaming_NamedShape.hxx>
52 #include <TNaming_Tool.hxx>
53 #include <TNaming_Builder.hxx>
54 #include <TNaming_SameShapeIterator.hxx>
55 #include <TNaming_NewShapeIterator.hxx>
56 #include <TNaming_Iterator.hxx>
57 #include <TDataStd_Integer.hxx>
58 #include <TDataStd_UAttribute.hxx>
59 #include <TDataStd_Name.hxx>
60 #include <TopTools_ListOfShape.hxx>
61 #include <TopTools_DataMapOfShapeShape.hxx>
62 #include <TopTools_MapOfShape.hxx>
63 #include <TopExp_Explorer.hxx>
64 #include <BRep_Tool.hxx>
65 #include <TopoDS.hxx>
66 #include <TopoDS_Edge.hxx>
67 #include <TopExp.hxx>
68 #include <TDF_ChildIterator.hxx>
69 #include <TDF_ChildIDIterator.hxx>
70 #include <TopoDS_Iterator.hxx>
71 #include <TDF_ChildIDIterator.hxx>
72 #include <Geom_Circle.hxx>
73 #include <Geom_Ellipse.hxx>
74 #include <Geom_TrimmedCurve.hxx>
75 #include <BRep_Builder.hxx>
76
77 //#define DEB_NAMING 1
78 #ifdef DEB_NAMING
79 #include <BRepTools.hxx>
80 #endif
81 /// added to the index in the packed map to signalize that the vertex of edge is selected
82 /// (multiplied by the index of the edge)
83 static const int kSTART_VERTEX_DELTA = 1000000;
84 // identifier that there is simple reference: selection equals to context
85 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
86 // reference to Part sub-object
87 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
88 // selection is invalid after recomputation
89 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
90
91 // identifier of the selection of the center of circle on edge
92 Standard_GUID kCIRCLE_CENTER("d0d0e0f1-217a-4b95-8fbb-0c4132f23718");
93 // identifier of the selection of the first focus point of ellipse on edge
94 Standard_GUID kELLIPSE_CENTER1("f70df04c-3168-4dc9-87a4-f1f840c1275d");
95 // identifier of the selection of the second focus point of ellipse on edge
96 Standard_GUID kELLIPSE_CENTER2("1395ae73-8e02-4cf8-b204-06ff35873a32");
97
98 // prefix for the whole feature context identification
99 const static std::wstring kWHOLE_FEATURE = L"all-in-";
100
101 // on this label is stored:
102 // TNaming_NamedShape - selected shape
103 // TNaming_Naming - topological selection information (for the body)
104 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
105 // TDataStd_Integer - type of the selected shape (for construction)
106 // TDF_Reference - from ReferenceAttribute, the context
107 bool Model_AttributeSelection::setValue(const ObjectPtr& theContext,
108   const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
109 {
110   if (theTemporarily) {
111     // just keep the stored without DF update
112     myTmpContext = 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 not 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
143   bool isDegeneratedEdge = false;
144   // do not use the degenerated edge as a shape, a null context and shape is used in the case
145   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
146     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
147     if (aSubShape.ShapeType() == TopAbs_EDGE)
148       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
149   }
150   if (!theContext.get() || isDegeneratedEdge) {
151     aSelLab.ForgetAllAttributes(true);
152     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
153     if (aToUnblock)
154       owner()->data()->blockSendAttributeUpdated(false);
155     return false;
156   }
157   bool isSelectBody = theContext->groupName() == ModelAPI_ResultBody::group();
158   if (!isSelectBody) {
159     ResultConstructionPtr aContextConstruction =
160       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
161     isSelectBody = aContextConstruction.get() && !aContextConstruction->isInfinite();
162   }
163   if (isSelectBody) {
164     ResultPtr aContextResult = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
165     GeomShapePtr aContextShape = aContextResult->shape();
166     // do not select the whole shape for body:it is already must be in the data framework
167     // equal and null selected objects mean the same: object is equal to context,
168     if (aContextShape.get() && (aContextShape->isEqual(theSubShape) || !theSubShape.get())) {
169       aSelLab.ForgetAllAttributes(true);
170       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
171     } else {
172       selectBody(aContextResult, theSubShape);
173     }
174   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
175     aSelLab.ForgetAllAttributes(true); // to remove old selection data
176     std::shared_ptr<Model_ResultConstruction> aConstruction =
177       std::dynamic_pointer_cast<Model_ResultConstruction>(theContext);
178     std::shared_ptr<GeomAPI_Shape> aSubShape;
179     if (theSubShape.get() && !aConstruction->shape()->isEqual(theSubShape))
180       aSubShape = theSubShape; // the whole context
181   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
182     aSelLab.ForgetAllAttributes(true);
183     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
184     selectPart(std::dynamic_pointer_cast<ModelAPI_Result>(theContext), theSubShape);
185   } else if (theContext->groupName() == ModelAPI_ResultGroup::group()) {
186     aSelLab.ForgetAllAttributes(true);
187     TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
188   } else { // check the feature context: only construction features of PartSet could be selected
189     FeaturePtr aFeatureContext = std::dynamic_pointer_cast<ModelAPI_Feature>(theContext);
190     if (aFeatureContext.get() && owner()->document() != aFeatureContext->document()) {
191       if (aFeatureContext->results().empty() ||
192           aFeatureContext->firstResult()->groupName() != ModelAPI_ResultConstruction::group()) {
193         aSelLab.ForgetAllAttributes(true);
194         myRef.setValue(ObjectPtr());
195         if (aToUnblock)
196           owner()->data()->blockSendAttributeUpdated(false);
197         return false;
198       }
199     }
200   }
201
202   owner()->data()->sendAttributeUpdated(this);
203
204   if (aToUnblock)
205     owner()->data()->blockSendAttributeUpdated(false);
206
207   return true;
208 }
209
210 void Model_AttributeSelection::setValueCenter(
211     const ObjectPtr& theContext, const std::shared_ptr<GeomAPI_Edge>& theEdge,
212     const CenterType theCenterType, const bool theTemporarily)
213 {
214   bool anUpdated = setValue(theContext, theEdge, theTemporarily);
215   if (theTemporarily) {
216     myTmpCenterType = theCenterType;
217   } else { // store in the data structure
218     TDF_Label aSelLab = selectionLabel();
219     switch(theCenterType) {
220     case CIRCLE_CENTER:
221       if (!anUpdated)
222         anUpdated = !aSelLab.IsAttribute(kCIRCLE_CENTER);
223       TDataStd_UAttribute::Set(aSelLab, kCIRCLE_CENTER);
224       break;
225     case ELLIPSE_FIRST_FOCUS:
226       if (!anUpdated)
227         anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER1);
228       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER1);
229       break;
230     case ELLIPSE_SECOND_FOCUS:
231       if (!anUpdated)
232         anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER2);
233       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER2);
234       break;
235     default: // [to avoid compilation warning]
236       break;
237     }
238     if (anUpdated)
239       owner()->data()->sendAttributeUpdated(this);
240   }
241 }
242
243 void Model_AttributeSelection::selectValue(
244     const std::shared_ptr<ModelAPI_AttributeSelection>& theSource)
245 {
246   CenterType aType;
247   std::shared_ptr<GeomAPI_Shape> aValue =
248     std::dynamic_pointer_cast<Model_AttributeSelection>(theSource)->internalValue(aType);
249   if (!aValue.get() || aType == NOT_CENTER) {
250     setValue(theSource->context(), aValue);
251   } else {
252     std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge);
253     anEdge->setImpl(new TopoDS_Shape(aValue->impl<TopoDS_Shape>()));
254     setValueCenter(theSource->context(), anEdge, aType);
255   }
256 }
257
258 void Model_AttributeSelection::removeTemporaryValues()
259 {
260   if (myTmpContext.get() || myTmpSubShape.get()) {
261     myTmpContext.reset();
262     myTmpSubShape.reset();
263   }
264 }
265
266 // returns the center of the edge: circular or elliptic
267 GeomShapePtr centerByEdge(GeomShapePtr theEdge, ModelAPI_AttributeSelection::CenterType theType)
268 {
269   if (theType != ModelAPI_AttributeSelection::NOT_CENTER && theEdge.get() != NULL) {
270     TopoDS_Shape aShape = theEdge->impl<TopoDS_Shape>();
271     if (!aShape.IsNull() && aShape.ShapeType() == TopAbs_EDGE) {
272       TopoDS_Edge anEdge = TopoDS::Edge(aShape);
273       double aFirst, aLast;
274       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
275       if (!aCurve.IsNull()) {
276         TopoDS_Vertex aVertex;
277         BRep_Builder aBuilder;
278         if (theType == ModelAPI_AttributeSelection::CIRCLE_CENTER) {
279           while(!aCurve.IsNull() && aCurve->DynamicType() == STANDARD_TYPE(Geom_TrimmedCurve))
280             aCurve = Handle(Geom_TrimmedCurve)::DownCast(aCurve)->BasisCurve();
281           Handle(Geom_Circle) aCirc = Handle(Geom_Circle)::DownCast(aCurve);
282           if (!aCirc.IsNull()) {
283             aBuilder.MakeVertex(aVertex, aCirc->Location(), Precision::Confusion());
284           }
285         } else { // ellipse
286           while(!aCurve.IsNull() && aCurve->DynamicType() == STANDARD_TYPE(Geom_TrimmedCurve))
287             aCurve = Handle(Geom_TrimmedCurve)::DownCast(aCurve)->BasisCurve();
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 (!myRef.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     FeaturePtr aFeature =
328       std::dynamic_pointer_cast<ModelAPI_Feature>(myTmpContext);
329     if (aFeature.get()) {
330       // it is just reference to construction.
331       return myTmpSubShape;
332     }
333     return myTmpSubShape.get() ? myTmpSubShape :
334       std::dynamic_pointer_cast<ModelAPI_Result>(myTmpContext)->shape();
335   }
336
337   TDF_Label aSelLab = selectionLabel();
338   if (aSelLab.IsAttribute(kINVALID_SELECTION))
339     return aResult;
340
341   if (aSelLab.IsAttribute(kCIRCLE_CENTER))
342     theType = CIRCLE_CENTER;
343   else if (aSelLab.IsAttribute(kELLIPSE_CENTER1))
344     theType = ELLIPSE_FIRST_FOCUS;
345   else if (aSelLab.IsAttribute(kELLIPSE_CENTER2))
346     theType = ELLIPSE_SECOND_FOCUS;
347
348
349   if (myRef.isInitialized()) {
350     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
351       ResultPtr aContext = context();
352       if (!aContext.get() || aContext->groupName() == ModelAPI_ResultConstruction::group())
353         return aResult; // empty result, for whole construction selection also
354       return aContext->shape();
355     }
356     if (aSelLab.IsAttribute(kPART_REF_ID)) {
357       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
358       if (!aPart.get() || !aPart->isActivated())
359         return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
360       Handle(TDataStd_Integer) anIndex;
361       if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
362         if (anIndex->Get()) { // special selection attribute was created, use it
363           return aPart->selectionValue(anIndex->Get());
364         } else { // face with name is already in the data model, so try to take it by name
365           Handle(TDataStd_Name) aName;
366           if (aSelLab.FindAttribute(TDataStd_Name::GetID(), aName)) {
367             std::wstring aSubShapeName = Locale::Convert::toWString(aName->Get().ToExtString());
368             std::size_t aPartEnd = aSubShapeName.find(L'/');
369             if (aPartEnd != std::wstring::npos && aPartEnd != aSubShapeName.rfind(L'/')) {
370               std::wstring aNameInPart = aSubShapeName.substr(aPartEnd + 1);
371               int anInd;
372               std::string aType; // to reuse already existing selection the type is not needed
373               return aPart->shapeInPart(aNameInPart, aType, anInd);
374             }
375           }
376         }
377       }
378     }
379
380     std::shared_ptr<Model_ResultConstruction> aConstr =
381       std::dynamic_pointer_cast<Model_ResultConstruction>(context());
382     if (aConstr) {
383       if (aConstr->isInfinite())
384         return aResult; // empty result
385     }
386     if (!aConstr.get()) { // for construction context, return empty result as usual even
387       // the whole feature is selected
388       FeaturePtr aFeature = contextFeature();
389       if (aFeature.get()) {
390         std::list<GeomShapePtr> allShapes;
391         std::list<ResultPtr>::const_iterator aRes = aFeature->results().cbegin();
392         for (; aRes != aFeature->results().cend(); aRes++) {
393           if (aRes->get() && !(*aRes)->isDisabled()) {
394             GeomShapePtr aShape = (*aRes)->shape();
395             if (aShape.get() && !aShape->isNull()) {
396               allShapes.push_back(aShape);
397             }
398           }
399         }
400         return GeomAlgoAPI_CompoundBuilder::compound(allShapes);
401       }
402     } else {
403       if (contextFeature().get()) {
404         return aResult; // for the whole sketch feature selected return null => all faces
405       }
406     }
407
408     Handle(TNaming_NamedShape) aSelection;
409     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
410       TopoDS_Shape aSelShape = aSelection->Get();
411       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
412       aResult->setImpl(new TopoDS_Shape(aSelShape));
413     } else if (aConstr) { // simple construction element: just shape of this construction element
414       aResult = aConstr->shape();
415     }
416   }
417   return aResult;
418 }
419
420 bool Model_AttributeSelection::isInvalid()
421 {
422   return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
423 }
424
425 bool Model_AttributeSelection::isInitialized()
426 {
427   if (myRef.isInitialized()) {
428     TDF_Label aSelLab = selectionLabel();
429     // it is just reference to shape, not sub-shape
430     if (aSelLab.IsAttribute(kSIMPLE_REF_ID) || aSelLab.IsAttribute(kPART_REF_ID)) {
431       ResultPtr aContext = context();
432       return aContext.get() != NULL;
433     }
434     Handle(TNaming_NamedShape) aSelection;
435     if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
436       return !aSelection->Get().IsNull();
437     } else { // for simple construction element: just shape of this construction element
438       if (myRef.value().get())
439         return true;
440       // check that this is on open of document, so, results are not initialized yet
441       TDF_Label aRefLab = myRef.myRef->Get();
442       if (aRefLab.IsNull() || !owner().get())
443         return false;
444       std::shared_ptr<Model_Document> aMyDoc =
445         std::dynamic_pointer_cast<Model_Document>(owner()->document());
446       if (!aMyDoc.get())
447         return false;
448       // check at least the feature exists
449       return aMyDoc->featureByLab(aRefLab).get() != NULL;
450     }
451   }
452   return false;
453 }
454
455 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
456 : myRef(theLabel),
457   myIsGeometricalSelection(false)
458 {
459   myIsInitialized = myRef.isInitialized();
460   myParent = NULL;
461 }
462
463 void Model_AttributeSelection::setID(const std::string theID)
464 {
465   myRef.setID(theID);
466   ModelAPI_AttributeSelection::setID(theID);
467   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
468   if (myParent) {
469     // to be able to select as geometrical selection and then - split
470     myIsGeometricalSelection = true; // myParent->isGeometricalSelection();
471   } else {
472     myIsGeometricalSelection =
473       ModelAPI_Session::get()->validators()->isGeometricalSelection(aFeature->getKind(), id());
474   }
475 }
476
477 ResultPtr Model_AttributeSelection::context()
478 {
479   if (!myRef.isInitialized() && !myTmpContext.get() && !myTmpSubShape.get())
480     return ResultPtr();
481
482   if (myTmpContext.get() || myTmpSubShape.get()) {
483     return std::dynamic_pointer_cast<ModelAPI_Result>(myTmpContext);
484   }
485
486   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
487   // for parts there could be same-data result, so take the last enabled
488   if (aResult.get()) {
489     if(aResult->groupName() == ModelAPI_ResultPart::group()) {
490       int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
491       for(int a = aSize - 1; a >= 0; a--) {
492         ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
493         if(aPart.get() && aPart->data() == aResult->data()) {
494           ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
495           FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
496           // check that this result is not this-feature result (it is forbidden to select itself)
497           if(anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
498             return aPartResult;
499           }
500         }
501       }
502     }
503   } else { // if feature - construction is selected, it has only one result, return this result
504     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
505     if (aFeature.get() && aFeature->results().size() == 1 &&
506         aFeature->firstResult()->groupName() == ModelAPI_ResultConstruction::group())
507       return aFeature->firstResult();
508   }
509   return aResult;
510 }
511
512 FeaturePtr Model_AttributeSelection::contextFeature() {
513   if (myTmpContext.get()) {
514     return std::dynamic_pointer_cast<ModelAPI_Feature>(myTmpContext);
515   }
516   return std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
517 }
518 ObjectPtr Model_AttributeSelection::contextObject() {
519   FeaturePtr aRes = contextFeature();
520   if (aRes.get())
521     return aRes;
522   return context();
523 }
524
525
526 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
527 {
528   ModelAPI_AttributeSelection::setObject(theObject);
529   myRef.setObject(theObject);
530 }
531
532 /// Sets the invalid flag if flag is false, or removes it if "true"
533 /// Returns theFlag
534 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
535   if (theFlag) {
536     theLab.ForgetAttribute(kINVALID_SELECTION);
537   } else {
538     TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
539   }
540   return theFlag;
541 }
542
543 void Model_AttributeSelection::split(
544   ResultPtr theContext, TopoDS_Shape theNewShape, TopAbs_ShapeEnum theType)
545 {
546   TopTools_ListOfShape aSubs;
547   for(TopoDS_Iterator anExplorer(theNewShape); anExplorer.More(); anExplorer.Next()) {
548     if (!anExplorer.Value().IsNull() &&
549       anExplorer.Value().ShapeType() == theType) {
550         aSubs.Append(anExplorer.Value());
551     } else { // invalid case; bad result shape, so, impossible to split easily
552       aSubs.Clear();
553       break;
554     }
555   }
556   if (aSubs.Extent() > 1) { // ok to split
557     TopTools_ListIteratorOfListOfShape aSub(aSubs);
558     GeomShapePtr aSubSh(new GeomAPI_Shape);
559     aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
560     setValue(theContext, aSubSh);
561     for(aSub.Next(); aSub.More(); aSub.Next()) {
562       aSubSh.reset(new GeomAPI_Shape);
563       aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
564       myParent->append(theContext, aSubSh);
565     }
566   }
567 }
568
569 bool Model_AttributeSelection::update()
570 {
571   FeaturePtr aContextFeature = contextFeature();
572   if (aContextFeature.get()) {
573     owner()->data()->sendAttributeUpdated(this);  // send updated if "update" called in any way
574     return true;
575   }
576   TDF_Label aSelLab = selectionLabel();
577   ResultPtr aContext = context();
578   if (!aContext.get())
579     return setInvalidIfFalse(aSelLab, false);
580   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
581     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
582   }
583
584   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
585     std::shared_ptr<GeomAPI_Shape> aNoSelection;
586     bool aResult = selectPart(aContext, aNoSelection, true);
587     aResult = setInvalidIfFalse(aSelLab, aResult);
588     if (aResult) {
589       owner()->data()->sendAttributeUpdated(this);
590     }
591     return aResult;
592   }
593
594   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
595     // body: just a named shape, use topological selection mechanism
596     bool aResult = false;
597     TopoDS_Shape anOldShape;
598     Handle(TNaming_NamedShape) aNS;
599     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
600       anOldShape = aNS->Get();
601
602     TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
603     Selector_Selector aSelector(aSelLab, baseDocumentLab());
604     aResult = aSelector.restore(aContextShape);
605     bool aWasInvalid = aSelLab.IsAttribute(kINVALID_SELECTION);
606     setInvalidIfFalse(aSelLab, aResult);
607
608     TopoDS_Shape aNewShape;
609     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
610       aNewShape = aNS->Get();
611
612     // check the selected value is a part of the context
613     if (aResult && !aNewShape.IsNull() && !aContextShape.IsNull() &&
614         !aContextShape.IsSame(aNewShape)) {
615       TopoDS_Shape aNewS = aNewShape;
616       // take only sub-shape of composite for checking
617       if (aNewS.ShapeType() == TopAbs_WIRE || aNewS.ShapeType() == TopAbs_SHELL ||
618         aNewS.ShapeType() == TopAbs_COMPOUND || aNewS.ShapeType() == TopAbs_COMPSOLID) {
619         TopoDS_Iterator anIter(aNewS);
620         if (anIter.More())
621           aNewS = anIter.Value();
622       }
623       bool anIsInside = false;
624       TopExp_Explorer anExp(aContextShape, aNewS.ShapeType());
625       for (; anExp.More() && !anIsInside; anExp.Next()) {
626         if (anExp.Current().IsSame(aNewS))
627           anIsInside = true;
628       }
629       if (!anIsInside) {
630         aResult = false;
631         aNewShape.Nullify();
632         setInvalidIfFalse(aSelLab, aResult);
633       }
634     }
635
636     if (anOldShape.IsNull() || aNewShape.IsNull() || !anOldShape.IsEqual(aNewShape) || aWasInvalid)
637     {
638       // shape type should not be changed: if shape becomes compound of such shapes, then split
639       if (myParent && !anOldShape.IsNull() && !aNewShape.IsNull() &&
640           anOldShape.ShapeType() != aNewShape.ShapeType() &&
641           aNewShape.ShapeType() == TopAbs_COMPOUND) {
642         split(aContext, aNewShape, anOldShape.ShapeType());
643       }
644       // for issue #3076 check that the new value belongs to the new context
645       if (!aNewShape.IsNull() && !aContextShape.IsNull() &&
646           (aNewShape.ShapeType() == TopAbs_VERTEX || aNewShape.ShapeType() == TopAbs_EDGE ||
647            aNewShape.ShapeType() == TopAbs_FACE)) {
648         TopExp_Explorer anExp(aContextShape, aNewShape.ShapeType());
649         for(; anExp.More(); anExp.Next()) {
650           if (anExp.Current().IsSame(aNewShape))
651             break;
652         }
653         aResult = setInvalidIfFalse(aSelLab, anExp.More());
654       }
655       owner()->data()->sendAttributeUpdated(this);  // send updated if shape is changed
656     }
657     return aResult;
658   }
659
660   if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
661     bool aResult = true;
662     std::shared_ptr<Model_ResultConstruction> aConstructionContext =
663       std::dynamic_pointer_cast<Model_ResultConstruction>(aContext);
664     if (!aConstructionContext->isInfinite()) {
665       TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
666       Selector_Selector aSelector(aSelLab, baseDocumentLab());
667       TopoDS_Shape anOldShape = aSelector.value();
668       aResult = aSelector.restore(aContextShape);
669       setInvalidIfFalse(aSelLab, aResult);
670       if (aResult && !anOldShape.IsEqual(aSelector.value()))
671         owner()->data()->sendAttributeUpdated(this);  // send updated if shape is changed
672     } else {
673       owner()->data()->sendAttributeUpdated(this);  // send updated if "update" called in any way
674     }
675     return aResult;
676   }
677   return setInvalidIfFalse(aSelLab, false); // unknown case
678 }
679
680 void Model_AttributeSelection::selectBody(
681   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
682 {
683   // perform the selection
684   TopoDS_Shape aContext;
685
686   ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
687   if (aBody) {
688     aContext = aBody->shape()->impl<TopoDS_Shape>();
689   } else {
690     ResultPtr aResult =
691       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
692     if (aResult) {
693       aContext = aResult->shape()->impl<TopoDS_Shape>();
694     } else {
695       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
696       return;
697     }
698   }
699
700   if (!aContext.IsNull()) {
701     TDF_Label aSelLab = selectionLabel();
702     TopoDS_Shape aNewSub = theSubShape->impl<TopoDS_Shape>();
703
704     bool aSelectorOk = true;
705     Selector_Selector aSelector(aSelLab, baseDocumentLab());
706     try {
707       aSelectorOk = aSelector.select(aContext, aNewSub, myIsGeometricalSelection);
708       if (aSelectorOk) {
709         aSelectorOk = aSelector.store(aContext);
710       }
711     } catch(...) {
712       aSelectorOk = false;
713     }
714     if (aSelectorOk) {
715       TopoDS_Shape aShape = aSelector.value();
716       aSelectorOk = !aShape.IsNull() && aShape.ShapeType() == aNewSub.ShapeType();
717     }
718     setInvalidIfFalse(aSelLab, aSelectorOk);
719   }
720 }
721
722 bool Model_AttributeSelection::selectPart(
723   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
724   const bool theUpdate)
725 {
726   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
727   if (!aPart.get() || !aPart->isActivated())
728     return true; // postponed naming
729   if (theUpdate) {
730     Handle(TDataStd_Integer) anIndex;
731     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
732       // by internal selection
733       if (anIndex->Get() > 0) {
734         // update the selection by index
735         return aPart->updateInPart(anIndex->Get());
736       } else {
737         return true; // nothing to do, referencing just by name
738       }
739     }
740     return true; // nothing to do, referencing just by name
741   }
742   // store the shape (in case part is not loaded it should be useful
743   TopoDS_Shape aShape;
744   std::wstring aName = theContext->data()->name();
745   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
746     aShape = theContext->shape()->impl<TopoDS_Shape>();
747   } else {
748     aShape = theSubShape->impl<TopoDS_Shape>();
749     int anIndex;
750     aName += L"/" + aPart->nameInPart(theSubShape, anIndex);
751     TDataStd_Integer::Set(selectionLabel(), anIndex);
752   }
753   TNaming_Builder aBuilder(selectionLabel());
754   aBuilder.Select(aShape, aShape);
755   // identify by name in the part
756   TDataStd_Name::Set(selectionLabel(), aName.c_str());
757   return !aName.empty();
758 }
759
760 TDF_Label Model_AttributeSelection::selectionLabel()
761 {
762   return myRef.myRef->Label().FindChild(1);
763 }
764
765 /// prefixes of the shape names with centers defined
766 static std::map<ModelAPI_AttributeSelection::CenterType, std::wstring> kCENTERS_PREFIX;
767
768 /// returns the map that contains all possible prefixes of the center-names
769 static std::map<ModelAPI_AttributeSelection::CenterType, std::wstring>& centersMap()
770 {
771   if (kCENTERS_PREFIX.empty()) { // fill map by initial values
772     kCENTERS_PREFIX[ModelAPI_AttributeSelection::CIRCLE_CENTER] = L"__cc";
773     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS] = L"__eff";
774     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_SECOND_FOCUS] = L"__esf";
775   }
776   return kCENTERS_PREFIX;
777 }
778
779 std::wstring Model_AttributeSelection::namingName(const std::wstring& theDefaultName)
780 {
781   std::wstring aName(L"");
782   if(!this->isInitialized())
783     return !theDefaultName.empty() ? theDefaultName : aName;
784
785   // not argument has not parametric name (filters)
786   if (!this->isArgument() || (myParent && !myParent->isArgument())) {
787     GeomShapePtr aShape = value();
788     if (!aShape.get() && context().get())
789       aShape = context()->shape();
790     std::wstring aNotArgName;
791     if (aShape.get()) {
792       aNotArgName = Locale::Convert::toWString(aShape->shapeTypeStr());
793       if (myParent) {
794         std::wostringstream aStream;
795         aStream << "_" << selectionLabel().Father().Tag();
796         aNotArgName += aStream.str();
797       }
798     }
799     return aNotArgName;
800   }
801
802   CenterType aCenterType = NOT_CENTER;
803   std::shared_ptr<GeomAPI_Shape> aSubSh = internalValue(aCenterType);
804
805   FeaturePtr aContFeature = contextFeature();
806   if (aContFeature.get()) {
807     std::wstring aResName;
808     // checking part-owner
809     if (aContFeature->document() != owner()->document())
810         aResName += Locale::Convert::toWString(aContFeature->document()->kind()) + L"/";
811     // selection of a full feature
812     if (aContFeature.get()) {
813       return aResName + kWHOLE_FEATURE + aContFeature->name();
814     }
815     // in case of selection of removed result
816     return L"";
817   }
818
819   ResultPtr aCont = context();
820   if (!aCont.get()) {
821     return L""; // invalid case
822   }
823   TDF_Label aSelLab = selectionLabel();
824   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // whole context, no value
825     return contextName(aCont);
826   }
827
828   // if it is in result of another part
829   if (aCont->groupName() == ModelAPI_ResultPart::group()) {
830     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aCont);
831     int anIndex;
832     std::wstring aResult = aSubSh.get() ?
833       aPart->data()->name() + L"/" + aPart->nameInPart(aSubSh, anIndex)
834       : aPart->data()->name();
835     if (aCenterType != NOT_CENTER)
836       aResult += centersMap()[aCenterType];
837     return aResult;
838   }
839
840   // whole infinitive construction
841   if (aCont->groupName() == ModelAPI_ResultConstruction::group()) {
842     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<Model_ResultConstruction>(aCont);
843     if (aConstr->isInfinite()) {
844       return contextName(aCont);
845     }
846   }
847
848   Selector_Selector aSelector(aSelLab, baseDocumentLab());
849   std::wstring aResult;
850   if (aCont->shape().get() && aSelector.restore(aCont->shape()->impl<TopoDS_Shape>()))
851     aResult = aSelector.name(this);
852   if (aCenterType != NOT_CENTER) {
853     aResult += centersMap()[aCenterType];
854   }
855   return aResult;
856 }
857
858 // returns the center type and modifies the shape name if this name is center-name
859 static ModelAPI_AttributeSelection::CenterType centerTypeByName(std::wstring& theShapeName)
860 {
861   std::map<ModelAPI_AttributeSelection::CenterType, std::wstring>::iterator aPrefixIter =
862     centersMap().begin();
863   for(; aPrefixIter != centersMap().end(); aPrefixIter++) {
864     std::size_t aFound = theShapeName.find(aPrefixIter->second);
865     if (aFound != std::wstring::npos &&
866         aFound == theShapeName.size() - aPrefixIter->second.size()) {
867       theShapeName = theShapeName.substr(0, aFound);
868       return aPrefixIter->first;
869     }
870   }
871   return ModelAPI_AttributeSelection::NOT_CENTER;
872 }
873
874 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
875 void Model_AttributeSelection::selectSubShape(
876   const std::string& theType, const std::wstring& theSubShapeName)
877 {
878   if(theSubShapeName.empty() || theType.empty()) return;
879
880   std::wstring aSubShapeName = theSubShapeName;
881   CenterType aCenterType = theType[0] == 'v' || theType[0] == 'V' ? // only for vertex-type
882     centerTypeByName(aSubShapeName) : NOT_CENTER;
883   std::string aType = aCenterType == NOT_CENTER ? theType : "EDGE"; // search for edge now
884   static const GeomShapePtr anEmptyShape;
885
886   // first iteration is selection by name without center prefix, second - in case of problem,
887   // try with initial name
888   for(int aUseCenter = 1; aUseCenter >= 0; aUseCenter--)  {
889     if (aUseCenter == 0 && aCenterType != NOT_CENTER) {
890       aSubShapeName = theSubShapeName;
891       aCenterType = NOT_CENTER;
892       aType = theType;
893     } else if (aUseCenter != 1) continue;
894     TopAbs_ShapeEnum aShapeType =  TopAbs_ShapeEnum(GeomAPI_Shape::shapeTypeByStr(aType));
895
896     std::shared_ptr<Model_Document> aDoc =
897       std::dynamic_pointer_cast<Model_Document>(owner()->document());
898     // check this is Part-name: 2 delimiters in the name
899     std::size_t aPartEnd = aSubShapeName.find(L'/');
900     if (aPartEnd != std::wstring::npos) {
901       std::wstring aPartName = aSubShapeName.substr(0, aPartEnd);
902       DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
903       if (aPartName == Locale::Convert::toWString(aRootDoc->kind())) {
904         aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
905         aSubShapeName = aSubShapeName.substr(aPartEnd + 1);
906       }
907       else {
908         ObjectPtr aFound =
909           owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
910         if (aFound.get()) { // found such part, so asking it for the name
911           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
912           std::wstring aNameInPart = aSubShapeName.substr(aPartEnd + 1);
913           if (aNameInPart.empty()) { // whole part
914             setValue(aPart, anEmptyShape);
915             return;
916           }
917           int anIndex;
918           std::shared_ptr<GeomAPI_Shape> aSelected =
919             aPart->shapeInPart(aNameInPart, aType, anIndex);
920           if (aSelected.get()) {
921             if (aCenterType != NOT_CENTER) {
922               if (!aSelected->isEdge())
923                 continue;
924               std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aSelected));
925               setValueCenter(aPart, aSelectedEdge, aCenterType);
926             }
927             else
928               setValue(aPart, aSelected);
929             TDataStd_Integer::Set(selectionLabel(), anIndex);
930             return;
931           }
932         } else { // for the ImportResult feature Objects widget this may be a result in other part
933        // result may be hidden (like, tranlsatiomn of part) in PartSet, so iterate Part-features
934           int aNum = aRootDoc->size(ModelAPI_Feature::group());
935           for (int a = 0; a < aNum; a++) {
936             FeaturePtr aFeat = std::dynamic_pointer_cast<ModelAPI_Feature>(
937               aRootDoc->object(ModelAPI_Feature::group(), a));
938             if (aFeat.get() && aFeat->data() && aFeat->data()->isValid() &&
939               aFeat->getKind() == "Part" && aFeat->results().size()) {
940               ResultPartPtr aPart =
941                 std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFeat->firstResult());
942               if (aPart.get() && aPart->partDoc().get() && aPart->data()->name() == aPartName) {
943                 aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
944                 aSubShapeName = aSubShapeName.substr(aPartEnd + 1);
945               }
946             }
947           }
948         }
949       }
950     }
951
952     // check this is a whole feature context
953     if (aSubShapeName.size() > kWHOLE_FEATURE.size() &&
954       aSubShapeName.substr(0, kWHOLE_FEATURE.size()) == kWHOLE_FEATURE) {
955       std::wstring aFeatureName = aSubShapeName.substr(kWHOLE_FEATURE.size());
956       ObjectPtr anObj = aDoc->objectByName(ModelAPI_Feature::group(), aFeatureName);
957       if (anObj.get()) {
958         setValue(anObj, anEmptyShape);
959         return;
960       }
961     }
962
963     // the whole result selection check
964     if (aSubShapeName.find(L'/') == std::wstring::npos) {
965       ObjectPtr aRes = aDoc->objectByName(ModelAPI_ResultConstruction::group(), aSubShapeName);
966       if (!aRes.get()) {
967         aRes = aDoc->objectByName(ModelAPI_ResultBody::group(), aSubShapeName);
968         if (!aRes.get())
969           aRes = aDoc->objectByName(ModelAPI_ResultGroup::group(), aSubShapeName);
970       }
971       if (aRes.get()) {
972         setValue(aRes, anEmptyShape);
973         return;
974       }
975     }
976
977     Selector_Selector aSelector(selectionLabel(), baseDocumentLab());
978     myRestoreDocument = aDoc;
979     TDF_Label aContextLabel = aSelector.restoreByName(
980       aSubShapeName, aShapeType, this, myIsGeometricalSelection);
981     myRestoreDocument.reset();
982     if (!aContextLabel.IsNull()) {
983       ResultPtr aContext = aDoc->resultByLab(aContextLabel); // any label for document access
984       if (aContext.get() && aContext->shape().get()) {
985         TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
986         if (aSelector.solve(aContextShape)) {
987           TopoDS_Shape aSelectorShape = aSelector.value();
988           GeomShapePtr aShapeToBeSelected(new GeomAPI_Shape);
989           aShapeToBeSelected->setImpl<TopoDS_Shape>(new TopoDS_Shape(aSelectorShape));
990           // make the context result the latest existing
991           aContext = newestContext(aContext, aShapeToBeSelected);
992           if (myIsGeometricalSelection || aCenterType == NOT_CENTER) {
993             // store the currently generated name
994             selectionLabel().ForgetAllAttributes(true);
995             bool aToUnblock = false;
996             aToUnblock = !owner()->data()->blockSendAttributeUpdated(true);
997             myRef.setValue(aContext);
998             aSelector.store(aContextShape);
999             owner()->data()->sendAttributeUpdated(this);
1000             if (aToUnblock)
1001               owner()->data()->blockSendAttributeUpdated(false);
1002             return;
1003           } else { // re-select center of circle/arc by context and value
1004             if (!aShapeToBeSelected->isEdge())
1005               continue;
1006             std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aShapeToBeSelected));
1007             setValueCenter(aContext, aSelectedEdge, aCenterType);
1008           }
1009           return;
1010         }
1011       }
1012     }
1013   }
1014   // invalid
1015   TDF_Label aSelLab = selectionLabel();
1016   setInvalidIfFalse(aSelLab, false);
1017   reset();
1018 }
1019
1020 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1021                                               const GeomPointPtr& thePoint)
1022 {
1023   if (theType.empty() || !thePoint)
1024     return;
1025
1026   // list of parent features
1027   FeaturePtr anOwner = ModelAPI_Feature::feature(owner());
1028   std::set<FeaturePtr> aParents = ModelAPI_Tools::getParents(anOwner);
1029
1030   int aSelectionIndex = 0;
1031   GeomAPI_Shape::ShapeType aType = GeomAPI_Shape::shapeTypeByStr(theType);
1032   if (aType == GeomAPI_Shape::SHAPE) {
1033     // possibly, the string consists of the type and the index,
1034     // thus, try to separate them
1035     size_t aUndersporePos = theType.find_first_of('_');
1036     if (aUndersporePos != std::string::npos)
1037       aType = GeomAPI_Shape::shapeTypeByStr(theType.substr(0, aUndersporePos));
1038
1039     if (aType != GeomAPI_Shape::SHAPE) {
1040       for (std::string::const_iterator aChar = theType.begin() + aUndersporePos + 1;
1041            aChar != theType.end(); ++aChar) {
1042         if (std::isdigit(*aChar))
1043           aSelectionIndex = aSelectionIndex * 10 + (*aChar - '0');
1044         else {
1045           aSelectionIndex = 1;
1046           break;
1047         }
1048       }
1049       aSelectionIndex -= 1;
1050     }
1051   }
1052
1053   std::list<ModelGeomAlgo_Shape::SubshapeOfResult> anAppropriate;
1054
1055   // collect features from PartSet and the current part
1056   SessionPtr aSession = ModelAPI_Session::get();
1057   std::list<FeaturePtr> aFeatures = aSession->moduleDocument()->allFeatures();
1058   if (aSession->moduleDocument() != owner()->document()) {
1059     std::list<FeaturePtr> aPartFeatures = owner()->document()->allFeatures();
1060     aFeatures.insert(aFeatures.end(), aPartFeatures.begin(), aPartFeatures.end());
1061   }
1062   // Process results of all features from the last to the first
1063   // to find appropriate sub-shape
1064   for (std::list<FeaturePtr>::const_reverse_iterator anIt = aFeatures.rbegin();
1065        anIt != aFeatures.rend(); ++anIt) {
1066     // selection cannot be linked to the parent features
1067     if (aParents.find(*anIt) != aParents.end())
1068       continue;
1069     // check the feature is a part of composite feature (like sketch elements),
1070     // then do not process it, it will be processed in scope of composite feature
1071     bool isSubOfComposite = false;
1072     const std::set<AttributePtr>& aRefs = (*anIt)->data()->refsToMe();
1073     for (std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
1074          aRefIt != aRefs.end() && !isSubOfComposite; ++aRefIt) {
1075       FeaturePtr aFeature = ModelAPI_Feature::feature((*aRefIt)->owner());
1076       CompositeFeaturePtr aCompFeature =
1077           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
1078       isSubOfComposite = aCompFeature && aCompFeature->isSub(*anIt);
1079     }
1080     if (isSubOfComposite)
1081       continue;
1082
1083     // process results of the current feature to find appropriate sub-shape
1084     if (ModelGeomAlgo_Shape::findSubshapeByPoint(*anIt, thePoint, aType, anAppropriate)) {
1085       std::list<ModelGeomAlgo_Shape::SubshapeOfResult>::iterator anApIt = anAppropriate.begin();
1086       for (; aSelectionIndex > 0 && anApIt != anAppropriate.end(); --aSelectionIndex)
1087         ++anApIt; // skip this shape, because one of the previous is selected
1088
1089       if (anApIt != anAppropriate.end()) {
1090         if (anApIt->myCenterType == (int)ModelAPI_AttributeSelection::NOT_CENTER)
1091           setValue(anApIt->myResult, anApIt->mySubshape);
1092         else
1093           setValueCenter(anApIt->myResult, anApIt->mySubshape->edge(),
1094                          (ModelAPI_AttributeSelection::CenterType)anApIt->myCenterType);
1095         return;
1096       }
1097     }
1098   }
1099
1100   TDF_Label aSelLab = selectionLabel();
1101   setInvalidIfFalse(aSelLab, false);
1102   reset();
1103 }
1104
1105 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1106   const std::wstring& theContextName, const int theIndex)
1107 {
1108   // selection of context by name
1109   selectSubShape(theType, theContextName);
1110   ResultPtr aContext = context();
1111   if (aContext.get()) {
1112     GeomShapePtr aContShape = aContext->shape();
1113     if (aContShape.get()) {
1114       GeomAlgoAPI_NExplode aNExp(aContShape, GeomAPI_Shape::shapeTypeByStr(theType));
1115       GeomShapePtr aValue = aNExp.shape(theIndex);
1116       if (aValue.get())
1117         setValue(aContext, aValue);
1118     }
1119   }
1120 }
1121
1122 void Model_AttributeSelection::setId(int theID)
1123 {
1124   std::shared_ptr<GeomAPI_Shape> aSelection;
1125
1126   ResultPtr aContextRes = context();
1127   // support for compsolids:
1128   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1129     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1130   }
1131   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1132
1133   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1134   // searching for the latest main shape
1135   if (theID > 0 && aContext && !aContext->isNull())
1136   {
1137     std::shared_ptr<Model_Document> aDoc =
1138       std::dynamic_pointer_cast<Model_Document>(aContextRes->document());
1139     if (aDoc.get()) {
1140       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1141       if (!aNS.IsNull()) {
1142         aMainShape = TNaming_Tool::CurrentShape(aNS);
1143       }
1144     }
1145
1146     TopTools_IndexedMapOfShape aSubShapesMap;
1147     TopExp::MapShapes(aMainShape, aSubShapesMap);
1148     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1149
1150     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1151     aResult->setImpl(new TopoDS_Shape(aSelShape));
1152
1153     aSelection = aResult;
1154   }
1155
1156   setValue(aContextRes, aSelection);
1157 }
1158
1159 std::wstring Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1160 {
1161   std::wstring aResult;
1162   if (owner()->document() != theContext->document()) {
1163     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1164       aResult = Locale::Convert::toWString(theContext->document()->kind()) + L"/";
1165     } else {
1166       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1167         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1168       if (aDocRes.get()) {
1169         aResult = aDocRes->data()->name() + L"/";
1170       }
1171     }
1172   }
1173   aResult += theContext->data()->name();
1174   return aResult;
1175 }
1176
1177 void Model_AttributeSelection::computeValues(
1178   ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
1179   TopTools_ListOfShape& theShapes)
1180 {
1181   bool aWasWholeContext = theValShape.IsNull();
1182   if (aWasWholeContext) {
1183     theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
1184   }
1185   TopAbs_ShapeEnum aValType = theValShape.ShapeType();
1186   TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
1187   // if a new value is unchanged in the new context, do nothing: value is correct
1188   TopExp_Explorer aSubExp(aNewContShape, aValType);
1189   for(; aSubExp.More(); aSubExp.Next()) {
1190     if (aSubExp.Current().IsSame(theValShape)) {
1191       theShapes.Append(theValShape);
1192       return;
1193     }
1194   }
1195   // if new context becomes compsolid, the resulting sub may be in sub-solids
1196   std::list<ResultPtr> aNewToIterate;
1197   aNewToIterate.push_back(theNewContext);
1198   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theNewContext);
1199   if (aComp.get()) {
1200     std::list<ResultPtr> allNewContextSubs;
1201     ModelAPI_Tools::allSubs(aComp, allNewContextSubs);
1202     std::list<ResultPtr>::iterator aSub = allNewContextSubs.begin();
1203     for(; aSub != allNewContextSubs.end(); aSub++) {
1204       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aSub);
1205       if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1206         aNewToIterate.push_back(aBody);
1207     }
1208   }
1209
1210   // first iteration: searching for the whole shape appearance (like face of the box)
1211   // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
1212   int aToFindPart = 0;
1213   TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
1214   TopTools_MapOfShape anOlds; // to know how many olds produced new containers
1215   for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
1216     std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
1217     for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
1218       std::shared_ptr<Model_Data> aNewData =
1219         std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
1220       TDF_Label aNewLab = aNewData->shapeLab();
1221       // searching for produced sub-shape fully on some label
1222       TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID());
1223       for(; aNSIter.More(); aNSIter.Next()) {
1224         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1225         for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
1226           if (aToFindPart == 0) { // search shape is fully inside
1227             if (aPairIter.OldShape().IsSame(theValShape)) {
1228               if (aPairIter.NewShape().IsNull()) {// value was removed
1229                 theShapes.Clear();
1230                 return;
1231               }
1232               // don't add edges generated from faces
1233               if (aPairIter.NewShape().ShapeType() <= aValType)
1234                 theShapes.Append(aPairIter.NewShape());
1235             }
1236           } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
1237             TopExp_Explorer anExp(aPairIter.OldShape(), aValType);
1238             for(; anExp.More(); anExp.Next()) {
1239               if (anExp.Current().IsSame(theValShape)) { // found a new container
1240                 if (aPairIter.NewShape().IsNull()) // skip removed high-level shape
1241                   continue;
1242                 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
1243                 anOlds.Add(aPairIter.OldShape());
1244                 break;
1245               }
1246             }
1247           }
1248         }
1249       }
1250     }
1251   }
1252   if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
1253     // also iterate the whole old shape to find not-modified shapes that contain this old
1254     TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
1255     NCollection_Map<TopAbs_ShapeEnum> aNewTypes; // types of shapes to iterate
1256     TopTools_DataMapOfShapeShape::Iterator aNewTypeIter(aNewToOld);
1257     for(; aNewTypeIter.More(); aNewTypeIter.Next()) {
1258       if (aNewTypeIter.Key().ShapeType() != aValType)
1259         aNewTypes.Add(aNewTypeIter.Key().ShapeType());
1260     }
1261     NCollection_Map<TopAbs_ShapeEnum>::Iterator aTypeIter(aNewTypes);
1262     for(; aTypeIter.More(); aTypeIter.Next()) {
1263       for(TopExp_Explorer anExp(anOldContShape, aTypeIter.Value()); anExp.More(); anExp.Next()) {
1264         TopoDS_Shape anOld = anExp.Current();
1265         if (aNewToOld.IsBound(anOld) || anOlds.Contains(anOld)) // this was modified
1266           continue;
1267         TopExp_Explorer aValExp(anOld, aValType);
1268         for(; aValExp.More(); aValExp.Next()) {
1269           const TopoDS_Shape& anUnchanged = aValExp.Current();
1270           if (anUnchanged.IsSame(theValShape)) {
1271             aNewToOld.Bind(anOld, anOld);
1272             anOlds.Add(anOld);
1273             break;
1274           }
1275         }
1276       }
1277     }
1278
1279     // map of sub-shapes -> number of occurrences of these shapes in containers
1280     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
1281     TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
1282     for(; aContIter.More(); aContIter.Next()) {
1283       for(aSubExp.Init(aContIter.Key(), aValType); aSubExp.More(); aSubExp.Next()) {
1284         if (!aSubs.IsBound(aSubExp.Current())) {
1285           aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
1286         }
1287         // store old to know how many olds produced this shape
1288         aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
1289       }
1290     }
1291     // if sub is appeared same times in containers as the number of old shapes that contain it
1292     int aCountInOld = anOlds.Size();
1293     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
1294       aSubsIter(aSubs);
1295     for(; aSubsIter.More(); aSubsIter.Next()) {
1296       if (aSubsIter.Value().Size() == aCountInOld) {
1297         TopoDS_Shape anOld = aSubsIter.Key();
1298         // check this exists in the new shape
1299         TopExp_Explorer aNew(aNewContShape, anOld.ShapeType());
1300         for (; aNew.More(); aNew.Next()) {
1301           if (aNew.Current().IsSame(anOld))
1302             break;
1303         }
1304         if (aNew.More())
1305           theShapes.Append(anOld);
1306       }
1307     }
1308   }
1309   if (theShapes.IsEmpty()) { // nothing was changed
1310     if (aWasWholeContext)
1311       theShapes.Append(TopoDS_Shape());
1312     else { // if theValShape exists in new context, add it without changes, otherwise - nothing
1313       for (TopExp_Explorer aNew(aNewContShape, aValType); aNew.More(); aNew.Next()){
1314         if (aNew.Current().IsSame(theValShape)) {
1315           theShapes.Append(theValShape);
1316           break;
1317         }
1318       }
1319     }
1320   } else if (theShapes.Size() > 1) {
1321     // check it is possible to remove extra sub-shapes:
1322     // keep only shapes with the same number of containers if possible
1323     TopAbs_ShapeEnum anAncType = TopAbs_FACE;
1324     if (aValType == TopAbs_VERTEX)
1325       anAncType = TopAbs_EDGE;
1326     TopoDS_Shape anOldContext = theOldContext->shape()->impl<TopoDS_Shape>();
1327     TopTools_IndexedDataMapOfShapeListOfShape anOldMap;
1328     TopExp::MapShapesAndUniqueAncestors(anOldContext, aValType,  anAncType, anOldMap);
1329     if (anOldMap.Contains(theValShape)) {
1330       int aNumInOld = anOldMap.FindFromKey(theValShape).Extent();
1331       TopTools_IndexedDataMapOfShapeListOfShape aNewMap;
1332       TopExp::MapShapesAndUniqueAncestors(aNewContShape, aValType,  anAncType, aNewMap);
1333       TopTools_ListOfShape aNewResults;
1334       for(TopTools_ListOfShape::Iterator aNewSubs(theShapes); aNewSubs.More(); aNewSubs.Next()) {
1335         TopoDS_Shape aCand = aNewSubs.Value();
1336         if (aNewMap.Contains(aCand) && aNewMap.FindFromKey(aCand).Extent() == aNumInOld)
1337           aNewResults.Append(aCand);
1338       }
1339       if (!aNewResults.IsEmpty() && aNewResults.Size() < theShapes.Size())
1340         theShapes = aNewResults;
1341     }
1342   }
1343 }
1344
1345
1346 void Model_AttributeSelection::concealedFeature(
1347   const FeaturePtr theFeature, const FeaturePtr theStop, const bool theCheckCopy,
1348   std::list<FeaturePtr>& theConcealers, const ResultPtr theResultOfFeature,
1349   const bool theCheckWholeFeature)
1350 {
1351   std::set<FeaturePtr> alreadyProcessed;
1352   alreadyProcessed.insert(theFeature);
1353   if (theStop.get())
1354     alreadyProcessed.insert(theStop);
1355   /// iterate all results to find the concealment-attribute
1356   std::list<ResultPtr> aRootRes;
1357   if (theResultOfFeature.get()) {
1358     ResultPtr aRoot = ModelAPI_Tools::bodyOwner(theResultOfFeature, true);
1359     aRootRes.push_back(aRoot ? aRoot : theResultOfFeature);
1360   } else { // all results of a feature
1361    aRootRes = theFeature->results();
1362   }
1363   std::list<ResultPtr>::const_iterator aRootIter = aRootRes.cbegin();
1364   for(; aRootIter != aRootRes.cend(); aRootIter++) {
1365     std::list<DataPtr> allRes;
1366     allRes.push_back((*aRootIter)->data());
1367     ResultBodyPtr aRootBody = ModelAPI_Tools::bodyOwner(*aRootIter, true);
1368     if (!aRootBody.get())
1369       aRootBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRootIter);
1370     if (aRootBody.get()) {
1371       std::list<ResultPtr> allSub;
1372       ModelAPI_Tools::allSubs(aRootBody, allSub);
1373       for(std::list<ResultPtr>::iterator anIt = allSub.begin(); anIt != allSub.end(); anIt++)
1374         allRes.push_back((*anIt)->data());
1375     }
1376     if (theCheckWholeFeature)
1377       allRes.push_back(theFeature->data());
1378     for(std::list<DataPtr>::iterator aRIter = allRes.begin(); aRIter != allRes.end(); aRIter++) {
1379       const std::set<AttributePtr>& aRefs = (*aRIter)->refsToMe();
1380       std::set<AttributePtr>::const_iterator aRef = aRefs.cbegin();
1381       for (; aRef != aRefs.cend(); aRef++) {
1382         if (!aRef->get() || !(*aRef)->owner().get())
1383           continue;
1384         // concealed attribute only
1385         FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1386         if (alreadyProcessed.find(aRefFeat) != alreadyProcessed.end()) // optimization
1387           continue;
1388         alreadyProcessed.insert(aRefFeat);
1389         if (ModelAPI_Session::get()->validators()->isConcealed(aRefFeat->getKind(), (*aRef)->id())
1390           || (theCheckCopy &&
1391               std::dynamic_pointer_cast<ModelAPI_FeatureCopyInterface>(aRefFeat).get()))
1392         {
1393           // for extrusion cut in python script the nested sketch reference may be concealed before
1394           // it is nested, so, check this composite feature is valid
1395           static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
1396           // need to be validated to update the "Apply" state if not previewed
1397           if (aFactory->validate(aRefFeat)) {
1398             if (theStop.get()) {
1399               std::shared_ptr<Model_Document> aDoc =
1400                 std::dynamic_pointer_cast<Model_Document>(theStop->document());
1401               if (!aDoc->isLaterByDep(theStop, aRefFeat)) // skip feature later than stop
1402                 continue;
1403             }
1404             theConcealers.push_back(aRefFeat);
1405           }
1406         }
1407       }
1408     }
1409   }
1410 }
1411
1412 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
1413   const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
1414   TDF_Label theAccessLabel,
1415   std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
1416 {
1417   std::list<ResultPtr> aResults; // keep order, new context, null if deleted
1418   std::set<ResultPtr> aResultsSet; // to avoid duplicates
1419   // iterate context and shape, but also if it is sub-shape of main shape, check also it
1420   TopTools_ListOfShape aContextList;
1421   aContextList.Append(theContShape);
1422   if (theContext.get()) {
1423     ResultPtr aComposite = ModelAPI_Tools::bodyOwner(theContext);
1424     if (aComposite.get() && aComposite->shape().get() && !aComposite->shape()->isNull())
1425       aContextList.Append(aComposite->shape()->impl<TopoDS_Shape>());
1426   }
1427   for(TopTools_ListOfShape::Iterator aContIter(aContextList); aContIter.More(); aContIter.Next()) {
1428     TNaming_SameShapeIterator aModifIter(aContIter.ChangeValue(), theAccessLabel);
1429     for(; aModifIter.More(); aModifIter.Next()) {
1430       TDF_Label anObjLab = aModifIter.Label().Father();
1431       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1432         (theDoc->objects()->object(anObjLab));
1433       if (!aModifierObj.get()) {
1434         // #2241: shape may be sub-element of new object, not main (shell created from faces)
1435         if (!anObjLab.IsRoot())
1436           aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1437           (theDoc->objects()->object(anObjLab.Father()));
1438         if (!aModifierObj.get())
1439           continue;
1440       }
1441       FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
1442       if (!aModifierFeat.get())
1443         continue;
1444       FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1445       if (aModifierFeat == aThisFeature || !theDoc->isLaterByDep(aThisFeature, aModifierFeat))
1446         continue; // the modifier feature is later than this, so, should not be used
1447       FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
1448       if (aCurrentModifierFeat == aModifierFeat ||
1449         !theDoc->isLaterByDep(aModifierFeat, aCurrentModifierFeat))
1450         continue; // the current modifier is later than the found, so, useless
1451       Handle(TNaming_NamedShape) aNewNS;
1452       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1453       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1454         if (aResultsSet.find(aModifierObj) == aResultsSet.end()) {
1455           aResultsSet.insert(aModifierObj);
1456           aResults.push_back(aModifierObj);
1457         }
1458       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
1459         aResults.push_back(ResultPtr());
1460       } else { // not-processed modification => don't support it
1461         continue;
1462       }
1463     }
1464   }
1465   // if there exist context composite and sub-result(s), leave only sub(s)
1466   for(std::list<ResultPtr>::iterator aResIter = aResults.begin(); aResIter != aResults.end();) {
1467     ResultPtr aParent = ModelAPI_Tools::bodyOwner(*aResIter);
1468     for(; aParent.get(); aParent = ModelAPI_Tools::bodyOwner(aParent))
1469       if (aResultsSet.count(aParent))
1470         break;
1471     if (aParent.get()) {
1472       aResultsSet.erase(aParent);
1473       for(std::list<ResultPtr>::iterator anIt = aResults.begin(); anIt != aResults.end(); anIt++) {
1474         if (*anIt == aParent) {
1475           aResults.erase(anIt);
1476           aResIter = aResults.begin(); // erase from set, so, restart iteration
1477           break;
1478         }
1479       }
1480     } else aResIter++;
1481   }
1482
1483   bool aStaySame = false;
1484   if (aResults.empty()) {
1485     // check the context become concealed by operation which is earlier than this selection
1486     FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1487     FeaturePtr aContextOwner = theDoc->feature(theContext);
1488     std::list<FeaturePtr> aConcealers;
1489     concealedFeature(aContextOwner, aThisFeature, false, aConcealers, theContext);
1490     std::list<FeaturePtr>::iterator aConcealer = aConcealers.begin();
1491     for(; aConcealer != aConcealers.end(); aConcealer++) {
1492       std::list<ResultPtr> aRefResults;
1493       ModelAPI_Tools::allResults(*aConcealer, aRefResults);
1494       std::list<ResultPtr>::iterator aRefIter = aRefResults.begin();
1495       for(; aRefIter != aRefResults.end(); aRefIter++) {
1496         ResultBodyPtr aRefBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRefIter);
1497         if (!aRefBody.get() || aRefBody->numberOfSubs() != 0) // iterate only leafs
1498           continue;
1499         GeomShapePtr aRefShape = aRefBody->shape();
1500         if (!aRefShape.get() || aRefShape->isNull())
1501           continue;
1502         if (aRefShape->impl<TopoDS_Shape>().IsSame(theContShape)) {
1503           // add the new context result with the same shape
1504           aResults.push_back(aRefBody);
1505         }
1506       }
1507       if (aResults.empty())
1508         return true; // feature conceals result, return true, so the context will be removed
1509     }
1510     aStaySame = aResults.empty();
1511   }
1512   if (myParent && myParent->isMakeCopy()) {
1513     // check there are copies before the new results, so, make a copy
1514     std::list<ObjectPtr> aCopyContext;
1515     std::list<GeomShapePtr> aCopyVals;
1516     // features between the new and the old: check the "Move" interface to get a copy
1517     FeaturePtr aRootOwner = theDoc->feature(theContext);
1518     FeaturePtr anOwner = ModelAPI_Tools::compositeOwner(aRootOwner);
1519     for(; anOwner.get(); anOwner = ModelAPI_Tools::compositeOwner(anOwner))
1520       aRootOwner = anOwner;
1521     FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1522     // iterate all results to find a "Copy" features between the new and one and to add the
1523     // copy-results also to results if this attribute refers to the copied shape
1524     int anIndex = kUNDEFINED_FEATURE_INDEX;
1525     for(FeaturePtr aFeat = theDoc->objects()->nextFeature(aRootOwner, anIndex); aFeat.get() &&
1526         aFeat != aThisFeature; aFeat = theDoc->objects()->nextFeature(aFeat, anIndex)) {
1527       std::shared_ptr<ModelAPI_FeatureCopyInterface> aCopier =
1528         std::dynamic_pointer_cast<ModelAPI_FeatureCopyInterface>(aFeat);
1529       if (aCopier.get()) {
1530         GeomShapePtr aValShape(new GeomAPI_Shape);
1531         aValShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(
1532           theValShape.IsNull() ? theContShape : theValShape));
1533         aCopier->getCopies(theContext, aValShape, aCopyContext, aCopyVals);
1534       }
1535     }
1536     // check for the further modifications of the copy contexts and values
1537     std::list<ObjectPtr>::iterator aCopyContIter = aCopyContext.begin();
1538     std::list<GeomShapePtr>::iterator aCopyValIter = aCopyVals.begin();
1539     for(; aCopyContIter != aCopyContext.end(); aCopyContIter++, aCopyValIter++) {
1540       ResultPtr aNewCont = std::dynamic_pointer_cast<ModelAPI_Result>(*aCopyContIter);
1541       TopoDS_Shape aNewContShape = aNewCont->shape()->impl<TopoDS_Shape>();
1542       GeomShapePtr aNewVal = *aCopyValIter;
1543       TopoDS_Shape aNewValShape;
1544       if (aNewVal.get() && !aNewVal->isNull())
1545         aNewValShape = aNewVal->impl<TopoDS_Shape>();
1546       std::list<ResultPtr> aNewRes;
1547       TopTools_ListOfShape aNewUpdatedVal;
1548       if (searchNewContext(theDoc, aNewContShape, aNewCont, aNewValShape,
1549           theAccessLabel, aNewRes, aNewUpdatedVal)) {
1550         // append new results instead of the current ones
1551         std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1552         TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1553         for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1554           theResults.push_back(*aNewIter);
1555           theValShapes.Append(aNewUpdVal.Value());
1556         }
1557       } else { // the current result is good
1558         theResults.push_back(aNewCont);
1559         theValShapes.Append(aNewValShape);
1560       }
1561     }
1562     if (aStaySame && !theResults.empty()) { // no changes except copy, so, keep the origin as first
1563       theResults.push_front(theContext);
1564       theValShapes.Prepend(theValShape);
1565       return true;
1566     }
1567   }
1568   if (aStaySame)
1569     return false;
1570
1571   // iterate all results to find further modifications
1572   std::list<ResultPtr>::iterator aResIter = aResults.begin();
1573   for(aResIter = aResults.begin(); aResIter != aResults.end(); aResIter++) {
1574     if (aResIter->get() != NULL) {
1575       ResultPtr aNewResObj = *aResIter;
1576       // compute new values by two contexts: the old and the new
1577       TopTools_ListOfShape aValShapes;
1578       computeValues(theContext, aNewResObj, theValShape, aValShapes);
1579
1580       TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
1581       for(; aNewVal.More(); aNewVal.Next()) {
1582         std::list<ResultPtr> aNewRes;
1583         TopTools_ListOfShape aNewUpdatedVal;
1584         TopoDS_Shape aNewValSh = aNewVal.Value();
1585         TopoDS_Shape aNewContShape = aNewResObj->shape()->impl<TopoDS_Shape>();
1586
1587         if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
1588           aNewValSh.Nullify();
1589         if (searchNewContext(theDoc, aNewContShape, aNewResObj, aNewValSh,
1590                              theAccessLabel, aNewRes, aNewUpdatedVal))
1591         {
1592           // append new results instead of the current ones
1593           std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1594           TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1595           for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1596             theResults.push_back(*aNewIter);
1597             theValShapes.Append(aNewUpdVal.Value());
1598           }
1599         } else { // the current result is good
1600           theResults.push_back(aNewResObj);
1601           theValShapes.Append(aNewValSh);
1602         }
1603       }
1604     }
1605   }
1606   return true; // theResults must be empty: everything is deleted
1607 }
1608
1609 void Model_AttributeSelection::updateInHistory(bool& theRemove)
1610 {
1611   static std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1612
1613   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1614   if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
1615       aContext->groupName() != ModelAPI_ResultPart::group())) {
1616     // but check the case the whole results are allowed: whole features may be selected
1617     if (myParent && myParent->isWholeResultAllowed()) {
1618       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
1619       if (aFeature.get()) {
1620         FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1621         std::list<FeaturePtr> aConcealers;
1622         bool aCopyPossible = myParent && myParent->isMakeCopy();
1623         concealedFeature(aFeature, aThisFeature, aCopyPossible, aConcealers, ResultPtr());
1624         if (aConcealers.empty())
1625           return;
1626         // if there are copies, but no direct modification, keep the original
1627         bool aKeepOrigin = false;
1628         if (aCopyPossible) {
1629           std::list<FeaturePtr>::iterator aConcealer = aConcealers.begin();
1630           for(aKeepOrigin = true; aConcealer != aConcealers.end(); aConcealer++)
1631             if (!std::dynamic_pointer_cast<ModelAPI_FeatureCopyInterface>(*aConcealer).get()) {
1632               aKeepOrigin = false;
1633               break;
1634             }
1635           if (aKeepOrigin) {
1636             aConcealers.push_front(aFeature);
1637           }
1638         }
1639         bool aChanged = false;
1640         std::list<FeaturePtr>::iterator aConcealer = aConcealers.begin();
1641         for(; aConcealer != aConcealers.end(); aConcealer++)
1642           if (aChanged) {
1643             if (aKeepOrigin || !myParent->isInList(*aConcealer, anEmptyShape))
1644               myParent->append(*aConcealer, anEmptyShape);
1645           } else {
1646             if (!myParent->isInList(*aConcealer, anEmptyShape)) {// avoid addition of duplicates
1647               setValue(*aConcealer, anEmptyShape);
1648               aChanged = true;
1649             } else if (aCopyPossible && *aConcealer == aFeature) {// keep origin in case of copy
1650               aChanged = true;
1651             }
1652           }
1653         if (!aChanged) // remove this
1654           theRemove = true;
1655         else if (!aKeepOrigin) // searching further modifications only if current changed
1656           updateInHistory(theRemove);
1657       }
1658     }
1659     return;// only bodies and parts may be modified later in the history, skip otherwise
1660   }
1661
1662   std::shared_ptr<Model_Document> aDoc =
1663     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1664   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1665   if (!aContData.get() || !aContData->isValid())
1666     return;
1667   TDF_Label aContLab = aContData->shapeLab(); // named shape where the selected context is located
1668
1669   // checking this may be just a reference to another context (same shape), so use that label
1670   Handle(TNaming_NamedShape) aContNS;
1671   Handle(TDF_Reference) aRefAttr;
1672   while(!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS) &&
1673         aContLab.FindAttribute(TDF_Reference::GetID(), aRefAttr))
1674     aContLab = aRefAttr->Get();
1675
1676   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
1677     bool aFoundNewContext = true;
1678     ResultPtr aNewContext = aContext;
1679     while(aFoundNewContext) {
1680       aFoundNewContext = false;
1681       // parts have no shape in result, so, trace references using the Part info
1682       if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
1683         ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
1684         if (aPartContext.get()) { // searching for the up to date references to the referenced cont
1685           const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
1686           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1687           for(; aRef != aRefs.end(); aRef++) {
1688             // to avoid detection of part changes by local selection only
1689             AttributeSelectionPtr aSel =
1690               std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1691             if (aSel.get() && aSel->value().get() &&
1692                 !aSel->value()->isSame(aSel->context()->shape()))
1693               continue;
1694
1695             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1696
1697             if (aRefFeat.get() && aRefFeat != owner() && aRefFeat->firstResult().get()) {
1698               // check the reference is concealed: #2900
1699               ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
1700               if (!aValidators->isConcealed(aRefFeat->getKind(), (*aRef)->id()))
1701                 continue;
1702               FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1703               if (!aDoc->isLaterByDep(aRefFeat, aThisFeature)) { // found better feature
1704                 aFoundNewContext = true;
1705                 aNewContext = aRefFeat->firstResult();
1706               }
1707             }
1708           }
1709         }
1710       }
1711     }
1712     if (aNewContext != aContext) {
1713       setValue(aNewContext, value());
1714     }
1715     return;
1716   }
1717   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1718   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1719   // iterate the context shape modifications in order to find a feature that is upper in history
1720   // that this one and is really modifies the referenced result to refer to it
1721   ResultPtr aModifierResFound;
1722   TNaming_Iterator aPairIter(aContNS);
1723   if (!aPairIter.More())
1724     return;
1725   TopoDS_Shape aNewCShape = aPairIter.NewShape();
1726   // trying to update also the sub-shape selected
1727   GeomShapePtr aSubShape = value();
1728   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1729     aSubShape.reset();
1730   TopoDS_Shape aValShape;
1731   if (aSubShape.get()) {
1732     aValShape = aSubShape->impl<TopoDS_Shape>();
1733   }
1734
1735   std::list<ResultPtr> aNewContexts;
1736   TopTools_ListOfShape aValShapes;
1737   if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1738   {
1739     std::set<ResultPtr> allContexts(aNewContexts.begin(), aNewContexts.end());
1740     std::set<ResultPtr> aSkippedContext;
1741
1742     // if there exist context composite and sub-result(s), leave only sub(s)
1743     std::set<ResultPtr>::iterator aResIter = allContexts.begin();
1744     for(; aResIter != allContexts.end(); aResIter++) {
1745       ResultPtr aParent = ModelAPI_Tools::bodyOwner(*aResIter);
1746       for(; aParent.get(); aParent = ModelAPI_Tools::bodyOwner(aParent))
1747         if (allContexts.count(aParent))
1748           aSkippedContext.insert(aParent);
1749     }
1750
1751     GeomAPI_Shape::ShapeType aListShapeType = GeomAPI_Shape::SHAPE;
1752     if (myParent) {
1753       if (myParent->selectionType() == "VERTEX" || myParent->selectionType() == "Vertices")
1754         aListShapeType = GeomAPI_Shape::VERTEX;
1755       else if (myParent->selectionType() == "EDGE" || myParent->selectionType() == "Edges")
1756         aListShapeType = GeomAPI_Shape::EDGE;
1757       else if (myParent->selectionType() == "FACE" || myParent->selectionType() == "Faces")
1758         aListShapeType = GeomAPI_Shape::FACE;
1759     }
1760
1761     // issue #3031: skip topology if there is more convenient shape type presents in the
1762     // same context as a result of this
1763     bool isWholeResult = myParent && myParent->isWholeResultAllowed() && !aSubShape.get();
1764     GeomAPI_Shape::ShapeType allowedType = GeomAPI_Shape::SHAPE;
1765     if (isWholeResult) {
1766       std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1767       TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1768       for(; aNewCont != aNewContexts.end(); aNewCont++, aNewValues.Next()) {
1769         if (aNewValues.Value().IsNull()) { // only for the whole context
1770           GeomAPI_Shape::ShapeType aShapeType = (*aNewCont)->shape()->shapeType();
1771           if (allowedType == GeomAPI_Shape::SHAPE) { // just set this one
1772             allowedType = aShapeType;
1773           } else {
1774             GeomAPI_Shape::ShapeType anAllowed = allowedType;
1775             if (anAllowed != aShapeType) { // select the best, nearest to the origin
1776               GeomAPI_Shape::ShapeType anOldShapeType = aContext->shape()->shapeType();
1777               GeomAPI_Shape::ShapeType aDeltaAllowed =
1778                 (GeomAPI_Shape::ShapeType)(anOldShapeType - anAllowed);
1779               if (aDeltaAllowed < 0)
1780                 aDeltaAllowed = (GeomAPI_Shape::ShapeType)(-aDeltaAllowed);
1781               GeomAPI_Shape::ShapeType aDeltaThis =
1782                 (GeomAPI_Shape::ShapeType)(anOldShapeType - aShapeType);
1783               if (aDeltaThis < 0)
1784                 aDeltaThis = (GeomAPI_Shape::ShapeType)(-aDeltaThis);
1785               if (aDeltaThis == aDeltaAllowed) { // equal distance to context, select complicated
1786                 if (anOldShapeType < anAllowed)
1787                   allowedType = aShapeType;
1788               } else if (aDeltaAllowed > aDeltaThis) { // this wins
1789                 allowedType = aShapeType;
1790               }
1791             }
1792           }
1793         }
1794       }
1795     }
1796
1797     std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1798     TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1799     bool aFirst = true; // first is set to this, next are appended to parent
1800     for(; aNewCont != aNewContexts.end(); aNewCont++, aNewValues.Next()) {
1801       if (aSkippedContext.count(*aNewCont))
1802         continue;
1803
1804       if (isWholeResult && aNewValues.Value().IsNull())
1805         if (allowedType != GeomAPI_Shape::SHAPE &&
1806             (*aNewCont)->shape()->shapeType() != allowedType)
1807           continue; // there is better result exists with the better shape type (issue #3031)
1808
1809       GeomShapePtr aValueShape;
1810       if (!aNewValues.Value().IsNull()) {
1811         aValueShape = std::make_shared<GeomAPI_Shape>();
1812         aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1813       }
1814       // Check that list has the same type of shape selection before adding.
1815       GeomAPI_Shape::ShapeType aShapeShapeType = GeomAPI_Shape::SHAPE;
1816       if (aValueShape.get()) {
1817         aShapeShapeType = aValueShape->shapeType();
1818       } else {
1819         aShapeShapeType = (*aNewCont)->shape()->shapeType();
1820       }
1821       if (aListShapeType != GeomAPI_Shape::SHAPE && aListShapeType != aShapeShapeType) {
1822         // exception is for whole results selected
1823         if (!isWholeResult) {
1824           continue;
1825         }
1826       }
1827
1828       ResultPtr aNewContext = *aNewCont;
1829       if (aValueShape.get()) { // #2892 if context is higher level result, search this sub in lower
1830         ResultBodyPtr aBodyContext = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aNewContext);
1831         if (aBodyContext.get() && aBodyContext->numberOfSubs() != 0) {
1832           std::list<ResultPtr> aLower;
1833           ModelAPI_Tools::allSubs(aBodyContext, aLower, true);
1834           for(std::list<ResultPtr>::iterator aL = aLower.begin(); aL != aLower.end(); aL++) {
1835             GeomShapePtr aLShape = (*aL)->shape();
1836             if (aLShape.get() && !aLShape->isNull()) {
1837               if (aLShape->isSubShape(aValueShape, false)) {
1838                 aNewContext = *aL;
1839                 break;
1840               }
1841             }
1842           }
1843         }
1844       }
1845
1846       if (aFirst) {
1847         if (!myParent || !myParent->isInList(aNewContext, aValueShape)) { // avoid duplicates
1848           setValue(aNewContext, aValueShape);
1849           aFirst = false;
1850         } else if (aNewContext == aContext && myParent && myParent->isMakeCopy()) {
1851           // this may be exactly the old one, not modified in case of copy
1852           aFirst = false;
1853         }
1854       } else if (myParent) {
1855         if (!myParent->isInList(aNewContext, aValueShape)) // avoid addition of duplicates
1856           myParent->append(aNewContext, aValueShape);
1857       }
1858     }
1859     if (aFirst) { // nothing was added, all results were deleted
1860       if (myParent) {
1861         theRemove = true;
1862       } else {
1863         static ResultPtr anEmptyContext;
1864         setValue(anEmptyContext, anEmptyShape); // nullify the selection
1865         return;
1866       }
1867     }
1868   }
1869 }
1870
1871 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1872 {
1873   myParent = theParent;
1874 }
1875
1876 std::wstring Model_AttributeSelection::contextName(const TDF_Label theSelectionLab)
1877 {
1878   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1879     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1880   FeaturePtr aFeatureOwner = aDoc->featureByLab(theSelectionLab);
1881   bool aBaseDocumnetUsed = false;
1882   if (!aFeatureOwner.get()) { // use module document
1883     aDoc = std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument());
1884     aFeatureOwner = aDoc->featureByLab(theSelectionLab);
1885     aBaseDocumnetUsed = true;
1886   }
1887   if (aFeatureOwner.get()) {
1888     // if it is sub-element of the sketch, the context name is the name of the sketch
1889     // searching also for result - real context
1890     ResultPtr aResult;
1891     FeaturePtr aComposite = ModelAPI_Tools::compositeOwner(aFeatureOwner);
1892     if (aComposite.get() && aComposite->results().size() == 1 &&
1893         aComposite->firstResult()->groupName() == ModelAPI_ResultConstruction::group()) {
1894       aFeatureOwner = aComposite;
1895       aResult = aFeatureOwner->firstResult();
1896     } else {
1897       aResult = aDoc->resultByLab(theSelectionLab);
1898     }
1899     if (aResult.get()) {
1900       // this is to avoid duplicated names of results problem
1901       std::wstring aContextName = aResult->data()->name();
1902       // myLab corresponds to the current time
1903       TDF_Label aCurrentLab = selectionLabel();
1904       while(aCurrentLab.Depth() > 3)
1905         aCurrentLab = aCurrentLab.Father();
1906
1907       int aNumInHistoryNames =
1908         aDoc->numberOfNameInHistory(aResult, aCurrentLab);
1909       while(aNumInHistoryNames > 1) { // add "_" before name the needed number of times
1910         aContextName = L"_" + aContextName;
1911         aNumInHistoryNames--;
1912       }
1913       if (aBaseDocumnetUsed)
1914         aContextName = Locale::Convert::toWString(aDoc->kind()) + L"/" + aContextName;
1915       return aContextName;
1916     }
1917   }
1918   return L""; // invalid case
1919 }
1920
1921 /// This method restores by the context and value name the context label and
1922 /// sub-label where the value is. Returns true if it is valid.
1923 bool Model_AttributeSelection::restoreContext(std::wstring theName,
1924   TDF_Label& theContext, TDF_Label& theValue)
1925 {
1926   static const GeomShapePtr anEmptyShape; // to store context only
1927   std::wstring aName = theName;
1928   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1929     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1930
1931   // remove the sub-value part if exists
1932   std::wstring aSubShapeName = aName;
1933   std::wstring::size_type n = aName.find(L'/');
1934   if (n != std::wstring::npos) {
1935     aName = aName.substr(0, n);
1936   }
1937
1938   if (aName.empty()) return false;
1939   bool anUniqueContext = false;
1940   ResultPtr aCont = aDoc->findByName(aName, aSubShapeName, anUniqueContext);
1941   if (!aCont.get() || !aCont->shape().get() || aCont->shape()->isNull()) {
1942     // name in PartSet?
1943     aDoc = std::dynamic_pointer_cast<Model_Document>(
1944       ModelAPI_Session::get()->moduleDocument());
1945     if (theName.find(Locale::Convert::toWString(aDoc->kind())) == 0) {
1946       // remove the document identifier from name if exists
1947       aSubShapeName = theName.substr(aDoc->kind().size() + 1);
1948       aName = aSubShapeName;
1949       n = aName.find(L'/');
1950       if (n != std::wstring::npos) {
1951         aName = aName.substr(0, n);
1952       }
1953     }
1954     aCont = aDoc->findByName(aName, aSubShapeName, anUniqueContext);
1955     if (!aCont.get() || !aCont->shape().get() || aCont->shape()->isNull())
1956       return false;
1957   }
1958
1959   // searching the sub-shape
1960   static const ResultPtr anEmpty;
1961   theValue = aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
1962
1963   // sketch sub-component shape and name is located in separated feature label, try the sub-name
1964   if (theValue.IsNull() && aCont->groupName() == ModelAPI_ResultConstruction::group()) {
1965     std::wstring::size_type aSlash = aSubShapeName.rfind(L'/');
1966     if (aSlash != std::wstring::npos) {
1967       std::wstring aCompName = aSubShapeName.substr(aSlash + 1);
1968       CompositeFeaturePtr aComposite =
1969         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aCont));
1970       if (aComposite.get() && aComposite->numberOfSubs()) {
1971         const int aSubNum = aComposite->numberOfSubs();
1972         for (int a = 0; a < aSubNum && theValue.IsNull(); a++) {
1973           FeaturePtr aSub = aComposite->subFeature(a);
1974           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
1975           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
1976           for (; aRes != aResults.cend() && theValue.IsNull(); aRes++) {
1977             if ((*aRes)->data()->name() == aCompName) {
1978               theValue = std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->shapeLab();
1979               break;
1980             } else { // any sub-label because the sketch line may be renamed, but not sub-vertices
1981               TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->shapeLab();
1982               TDF_ChildIDIterator aSubNames(aLab, TDataStd_Name::GetID());
1983               for(; aSubNames.More(); aSubNames.Next()) {
1984                 if (Handle(TDataStd_Name)::DownCast(aSubNames.Value())->Get().
1985                   IsEqual(aCompName.c_str())) {
1986                   theValue = aSubNames.Value()->Label();
1987                   break;
1988                 }
1989               }
1990             }
1991           }
1992         }
1993       }
1994     }
1995   }
1996
1997   if (aCont.get()) {
1998     theContext = std::dynamic_pointer_cast<Model_Data>(aCont->data())->label();
1999   }
2000   return true;
2001 }
2002
2003 bool Model_AttributeSelection::isLater(
2004   const TDF_Label theResult1, const TDF_Label theResult2) const
2005 {
2006   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
2007     std::dynamic_pointer_cast<Model_Document>(owner()->document());
2008   FeaturePtr aFeat1 = aDoc->featureByLab(theResult1);
2009   if (!aFeat1.get())
2010     return false;
2011   FeaturePtr aFeat2 = aDoc->featureByLab(theResult2);
2012   if (!aFeat2.get())
2013     return false;
2014   return aDoc->isLaterByDep(aFeat1, aFeat2);
2015 }
2016
2017 ResultPtr Model_AttributeSelection::newestContext(
2018   const ResultPtr theCurrent, const GeomShapePtr theValue)
2019 {
2020   ResultPtr aResult = theCurrent;
2021   GeomShapePtr aSelectedShape = theValue.get() ? theValue : theCurrent->shape();
2022   std::shared_ptr<Model_Document> aDoc =
2023     std::dynamic_pointer_cast<Model_Document>(owner()->document());
2024   bool aFindNewContext = true;
2025   while (aFindNewContext && aResult.get()) {
2026     aFindNewContext = false;
2027     // try to find the last context to find the up to date shape
2028     TopoDS_Shape aConShape = aResult->shape()->impl<TopoDS_Shape>();
2029     if (TNaming_Tool::HasLabel(selectionLabel(), aConShape)) {
2030       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
2031       if (!aNS.IsNull()) {
2032         aNS = TNaming_Tool::CurrentNamedShape(aNS);
2033         if (!aNS.IsNull()
2034             && isLater(selectionLabel(), aNS->Label())
2035             && isLater(aNS->Label(),
2036                        std::dynamic_pointer_cast<Model_Data>(aResult->data())->label()))
2037         {
2038           TDF_Label aLab = aNS->Label();
2039           ResultPtr aRes = aDoc->resultByLab(aLab);
2040           if (aRes.get()) {
2041             if (aRes->shape()->isSubShape(aSelectedShape)) {
2042               aResult = aRes;
2043               aFindNewContext = true;
2044               continue;
2045             }
2046           }
2047         }
2048       }
2049     }
2050
2051     // TestFillWireVertex.py - sketch constructions for wire may participate too
2052     //if (aResult->groupName() == ModelAPI_ResultBody::group()) {
2053       // try to search newer context by the concealment references
2054       // take references to all results: root one, any sub
2055     std::list<DataPtr> allRes;
2056     ResultPtr aCompContext;
2057     ResultBodyPtr aCompBody = ModelAPI_Tools::bodyOwner(aResult, true);
2058     if (aCompBody.get()) {
2059       std::list<ResultPtr> allSub;
2060       ModelAPI_Tools::allSubs(aCompBody, allSub);
2061       for(std::list<ResultPtr>::iterator anIt = allSub.begin(); anIt != allSub.end(); anIt++)
2062         allRes.push_back((*anIt)->data());
2063       allRes.push_back(aCompBody->data());
2064       aCompContext = aCompBody;
2065     }
2066     if (allRes.empty())
2067       allRes.push_back(aResult->data());
2068     allRes.push_back(aResult->document()->feature(aResult)->data());
2069
2070     bool aFoundReferernce = false;
2071     for (std::list<DataPtr>::iterator aSub = allRes.begin(); aSub != allRes.end(); aSub++) {
2072       DataPtr aResCont = *aSub;
2073       ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResCont->owner());
2074       if (aResBody.get() && aResBody->numberOfSubs() > 0 && aResBody != aCompContext)
2075         continue; // only lower and higher level subs are counted
2076       const std::set<AttributePtr>& aRefs = aResCont->refsToMe();
2077       std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
2078       for (; !aFindNewContext && aRef != aRefs.end(); aRef++) {
2079         if (!aRef->get() || !(*aRef)->owner().get())
2080           continue;
2081         // concealed attribute only
2082         FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
2083         if (!ModelAPI_Session::get()->validators()->isConcealed(
2084           aRefFeat->getKind(), (*aRef)->id()))
2085           continue;
2086         // search the feature result that contains sub-shape selected
2087         std::list<std::shared_ptr<ModelAPI_Result> > aResults;
2088
2089         // take all sub-results or one result
2090         std::list<ResultPtr> aRefFeatResults;
2091         ModelAPI_Tools::allResults(aRefFeat, aRefFeatResults);
2092         std::list<ResultPtr>::iterator aRefResIter = aRefFeatResults.begin();
2093         for (; aRefResIter != aRefFeatResults.end(); aRefResIter++) {
2094           ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRefResIter);
2095           if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
2096             aResults.push_back(aBody);
2097         }
2098         std::list<std::shared_ptr<ModelAPI_Result> >::iterator aResIter = aResults.begin();
2099
2100         // searching by sub-shape
2101         for (; aResIter != aResults.end(); aResIter++) {
2102           if (!aResIter->get() || !(*aResIter)->data()->isValid() || (*aResIter)->isDisabled())
2103             continue;
2104           aFoundReferernce = true;
2105           GeomShapePtr aShape = (*aResIter)->shape();
2106           if (aShape.get() && aShape->isSubShape(aSelectedShape, false)) {
2107             aResult = *aResIter; // found new context (produced from this) with same subshape
2108             aFindNewContext = true; // continue searching further
2109             break;
2110           }
2111         }
2112       }
2113     }
2114     if (aFoundReferernce && !aFindNewContext &&
2115         aResult->groupName() != ModelAPI_ResultConstruction::group()) {
2116       // #19019 : result is concealed by object that contains no such sub-shape
2117       return theCurrent;
2118     }
2119   }
2120   // if compsolid is context, try to take sub-solid as context: like in GUI and scripts
2121   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
2122   if (aComp && aComp->numberOfSubs()) {
2123     std::list<ResultPtr> allSubs;
2124     ModelAPI_Tools::allSubs(aComp, allSubs);
2125     std::list<ResultPtr>::iterator aS = allSubs.begin();
2126     for (; aS != allSubs.end(); aS++) {
2127       ResultBodyPtr aSub = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aS);
2128       if (aSub && aSub->numberOfSubs() == 0 && aSub->shape().get() &&
2129           aSub->shape()->isSubShape(aSelectedShape)) {
2130         aResult = aSub;
2131         break;
2132       }
2133     }
2134   }
2135   // in case sketch line was selected for wire, but wire was concealed and there is no such line
2136   // anymore, so, actually, the sketch element was selected (which is never concealed)
2137   if (aResult != theCurrent && theCurrent->groupName() == ModelAPI_ResultConstruction::group()) {
2138     std::list<FeaturePtr> aConcealers;
2139     FeaturePtr aResFeature = aDoc->feature(aResult);
2140     FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
2141     concealedFeature(aResFeature, aThisFeature, false, aConcealers, aResult, true);
2142     if (aConcealers.size())
2143       aResult = theCurrent;
2144   }
2145   return aResult;
2146 }
2147
2148 void Model_AttributeSelection::combineGeometrical()
2149 {
2150   if (myTmpContext.get() || myTmpSubShape.get())
2151     return;
2152   TDF_Label aSelLab = selectionLabel();
2153   if (aSelLab.IsAttribute(kINVALID_SELECTION) || !myRef.isInitialized())
2154     return;
2155
2156   if (aSelLab.IsAttribute(kCIRCLE_CENTER) || aSelLab.IsAttribute(kELLIPSE_CENTER1) ||
2157       aSelLab.IsAttribute(kELLIPSE_CENTER2) || aSelLab.IsAttribute(kSIMPLE_REF_ID))
2158     return;
2159
2160   if (aSelLab.IsAttribute(kPART_REF_ID)) {
2161     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
2162     if (!aPart.get() || !aPart->isActivated())
2163       return; // postponed naming needed
2164     Handle(TDataStd_Integer) anIndex;
2165     if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
2166       if (anIndex->Get()) { // special selection attribute was created, use it
2167         std::wstring aNewName;
2168         aPart->combineGeometrical(anIndex->Get(), aNewName);
2169         TDataStd_Name::Set(aSelLab, aNewName.c_str());
2170       }
2171     }
2172     return;
2173   }
2174
2175   std::shared_ptr<Model_ResultConstruction> aConstr =
2176     std::dynamic_pointer_cast<Model_ResultConstruction>(context());
2177   if (aConstr.get())
2178     return;
2179   FeaturePtr aFeature = contextFeature();
2180   if (aFeature.get())
2181     return;
2182
2183   Selector_Selector aSelector(aSelLab, baseDocumentLab());
2184   TopoDS_Shape aContextShape = context()->shape()->impl<TopoDS_Shape>();
2185   if (aSelector.restore(aContextShape)) {
2186     aSelector.combineGeometrical(aContextShape);
2187   }
2188 }
2189
2190 TDF_Label Model_AttributeSelection::baseDocumentLab()
2191 {
2192   if (ModelAPI_Session::get()->moduleDocument() != owner()->document())
2193     return std::dynamic_pointer_cast<Model_Document>
2194       (ModelAPI_Session::get()->moduleDocument())->extConstructionsLabel();
2195   static TDF_Label anEmpty;
2196   return anEmpty;
2197 }
2198
2199 void Model_AttributeSelection::reset()
2200 {
2201   ModelAPI_AttributeSelection::reset();
2202   myRef.reset();
2203 }