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