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