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