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