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