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