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