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