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