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