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