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