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