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