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