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