]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
Fix the problem with renamed sketch edges vertices selection (the stator_ermes case)
[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 not 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 to select 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 should not be 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 /// integer that contains the tag number of external construction shape naming
709 static Standard_GUID kEXTERNAL_CONSTRUCTION_TAG("f7d0726f-e848-4d22-9101-def16d0eff2c");
710
711 void Model_AttributeSelection::storeExternalConstruction(
712   const ResultConstructionPtr& theConstruction, const GeomShapePtr& theSubShape)
713 {
714   std::string aName = namingName();
715   if (aName.empty()) // unknown error
716     return;
717   std::shared_ptr<Model_Document> aMyDoc =
718     std::dynamic_pointer_cast<Model_Document>(owner()->document());
719   TDF_Label anExternalLab = aMyDoc->extConstructionsLabel();
720   Handle(TDataStd_Integer) anExtTag;
721   if (selectionLabel().FindAttribute(kEXTERNAL_CONSTRUCTION_TAG, anExtTag)) {
722     anExternalLab = anExternalLab.FindChild(anExtTag->Get()); // use existing label
723   } else {
724     // search label with the same name
725     TDF_ChildIDIterator aNamesIter(anExternalLab, TDataStd_Name::GetID());
726     for(; aNamesIter.More(); aNamesIter.Next()) {
727       if (aName == TCollection_AsciiString(Handle(TDataStd_Name)::DownCast(
728         aNamesIter.Value())->Get()).ToCString()) {
729         anExternalLab = aNamesIter.Value()->Label();
730         break;
731       }
732     }
733     if (aNamesIter.More()) {
734     } else {
735       anExternalLab = anExternalLab.NewChild(); // create new label
736       TDataStd_Integer::Set(selectionLabel(), kEXTERNAL_CONSTRUCTION_TAG,
737         anExternalLab.Tag()); // store this tag in the data model
738     }
739   }
740   anExternalLab.ForgetAllAttributes();
741   TopoDS_Shape aSubShape = theSubShape->impl<TopoDS_Shape>();
742   TNaming_Builder aBuilder(anExternalLab);
743   aBuilder.Generated(aSubShape);
744 }
745
746 void Model_AttributeSelection::selectBody(
747   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
748 {
749   // perform the selection
750   TopoDS_Shape aContext;
751
752   ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);//myRef.value()
753   if (aBody) {
754     aContext = aBody->shape()->impl<TopoDS_Shape>();
755   } else {
756     ResultPtr aResult =
757       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
758     if (aResult) {
759       aContext = aResult->shape()->impl<TopoDS_Shape>();
760     } else {
761       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
762       return;
763     }
764   }
765
766   if (!aContext.IsNull()) {
767     TDF_Label aSelLab = selectionLabel();
768     TopoDS_Shape aNewSub = theSubShape->impl<TopoDS_Shape>();
769     FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
770     if (aFeatureOwner->document() != theContext->document()) { // reference to the sketch face
771       if (theSubShape->shapeType() == GeomAPI_Shape::FACE ||
772           theSubShape->shapeType() == GeomAPI_Shape::WIRE) { // sketch face or sketch face wire
773         ResultConstructionPtr aConstr =
774           std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
775         int aFaceIndex = -1, aFacesNum = aConstr->facesNum();
776         for(int a = 0; a < aFacesNum; a++) {
777           bool isEqual = false;
778           GeomShapePtr aFace = aConstr->face(a);
779           if (!aFace.get() || aFace->isNull())
780             continue;
781           if (theSubShape->shapeType() == GeomAPI_Shape::FACE) {
782             isEqual = aFace->isEqual(theSubShape);
783           } else {
784             GeomAPI_ShapeExplorer anExp(aFace, GeomAPI_Shape::WIRE);
785             if (anExp.more())
786               isEqual = anExp.current()->isEqual(theSubShape);
787           }
788           if (isEqual) {
789             aFaceIndex = a;
790             break;
791           }
792         }
793         if (aFaceIndex >= 0) {
794           TDataStd_Integer::Set(aSelLab, theSubShape->shapeType() == GeomAPI_Shape::FACE ?
795             kEXT_SKETCH_FACE : kEXT_SKETCH_WIRE, aFaceIndex); // store index of the face
796           //storeExternalConstruction(aConstr, theSubShape);
797           return;
798         }
799       } else if (theSubShape->shapeType() == GeomAPI_Shape::EDGE ||// sketch result edge (full one)
800                  theSubShape->shapeType() == GeomAPI_Shape::VERTEX) { // or start/end vertex
801         bool isVertex = theSubShape->shapeType() == GeomAPI_Shape::VERTEX;
802         CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(
803           theContext->document()->feature(theContext));
804         if (aComposite.get()) { // iterate edges of composite to find index of matched with value
805           int aSub, anEdgeIndex = -1, aSubNum = aComposite->numberOfSubs();
806           int aVertIndex = -1, aVertShape = -1; // shape: 0 full, 1 start, 2 end
807           for(aSub = 0; aSub < aSubNum && anEdgeIndex == -1; aSub++) {
808             FeaturePtr aSubFeat = aComposite->subFeature(aSub);
809             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSubFeat->results();
810             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
811             for (; aRes != aResults.cend(); aRes++) {
812               ResultConstructionPtr aConstr =
813                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
814               if (aConstr->shape() && aConstr->shape()->isEdge()) {
815                 if (isVertex) {
816                   GeomAPI_ShapeExplorer aVertExp(aConstr->shape(), GeomAPI_Shape::VERTEX);
817                   for(int aNum = 1; aVertExp.more(); aVertExp.next(), aNum++) {
818                     if (aVertExp.current()->isSame(theSubShape) && aVertShape != 0) {
819                       aVertIndex = aSub;
820                       aVertShape = aNum;
821                     }
822                   }
823                 } else {
824                   if (aConstr->shape()->isSame(theSubShape)) {
825                     anEdgeIndex = aSub;
826                     break;
827                   }
828                 }
829               } else if (isVertex && aConstr->shape() && aConstr->shape()->isVertex()) {
830                 if (aConstr->shape()->isSame(theSubShape)) {
831                   aVertIndex = aSub;
832                   aVertShape = 0;
833                 }
834               }
835             }
836           }
837           if (anEdgeIndex >= 0) {
838             TDataStd_Integer::Set(aSelLab, kEXT_SKETCH_EDGE, anEdgeIndex); // store index of edge
839             return;
840           } else if (aVertIndex >= 0) {
841             aVertIndex += aVertShape * 1000000; // to store both integers: index and shape
842             TDataStd_Integer::Set(aSelLab, kEXT_SKETCH_VERT, aVertIndex); // store index of edge
843             return;
844           }
845         }
846       }
847     }
848     bool aSelectorOk = true;
849     Selector_Selector aSel(aSelLab);
850     try {
851       aSelectorOk = aSel.select(aContext, aNewSub);
852       if (aSelectorOk) {
853         aSel.store();
854         aSelectorOk = aSel.solve(aContext);
855       }
856     } catch(...) {
857       aSelectorOk = false;
858     }
859     Handle(TNaming_NamedShape) aSelectorShape;
860     if (aSelectorOk && aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aSelectorShape))
861     {
862       TopoDS_Shape aShape = aSelectorShape->Get();
863       if (aShape.IsNull() || aShape.ShapeType() != aNewSub.ShapeType())
864         aSelectorOk = false;
865     }
866     if (!aSelectorOk) {
867       setInvalidIfFalse(aSelLab, false);
868     }
869   }
870 }
871
872 bool Model_AttributeSelection::selectPart(
873   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
874   const bool theUpdate)
875 {
876   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
877   if (!aPart.get() || !aPart->isActivated())
878     return true; // postponed naming
879   if (theUpdate) {
880     Handle(TDataStd_Integer) anIndex;
881     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
882       // by internal selection
883       if (anIndex->Get() > 0) {
884         // update the selection by index
885         return aPart->updateInPart(anIndex->Get());
886       } else {
887         return true; // nothing to do, referencing just by name
888       }
889     }
890     return true; // nothing to do, referencing just by name
891   }
892   // store the shape (in case part is not loaded it should be useful
893   TopoDS_Shape aShape;
894   std::string aName = theContext->data()->name();
895   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
896     aShape = theContext->shape()->impl<TopoDS_Shape>();
897   } else {
898     aShape = theSubShape->impl<TopoDS_Shape>();
899     int anIndex;
900     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
901     TDataStd_Integer::Set(selectionLabel(), anIndex);
902   }
903   TNaming_Builder aBuilder(selectionLabel());
904   aBuilder.Select(aShape, aShape);
905   // identify by name in the part
906   TDataStd_Name::Set(selectionLabel(), aName.c_str());
907   return !aName.empty();
908 }
909
910 TDF_Label Model_AttributeSelection::selectionLabel()
911 {
912   return myRef.myRef->Label().FindChild(1);
913 }
914
915 /// prefixes of the shape names with centers defined
916 static std::map<ModelAPI_AttributeSelection::CenterType, std::string> kCENTERS_PREFIX;
917
918 /// returns the map that contains all possible prefixes of the center-names
919 static std::map<ModelAPI_AttributeSelection::CenterType, std::string>& centersMap()
920 {
921   if (kCENTERS_PREFIX.empty()) { // fill map by initial values
922     kCENTERS_PREFIX[ModelAPI_AttributeSelection::CIRCLE_CENTER] = "__cc";
923     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS] = "__eff";
924     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_SECOND_FOCUS] = "__esf";
925   }
926   return kCENTERS_PREFIX;
927 }
928
929 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
930 {
931   std::string aName("");
932   if(!this->isInitialized())
933     return !theDefaultName.empty() ? theDefaultName : aName;
934
935   CenterType aCenterType = NOT_CENTER;
936   std::shared_ptr<GeomAPI_Shape> aSubSh = internalValue(aCenterType);
937   ResultPtr aCont = context();
938
939   if (!aCont.get() ||
940       (aCont->groupName() == ModelAPI_ResultConstruction::group() && contextFeature().get())) {
941     // selection of a full feature
942     FeaturePtr aFeatureCont = contextFeature();
943     if (aFeatureCont.get()) {
944       return kWHOLE_FEATURE + aFeatureCont->name();
945     }
946     // in case of selection of removed result
947     return "";
948   }
949
950   TDF_Label aSelLab = selectionLabel();
951   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // whole context, no value
952     return contextName(aCont);
953   }
954
955   // if it is in result of another part
956   if (aCont->groupName() == ModelAPI_ResultPart::group()) {
957     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aCont);
958     int anIndex;
959     GeomShapePtr aValue = value();
960     if (aValue.get())
961       return aPart->data()->name() + "/" + aPart->nameInPart(aValue, anIndex);
962     else
963       return aPart->data()->name();
964   }
965
966
967   // whole infinitive construction
968   if (aCont->groupName() == ModelAPI_ResultConstruction::group()) {
969     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<Model_ResultConstruction>(aCont);
970     if (aConstr->isInfinite()) {
971       return contextName(aCont);
972     } else {
973       // external sketch face
974       Handle(TDataStd_Integer) anIndex;
975       if (aSelLab.FindAttribute(kEXT_SKETCH_FACE, anIndex) ||
976           aSelLab.FindAttribute(kEXT_SKETCH_WIRE, anIndex) ||
977           aSelLab.FindAttribute(kEXT_SKETCH_EDGE, anIndex) ||
978           aSelLab.FindAttribute(kEXT_SKETCH_VERT, anIndex)) {
979         std::shared_ptr<Model_Document> anExtDoc =
980           std::dynamic_pointer_cast<Model_Document>(aCont->document());
981         Selector_Selector aSelector(anExtDoc->extConstructionsLabel());
982         TopoDS_Shape aContShape = aConstr->shape()->impl<TopoDS_Shape>();
983         TopoDS_Shape aValShape = value()->impl<TopoDS_Shape>();
984         aSelector.select(aContShape, aValShape);
985         myRestoreDocument = anExtDoc;
986         std::string aName = anExtDoc->kind() + "/" + aSelector.name(this);
987         myRestoreDocument.reset();
988         return aName;
989       }
990     }
991   }
992
993   Selector_Selector aSelector(aSelLab);
994   std::string aResult;
995   if (aSelector.restore())
996     aResult = aSelector.name(this);
997   /*
998   Model_SelectionNaming aSelNaming(aSelLab);
999   std::string aResult = aSelNaming.namingName(
1000     aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
1001     */
1002   if (aCenterType != NOT_CENTER) {
1003     aResult += centersMap()[aCenterType];
1004   }
1005   return aResult;
1006 }
1007
1008 // returns the center type and modifies the shape name if this name is center-name
1009 static ModelAPI_AttributeSelection::CenterType centerTypeByName(std::string& theShapeName)
1010 {
1011   std::map<ModelAPI_AttributeSelection::CenterType, std::string>::iterator aPrefixIter =
1012     centersMap().begin();
1013   for(; aPrefixIter != centersMap().end(); aPrefixIter++) {
1014     std::size_t aFound = theShapeName.find(aPrefixIter->second);
1015     if (aFound != std::string::npos &&
1016         aFound == theShapeName.size() - aPrefixIter->second.size()) {
1017       theShapeName = theShapeName.substr(0, aFound);
1018       return aPrefixIter->first;
1019     }
1020   }
1021   return ModelAPI_AttributeSelection::NOT_CENTER;
1022 }
1023
1024 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
1025 void Model_AttributeSelection::selectSubShape(
1026   const std::string& theType, const std::string& theSubShapeName)
1027 {
1028   if(theSubShapeName.empty() || theType.empty()) return;
1029
1030   std::string aSubShapeName = theSubShapeName;
1031   CenterType aCenterType = theType[0] == 'v' || theType[0] == 'V' ? // only for vertex-type
1032     centerTypeByName(aSubShapeName) : NOT_CENTER;
1033   std::string aType = aCenterType == NOT_CENTER ? theType : "EDGE"; // search for edge now
1034   static const GeomShapePtr anEmptyShape;
1035
1036   // first iteration is selection by name without center prefix, second - in case of problem,
1037   // try with initial name
1038   for(int aUseCenter = 1; aUseCenter >= 0; aUseCenter--)  {
1039     if (aUseCenter == 0 && aCenterType != NOT_CENTER) {
1040       aSubShapeName = theSubShapeName;
1041       aCenterType = NOT_CENTER;
1042       aType = theType;
1043     } else if (aUseCenter != 1) continue;
1044     TopAbs_ShapeEnum aShapeType =  TopAbs_ShapeEnum(GeomAPI_Shape::shapeTypeByStr(aType));
1045
1046     std::shared_ptr<Model_Document> aDoc =
1047       std::dynamic_pointer_cast<Model_Document>(owner()->document());
1048     // check this is Part-name: 2 delimiters in the name
1049     std::size_t aPartEnd = aSubShapeName.find('/');
1050     if (aPartEnd != std::string::npos) {
1051       std::string aPartName = aSubShapeName.substr(0, aPartEnd);
1052       DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
1053       if (aPartName == aRootDoc->kind()) {
1054         aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
1055         aSubShapeName = aSubShapeName.substr(aPartEnd + 1);
1056       } else {
1057         ObjectPtr aFound =
1058           owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
1059         if (aFound.get()) { // found such part, so asking it for the name
1060           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
1061           aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
1062           aSubShapeName = aSubShapeName.substr(aPartEnd +1);
1063           if (aSubShapeName.empty()) { // the whole Part result
1064             setValue(aPart, anEmptyShape);
1065             return;
1066           }
1067         }
1068       }
1069     }
1070
1071     // check this is a whole feature context
1072     if (aSubShapeName.size() > kWHOLE_FEATURE.size() &&
1073       aSubShapeName.substr(0, kWHOLE_FEATURE.size()) == kWHOLE_FEATURE) {
1074       std::string aFeatureName = aSubShapeName.substr(kWHOLE_FEATURE.size());
1075       ObjectPtr anObj = aDoc->objectByName(ModelAPI_Feature::group(), aFeatureName);
1076       if (anObj.get()) {
1077         setValue(anObj, anEmptyShape);
1078         return;
1079       }
1080     }
1081
1082     // the whole result selection check
1083     if (aSubShapeName.find('/') == std::string::npos) {
1084       ObjectPtr aRes = aDoc->objectByName(ModelAPI_ResultConstruction::group(), aSubShapeName);
1085       if (!aRes.get())
1086         aRes = aDoc->objectByName(ModelAPI_ResultBody::group(), aSubShapeName);
1087       if (aRes.get()) {
1088         setValue(aRes, anEmptyShape);
1089         return;
1090       }
1091     }
1092
1093     Selector_Selector aSelector(aDoc->generalLabel());
1094     myRestoreDocument = aDoc;
1095     TDF_Label aContextLabel = aSelector.restoreByName(aSubShapeName, aShapeType, this);
1096     myRestoreDocument.reset();
1097     if (!aContextLabel.IsNull()) {
1098       ResultPtr aContext = aDoc->resultByLab(aContextLabel); // any label for document access
1099       if (aContext.get() && aContext->shape().get()) {
1100         TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
1101         if (aSelector.solve(aContextShape)) {
1102           TopoDS_Shape aSelectorShape = aSelector.value();
1103           GeomShapePtr aShapeToBeSelected(new GeomAPI_Shape);
1104           aShapeToBeSelected->setImpl<TopoDS_Shape>(new TopoDS_Shape(aSelectorShape));
1105           // make the context result the latest existing
1106           aContext = newestContext(aContext, aShapeToBeSelected);
1107           if (aCenterType != NOT_CENTER) {
1108             if (!aShapeToBeSelected->isEdge())
1109               continue;
1110             std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aShapeToBeSelected));
1111             setValueCenter(aContext, aSelectedEdge, aCenterType);
1112           }
1113           else
1114             setValue(aContext, aShapeToBeSelected);
1115           return;
1116         }
1117       }
1118     }
1119   }
1120   // invalid
1121   TDF_Label aSelLab = selectionLabel();
1122   setInvalidIfFalse(aSelLab, false);
1123   reset();
1124 }
1125
1126 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1127                                               const GeomPointPtr& thePoint)
1128 {
1129   if (theType.empty() || !thePoint)
1130     return;
1131
1132   // list of parent features
1133   FeaturePtr anOwner = ModelAPI_Feature::feature(owner());
1134   std::set<FeaturePtr> aParents = ModelAPI_Tools::getParents(anOwner);
1135
1136   int aSelectionIndex = 0;
1137   GeomAPI_Shape::ShapeType aType = GeomAPI_Shape::shapeTypeByStr(theType);
1138   if (aType == GeomAPI_Shape::SHAPE) {
1139     // possibly, the string consists of the type and the index,
1140     // thus, try to separate them
1141     size_t aUndersporePos = theType.find_first_of('_');
1142     if (aUndersporePos != std::string::npos)
1143       aType = GeomAPI_Shape::shapeTypeByStr(theType.substr(0, aUndersporePos));
1144
1145     if (aType != GeomAPI_Shape::SHAPE) {
1146       for (std::string::const_iterator aChar = theType.begin() + aUndersporePos + 1;
1147            aChar != theType.end(); ++aChar) {
1148         if (std::isdigit(*aChar))
1149           aSelectionIndex = aSelectionIndex * 10 + (*aChar - '0');
1150         else {
1151           aSelectionIndex = 1;
1152           break;
1153         }
1154       }
1155       aSelectionIndex -= 1;
1156     }
1157   }
1158
1159   std::list<ModelGeomAlgo_Shape::SubshapeOfResult> anAppropriate;
1160
1161   // collect features from PartSet and the current part
1162   SessionPtr aSession = ModelAPI_Session::get();
1163   std::list<FeaturePtr> aFeatures = aSession->moduleDocument()->allFeatures();
1164   if (aSession->moduleDocument() != owner()->document()) {
1165     std::list<FeaturePtr> aPartFeatures = owner()->document()->allFeatures();
1166     aFeatures.insert(aFeatures.end(), aPartFeatures.begin(), aPartFeatures.end());
1167   }
1168   // Process results of all features from the last to the first
1169   // to find appropriate sub-shape
1170   for (std::list<FeaturePtr>::const_reverse_iterator anIt = aFeatures.rbegin();
1171        anIt != aFeatures.rend(); ++anIt) {
1172     // selection cannot be linked to the parent features
1173     if (aParents.find(*anIt) != aParents.end())
1174       continue;
1175     // check the feature is a part of composite feature (like sketch elements),
1176     // then do not process it, it will be processed in scope of composite feature
1177     bool isSubOfComposite = false;
1178     const std::set<AttributePtr>& aRefs = (*anIt)->data()->refsToMe();
1179     for (std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
1180          aRefIt != aRefs.end() && !isSubOfComposite; ++aRefIt) {
1181       FeaturePtr aFeature = ModelAPI_Feature::feature((*aRefIt)->owner());
1182       CompositeFeaturePtr aCompFeature =
1183           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
1184       isSubOfComposite = aCompFeature && aCompFeature->isSub(*anIt);
1185     }
1186     if (isSubOfComposite)
1187       continue;
1188
1189     // process results of the current feature to find appropriate sub-shape
1190     if (ModelGeomAlgo_Shape::findSubshapeByPoint(*anIt, thePoint, aType, anAppropriate)) {
1191       std::list<ModelGeomAlgo_Shape::SubshapeOfResult>::iterator anApIt = anAppropriate.begin();
1192       for (; aSelectionIndex > 0 && anApIt != anAppropriate.end(); --aSelectionIndex)
1193         ++anApIt; // skip this shape, because one of the previous is selected
1194
1195       if (anApIt != anAppropriate.end()) {
1196         if (anApIt->myCenterType == (int)ModelAPI_AttributeSelection::NOT_CENTER)
1197           setValue(anApIt->myResult, anApIt->mySubshape);
1198         else
1199           setValueCenter(anApIt->myResult, anApIt->mySubshape->edge(),
1200                          (ModelAPI_AttributeSelection::CenterType)anApIt->myCenterType);
1201         return;
1202       }
1203     }
1204   }
1205
1206   TDF_Label aSelLab = selectionLabel();
1207   setInvalidIfFalse(aSelLab, false);
1208   reset();
1209 }
1210
1211 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1212   const std::string& theContextName, const int theIndex)
1213 {
1214   // selection of context by name
1215   selectSubShape(theType, theContextName);
1216   ResultPtr aContext = context();
1217   if (aContext.get()) {
1218     GeomShapePtr aContShape = aContext->shape();
1219     if (aContShape.get()) {
1220       GeomAlgoAPI_NExplode aNExp(aContShape, GeomAPI_Shape::shapeTypeByStr(theType));
1221       GeomShapePtr aValue = aNExp.shape(theIndex);
1222       if (aValue.get())
1223         setValue(aContext, aValue);
1224     }
1225   }
1226 }
1227
1228 int Model_AttributeSelection::Id()
1229 {
1230   int anID = 0;
1231   std::shared_ptr<GeomAPI_Shape> aSelection = value();
1232   ResultPtr aContextRes = context();
1233   // support for compsolids:
1234   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1235     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1236   }
1237   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1238
1239
1240   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1241   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1242   // searching for the latest main shape
1243   if (aSelection && !aSelection->isNull() && aContext && !aContext->isNull())
1244   {
1245     std::shared_ptr<Model_Document> aDoc =
1246       std::dynamic_pointer_cast<Model_Document>(context()->document());
1247     if (aDoc.get()) {
1248       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1249       if (!aNS.IsNull()) {
1250         aMainShape = TNaming_Tool::CurrentShape(aNS);
1251       }
1252     }
1253
1254     TopTools_IndexedMapOfShape aSubShapesMap;
1255     TopExp::MapShapes(aMainShape, aSubShapesMap);
1256     anID = aSubShapesMap.FindIndex(aSubShape);
1257   }
1258   return anID;
1259 }
1260
1261 void Model_AttributeSelection::setId(int theID)
1262 {
1263   std::shared_ptr<GeomAPI_Shape> aSelection;
1264
1265   ResultPtr aContextRes = context();
1266   // support for compsolids:
1267   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1268     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1269   }
1270   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1271
1272   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1273   // searching for the latest main shape
1274   if (theID > 0 && aContext && !aContext->isNull())
1275   {
1276     std::shared_ptr<Model_Document> aDoc =
1277       std::dynamic_pointer_cast<Model_Document>(aContextRes->document());
1278     if (aDoc.get()) {
1279       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1280       if (!aNS.IsNull()) {
1281         aMainShape = TNaming_Tool::CurrentShape(aNS);
1282       }
1283     }
1284
1285     TopTools_IndexedMapOfShape aSubShapesMap;
1286     TopExp::MapShapes(aMainShape, aSubShapesMap);
1287     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1288
1289     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1290     aResult->setImpl(new TopoDS_Shape(aSelShape));
1291
1292     aSelection = aResult;
1293   }
1294
1295   setValue(aContextRes, aSelection);
1296 }
1297
1298 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1299 {
1300   std::string aResult;
1301   if (owner()->document() != theContext->document()) {
1302     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1303       aResult = theContext->document()->kind() + "/";
1304     } else {
1305       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1306         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1307       if (aDocRes.get()) {
1308         aResult = aDocRes->data()->name() + "/";
1309       }
1310     }
1311   }
1312   aResult += theContext->data()->name();
1313   return aResult;
1314 }
1315
1316 void Model_AttributeSelection::computeValues(
1317   ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
1318   TopTools_ListOfShape& theShapes)
1319 {
1320   bool aWasWholeContext = theValShape.IsNull();
1321   if (aWasWholeContext) {
1322     //theShapes.Append(theValShape);
1323     //return;
1324     theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
1325   }
1326   //TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
1327   TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
1328   //if (anOldContShape.IsSame(theValShape)) { // full context shape substituted by new full context
1329     //theShapes.Append(aNewContShape);
1330     //return;
1331   //}
1332   // if a new value is unchanged in the new context, do nothing: value is correct
1333   TopExp_Explorer aSubExp(aNewContShape, theValShape.ShapeType());
1334   for(; aSubExp.More(); aSubExp.Next()) {
1335     if (aSubExp.Current().IsSame(theValShape)) {
1336       theShapes.Append(theValShape);
1337       return;
1338     }
1339   }
1340   // if new context becomes compsolid, the resulting sub may be in sub-solids
1341   std::list<ResultPtr> aNewToIterate;
1342   aNewToIterate.push_back(theNewContext);
1343   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theNewContext);
1344   if (aComp.get()) {
1345     std::list<ResultPtr> allNewContextSubs;
1346     ModelAPI_Tools::allSubs(aComp, allNewContextSubs);
1347     std::list<ResultPtr>::iterator aSub = allNewContextSubs.begin();
1348     for(; aSub != allNewContextSubs.end(); aSub++) {
1349       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aSub);
1350       if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1351         aNewToIterate.push_back(aBody);
1352     }
1353   }
1354
1355   // first iteration: searching for the whole shape appearance (like face of the box)
1356   // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
1357   int aToFindPart = 0;
1358   TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
1359   TopTools_MapOfShape anOlds; // to know how many olds produced new containers
1360   for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
1361     std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
1362     for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
1363       std::shared_ptr<Model_Data> aNewData =
1364         std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
1365       TDF_Label aNewLab = aNewData->shapeLab();
1366       // searching for produced sub-shape fully on some label
1367       TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID(), Standard_True);
1368       for(; aNSIter.More(); aNSIter.Next()) {
1369         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1370         for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
1371           if (aToFindPart == 0) { // search shape is fully inside
1372             if (aPairIter.OldShape().IsSame(theValShape)) {
1373               if (aPairIter.NewShape().IsNull()) {// value was removed
1374                 theShapes.Clear();
1375                 return;
1376               }
1377               theShapes.Append(aPairIter.NewShape());
1378             }
1379           } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
1380             TopExp_Explorer anExp(aPairIter.OldShape(), theValShape.ShapeType());
1381             for(; anExp.More(); anExp.Next()) {
1382               if (anExp.Current().IsSame(theValShape)) { // found a new container
1383                 if (aPairIter.NewShape().IsNull()) {// value was removed
1384                   theShapes.Clear();
1385                   return;
1386                 }
1387                 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
1388                 anOlds.Add(aPairIter.OldShape());
1389                 break;
1390               }
1391             }
1392           }
1393         }
1394       }
1395     }
1396   }
1397   if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
1398     // map of sub-shapes -> number of occurrences of these shapes in containers
1399     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
1400     TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
1401     for(; aContIter.More(); aContIter.Next()) {
1402       TopExp_Explorer aSubExp(aContIter.Key(), theValShape.ShapeType());
1403       for(; aSubExp.More(); aSubExp.Next()) {
1404         if (!aSubs.IsBound(aSubExp.Current())) {
1405           aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
1406         }
1407         // store old to know how many olds produced this shape
1408         aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
1409       }
1410     }
1411     // if sub is appeared same times in containers as the number of old shapes that contain it
1412     int aCountInOld = anOlds.Size();
1413     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
1414       aSubsIter(aSubs);
1415     for(; aSubsIter.More(); aSubsIter.Next()) {
1416       if (aSubsIter.Value().Size() == aCountInOld) {
1417         theShapes.Append(aSubsIter.Key());
1418       }
1419     }
1420   }
1421   if (theShapes.IsEmpty()) { // nothing was changed
1422     theShapes.Append(aWasWholeContext ? TopoDS_Shape() : theValShape);
1423   }
1424 }
1425
1426 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
1427   const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
1428   TDF_Label theAccessLabel,
1429   std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
1430 {
1431   std::set<ResultPtr> aResults; // to avoid duplicates, new context, null if deleted
1432   TopTools_ListOfShape aResContShapes;
1433   // iterate context and shape, but also if it is sub-shape of main shape, check also it
1434   TopTools_ListOfShape aContextList;
1435   aContextList.Append(theContShape);
1436   if (theContext.get()) {
1437     ResultPtr aComposite = ModelAPI_Tools::bodyOwner(theContext);
1438     if (aComposite.get() && aComposite->shape().get() && !aComposite->shape()->isNull())
1439       aContextList.Append(aComposite->shape()->impl<TopoDS_Shape>());
1440   }
1441   for(TopTools_ListOfShape::Iterator aContIter(aContextList); aContIter.More(); aContIter.Next()) {
1442     TNaming_SameShapeIterator aModifIter(aContIter.ChangeValue(), theAccessLabel);
1443     for(; aModifIter.More(); aModifIter.Next()) {
1444       TDF_Label anObjLab = aModifIter.Label().Father();
1445       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1446         (theDoc->objects()->object(anObjLab));
1447       if (!aModifierObj.get()) {
1448         // #2241: shape may be sub-element of new object, not main (shell created from faces)
1449         if (!anObjLab.IsRoot())
1450           aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1451           (theDoc->objects()->object(anObjLab.Father()));
1452         if (!aModifierObj.get())
1453           continue;
1454       }
1455       FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
1456       if (!aModifierFeat.get())
1457         continue;
1458       FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1459       if (aModifierFeat == aThisFeature || !theDoc->isLaterByDep(aThisFeature, aModifierFeat))
1460         continue; // the modifier feature is later than this, so, should not be used
1461       FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
1462       if (aCurrentModifierFeat == aModifierFeat ||
1463         !theDoc->isLaterByDep(aModifierFeat, aCurrentModifierFeat))
1464         continue; // the current modifier is later than the found, so, useless
1465       Handle(TNaming_NamedShape) aNewNS;
1466       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1467       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1468         aResults.insert(aModifierObj);
1469         //TNaming_Iterator aPairIter(aNewNS);
1470         //aResContShapes.Append(aPairIter.NewShape());
1471         aResContShapes.Append(aModifierObj->shape()->impl<TopoDS_Shape>());
1472       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
1473         aResults.insert(ResultPtr());
1474       } else { // not-processed modification => don't support it
1475         continue;
1476       }
1477     }
1478   }
1479   if (aResults.empty())
1480     return false; // no modifications found, must stay the same
1481   // iterate all results to find further modifications
1482   std::set<ResultPtr>::iterator aResIter = aResults.begin();
1483   for(; aResIter != aResults.end(); aResIter++) {
1484     if (aResIter->get() != NULL) {
1485       // compute new values by two contexts: the old and the new
1486       TopTools_ListOfShape aValShapes;
1487       computeValues(theContext, *aResIter, theValShape, aValShapes);
1488
1489       TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
1490       for(; aNewVal.More(); aNewVal.Next()) {
1491         std::list<ResultPtr> aNewRes;
1492         TopTools_ListOfShape aNewUpdatedVal;
1493         TopoDS_Shape aNewValSh = aNewVal.Value();
1494         TopoDS_Shape aNewContShape = (*aResIter)->shape()->impl<TopoDS_Shape>();
1495         if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
1496           aNewValSh.Nullify();
1497         if (searchNewContext(theDoc, aNewContShape, *aResIter, aNewValSh,
1498                              theAccessLabel, aNewRes, aNewUpdatedVal))
1499         {
1500           // append new results instead of the current ones
1501           std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1502           TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1503           for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1504             theResults.push_back(*aNewIter);
1505             theValShapes.Append(aNewUpdVal.Value());
1506           }
1507         } else { // the current result is good
1508           theResults.push_back(*aResIter);
1509           theValShapes.Append(aNewValSh);
1510         }
1511       }
1512     }
1513   }
1514   return true; // theResults must be empty: everything is deleted
1515 }
1516
1517 void Model_AttributeSelection::updateInHistory()
1518 {
1519   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1520   // only bodies and parts may be modified later in the history, don't do anything otherwise
1521   if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
1522       aContext->groupName() != ModelAPI_ResultPart::group()))
1523     return;
1524   std::shared_ptr<Model_Document> aDoc =
1525     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1526   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1527   if (!aContData.get() || !aContData->isValid())
1528     return;
1529   TDF_Label aContLab = aContData->shapeLab(); // named shape where the selected context is located
1530   Handle(TNaming_NamedShape) aContNS;
1531   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
1532     bool aFoundNewContext = true;
1533     ResultPtr aNewContext = aContext;
1534     while(aFoundNewContext) {
1535       aFoundNewContext = false;
1536       // parts have no shape in result, so, trace references using the Part info
1537       if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
1538         ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
1539         if (aPartContext.get()) { // searching for the up to date references to the referenced cont
1540           const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
1541           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1542           for(; aRef != aRefs.end(); aRef++) {
1543             // to avoid detection of part changes by local selection only
1544             AttributeSelectionPtr aSel =
1545               std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1546             if (aSel.get() && aSel->value().get() &&
1547                 !aSel->value()->isSame(aSel->context()->shape()))
1548               continue;
1549
1550             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1551             if (aRefFeat.get() && aRefFeat != owner()) {
1552               FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1553               if (!aDoc->isLaterByDep(aRefFeat, aThisFeature)) { // found better feature
1554                 aFoundNewContext = true;
1555                 aNewContext = aRefFeat->firstResult();
1556               }
1557             }
1558           }
1559         }
1560       }
1561     }
1562     if (aNewContext != aContext) {
1563       setValue(aNewContext, value());
1564     }
1565     return;
1566   }
1567   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1568   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1569   // iterate the context shape modifications in order to find a feature that is upper in history
1570   // that this one and is really modifies the referenced result to refer to it
1571   ResultPtr aModifierResFound;
1572   TNaming_Iterator aPairIter(aContNS);
1573   if (!aPairIter.More())
1574     return;
1575   TopoDS_Shape aNewCShape = aPairIter.NewShape();
1576   bool anIterate = true;
1577   // trying to update also the sub-shape selected
1578   GeomShapePtr aSubShape = value();
1579   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1580     aSubShape.reset();
1581   TopoDS_Shape aValShape;
1582   if (aSubShape.get()) {
1583     aValShape = aSubShape->impl<TopoDS_Shape>();
1584   }
1585
1586   std::list<ResultPtr> aNewContexts;
1587   TopTools_ListOfShape aValShapes;
1588   if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1589   {
1590     std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1591     TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1592     if (aNewCont == aNewContexts.end()) { // all results were deleted
1593       ResultPtr anEmptyContext;
1594       std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1595       setValue(anEmptyContext, anEmptyShape); // nullify the selection
1596       return;
1597     }
1598
1599     GeomShapePtr aValueShape;
1600     if (!aNewValues.Value().IsNull()) {
1601       aValueShape = std::make_shared<GeomAPI_Shape>();
1602       aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1603     }
1604     setValue(*aNewCont, aValueShape);
1605     // if there are more than one result, put them by "append" into "parent" list
1606     if (myParent) {
1607       for(aNewCont++, aNewValues.Next(); aNewCont != aNewContexts.end();
1608           aNewCont++, aNewValues.Next()) {
1609         GeomShapePtr aValueShape;
1610         if (!aNewValues.Value().IsNull()) {
1611           aValueShape = std::make_shared<GeomAPI_Shape>();
1612           aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1613         }
1614
1615         // Check that list has the same type of shape selection before adding.
1616         GeomAPI_Shape::ShapeType aListShapeType = GeomAPI_Shape::SHAPE;
1617         if (myParent->selectionType() == "VERTEX") aListShapeType = GeomAPI_Shape::VERTEX;
1618         else if (myParent->selectionType() == "EDGE") aListShapeType = GeomAPI_Shape::EDGE;
1619         else if (myParent->selectionType() == "FACE") aListShapeType = GeomAPI_Shape::FACE;
1620
1621         GeomAPI_Shape::ShapeType aShapeShapeType = GeomAPI_Shape::SHAPE;
1622         if (aValueShape.get()) {
1623           aShapeShapeType = aValueShape->shapeType();
1624         } else {
1625           (*aNewCont)->shape()->shapeType();
1626         }
1627
1628         if (aListShapeType != GeomAPI_Shape::SHAPE && aListShapeType != aShapeShapeType) {
1629           continue;
1630         }
1631
1632         myParent->append(*aNewCont, aValueShape);
1633       }
1634     }
1635   }
1636 }
1637
1638 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1639 {
1640   myParent = theParent;
1641 }
1642
1643 std::string Model_AttributeSelection::contextName(const TDF_Label theSelectionLab)
1644 {
1645   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1646     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1647   FeaturePtr aFeatureOwner = aDoc->featureByLab(theSelectionLab);
1648   if (aFeatureOwner.get()) {
1649     // if it is sub-element of the sketch, the context name is the name of the sketch
1650     // searching also for result - real context
1651     ResultPtr aResult;
1652     FeaturePtr aComposite = ModelAPI_Tools::compositeOwner(aFeatureOwner);
1653     if (aComposite.get() && aComposite->results().size() == 1 &&
1654         aComposite->firstResult()->groupName() == ModelAPI_ResultConstruction::group()) {
1655       aFeatureOwner = aComposite;
1656       aResult = aFeatureOwner->firstResult();
1657     } else {
1658       aResult = aDoc->resultByLab(theSelectionLab);
1659     }
1660     if (aResult.get()) {
1661       // this is to avoid duplicated names of results problem
1662       std::string aContextName = aResult->data()->name();
1663       // myLab corresponds to the current time
1664       TDF_Label aCurrentLab = selectionLabel();
1665       while(aCurrentLab.Depth() > 3)
1666         aCurrentLab = aCurrentLab.Father();
1667
1668       int aNumInHistoryNames =
1669         aDoc->numberOfNameInHistory(aResult, aCurrentLab);
1670       while(aNumInHistoryNames > 1) { // add "_" before name the needed number of times
1671         aContextName = "_" + aContextName;
1672         aNumInHistoryNames--;
1673       }
1674       return aContextName;
1675     }
1676   }
1677   return ""; // invalid case
1678 }
1679
1680 /// This method restores by the context and value name the context label and
1681 /// sub-label where the value is. Returns true if it is valid.
1682 bool Model_AttributeSelection::restoreContext(std::string theName,
1683   TDF_Label& theContext, TDF_Label& theValue)
1684 {
1685   static const GeomShapePtr anEmptyShape; // to store context only
1686   std::string aName = theName;
1687   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1688     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1689
1690   // remove the sub-value part if exists
1691   std::string aSubShapeName = aName;
1692   std::string::size_type n = aName.find('/');
1693   if (n != std::string::npos) {
1694     aName = aName.substr(0, n);
1695   }
1696
1697   if (aName.empty()) return false;
1698   bool anUniqueContext = false;
1699   ResultPtr aCont = aDoc->findByName(aName, aSubShapeName, anUniqueContext);
1700   if (!aCont.get() || !aCont->shape().get() || aCont->shape()->isNull())
1701     return false;
1702
1703   // searching the sub-shape
1704   static const ResultPtr anEmpty;
1705   theValue = aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
1706
1707   // sketch sub-component shape and name is located in separated feature label, try the sub-name
1708   if (theValue.IsNull() && aCont->groupName() == ModelAPI_ResultConstruction::group()) {
1709     std::string::size_type aSlash = aSubShapeName.rfind('/');
1710     if (aSlash != std::string::npos) {
1711       std::string aCompName = aSubShapeName.substr(aSlash + 1);
1712       CompositeFeaturePtr aComposite =
1713         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aCont));
1714       if (aComposite.get() && aComposite->numberOfSubs()) {
1715         const int aSubNum = aComposite->numberOfSubs();
1716         for (int a = 0; a < aSubNum && theValue.IsNull(); a++) {
1717           FeaturePtr aSub = aComposite->subFeature(a);
1718           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
1719           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
1720           for (; aRes != aResults.cend() && theValue.IsNull(); aRes++) {
1721             if ((*aRes)->data()->name() == aCompName) {
1722               theValue = std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->shapeLab();
1723               break;
1724             } else { // any sub-label because the sketch line may be renamed, but not sub-vertices
1725               TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->shapeLab();
1726               TDF_ChildIDIterator aSubNames(aLab, TDataStd_Name::GetID());
1727               for(; aSubNames.More(); aSubNames.Next()) {
1728                 if (Handle(TDataStd_Name)::DownCast(aSubNames.Value())->Get().
1729                   IsEqual(aCompName.c_str())) {
1730                   theValue = aSubNames.Value()->Label();
1731                   break;
1732                 }
1733               }
1734             }
1735           }
1736         }
1737       }
1738     }
1739   }
1740
1741   if (aCont.get()) {
1742     theContext = std::dynamic_pointer_cast<Model_Data>(aCont->data())->label();
1743   }
1744   return true;
1745 }
1746
1747 TDF_Label Model_AttributeSelection::newestContext(const TDF_Label theCurrentContext) {
1748   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1749     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1750   ResultPtr aContext = aDoc->resultByLab(theCurrentContext);
1751   if (aContext.get()) {
1752     aContext = newestContext(aContext, GeomShapePtr(), true);
1753     if (aContext.get())
1754       return std::dynamic_pointer_cast<Model_Data>(aContext->data())->label();
1755   }
1756   return theCurrentContext; // nothing is changed
1757 }
1758
1759 bool Model_AttributeSelection::isLater(
1760   const TDF_Label theResult1, const TDF_Label theResult2) const
1761 {
1762   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1763     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1764   FeaturePtr aFeat1 = aDoc->featureByLab(theResult1);
1765   if (!aFeat1.get())
1766     return false;
1767   FeaturePtr aFeat2 = aDoc->featureByLab(theResult2);
1768   if (!aFeat2.get())
1769     return false;
1770   return aDoc->isLaterByDep(aFeat1, aFeat2);
1771 }
1772
1773 ResultPtr Model_AttributeSelection::newestContext(
1774   const ResultPtr theCurrent, const GeomShapePtr theValue, const bool theAnyValue)
1775 {
1776   ResultPtr aResult = theCurrent;
1777   GeomShapePtr aSelectedShape = theValue.get() ? theValue : theCurrent->shape();
1778   std::shared_ptr<Model_Document> aDoc =
1779     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1780   bool aFindNewContext = true;
1781   while (aFindNewContext && aResult.get()) {
1782     aFindNewContext = false;
1783     // try to find the last context to find the up to date shape
1784     TopoDS_Shape aConShape = aResult->shape()->impl<TopoDS_Shape>();
1785     if (TNaming_Tool::HasLabel(selectionLabel(), aConShape)) {
1786       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
1787       if (!aNS.IsNull()) {
1788         aNS = TNaming_Tool::CurrentNamedShape(aNS);
1789         if (!aNS.IsNull()
1790             && isLater(selectionLabel(), aNS->Label())
1791             && isLater(aNS->Label(),
1792                        std::dynamic_pointer_cast<Model_Data>(aResult->data())->label()))
1793         {
1794           TDF_Label aLab = aNS->Label();
1795           ResultPtr aRes = aDoc->resultByLab(aLab);
1796           if (aRes.get()) {
1797             if (theAnyValue || aRes->shape()->isSubShape(aSelectedShape)) {
1798               aResult = aRes;
1799               aFindNewContext = true;
1800               continue;
1801             }
1802           }
1803         }
1804       }
1805     }
1806     if (theAnyValue) { // only for neighbors for now
1807       // try to find modification of sub-shapes: the best number of matches
1808       std::map<ResultPtr, int> aMatches; // result -> number of matches of shapes to find the best
1809       TDF_Label aResLab = std::dynamic_pointer_cast<Model_Data>(aResult->data())->shapeLab();
1810       TDF_ChildIDIterator aModifIter(aResLab, TNaming_NamedShape::GetID());
1811       for(; aModifIter.More(); aModifIter.Next()) {
1812         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aModifIter.Value());
1813         if (aNS->Evolution() == TNaming_MODIFY || aNS->Evolution() == TNaming_GENERATED) {
1814           for(TNaming_Iterator aNSIter(aNS); aNSIter.More(); aNSIter.Next()) {
1815             TNaming_NewShapeIterator aNewIter(aNSIter.NewShape(), aNS->Label());
1816             for(; aNewIter.More(); aNewIter.Next()) {
1817               TDF_Label aLab = aNewIter.Label();
1818               if (isLater(aLab, aNS->Label()) && isLater(selectionLabel(), aLab)) {
1819                 ResultPtr aRes = aDoc->resultByLab(aLab);
1820                 if (aRes.get()) {
1821                   if (aMatches.find(aRes) == aMatches.end())
1822                     aMatches[aRes] = 0;
1823                   aMatches[aRes]++; // found result, add matches
1824                 }
1825               }
1826             }
1827           }
1828         }
1829       }
1830       // searching for the best result-candidate
1831       int aBest = 0;
1832       ResultPtr aBestResult;
1833       std::map<ResultPtr, int>::iterator aMatchIter = aMatches.begin();
1834       for(; aMatchIter != aMatches.end(); aMatchIter++) {
1835         if (aMatchIter->second > aBest) {
1836           aBest = aMatchIter->second;
1837           aBestResult = aMatchIter->first;
1838         }
1839       }
1840       if (aBestResult.get()) {
1841         aResult = aBestResult;
1842         aFindNewContext = true;
1843         continue;
1844       }
1845     }
1846
1847
1848     // TestFillWireVertex.py - sketch constructions for wire may participate too
1849     //if (aResult->groupName() == ModelAPI_ResultBody::group()) {
1850       // try to search newer context by the concealment references
1851       // take references to all results: root one, any sub
1852     std::list<ResultPtr> allRes;
1853     ResultPtr aCompContext;
1854     ResultBodyPtr aCompBody = ModelAPI_Tools::bodyOwner(aResult, true);
1855     if (aCompBody.get()) {
1856       ModelAPI_Tools::allSubs(aCompBody, allRes);
1857       allRes.push_back(aCompBody);
1858       aCompContext = aCompBody;
1859     }
1860     if (allRes.empty())
1861       allRes.push_back(aResult);
1862
1863     for (std::list<ResultPtr>::iterator aSub = allRes.begin(); aSub != allRes.end(); aSub++) {
1864       ResultPtr aResCont = *aSub;
1865       ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResCont);
1866       if (aResBody.get() && aResBody->numberOfSubs() > 0 && aResBody != aCompContext)
1867         continue; // only lower and higher level subs are counted
1868       const std::set<AttributePtr>& aRefs = aResCont->data()->refsToMe();
1869       std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1870       for (; !aFindNewContext && aRef != aRefs.end(); aRef++) {
1871         if (!aRef->get() || !(*aRef)->owner().get())
1872           continue;
1873         // concealed attribute only
1874         FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1875         if (!ModelAPI_Session::get()->validators()->isConcealed(
1876           aRefFeat->getKind(), (*aRef)->id()))
1877           continue;
1878         // search the feature result that contains sub-shape selected
1879         std::list<std::shared_ptr<ModelAPI_Result> > aResults;
1880
1881         // take all sub-results or one result
1882         std::list<ResultPtr> aRefFeatResults;
1883         ModelAPI_Tools::allResults(aRefFeat, aRefFeatResults);
1884         std::list<ResultPtr>::iterator aRefResIter = aRefFeatResults.begin();
1885         for (; aRefResIter != aRefFeatResults.end(); aRefResIter++) {
1886           ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRefResIter);
1887           if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1888             aResults.push_back(aBody);
1889         }
1890         std::list<std::shared_ptr<ModelAPI_Result> >::iterator aResIter = aResults.begin();
1891         for (; aResIter != aResults.end(); aResIter++) {
1892           if (!aResIter->get() || !(*aResIter)->data()->isValid() || (*aResIter)->isDisabled())
1893             continue;
1894           GeomShapePtr aShape = (*aResIter)->shape();
1895           if (aShape.get() && (theAnyValue || aShape->isSubShape(aSelectedShape, false))) {
1896             aResult = *aResIter; // found new context (produced from this) with same subshape
1897             aFindNewContext = true; // continue searching further
1898             break;
1899           }
1900         }
1901       }
1902     }
1903   }
1904   // if compsolid is context, try to take sub-solid as context: like in GUI and scripts
1905   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
1906   if (aComp && aComp->numberOfSubs()) {
1907     std::list<ResultPtr> allSubs;
1908     ModelAPI_Tools::allSubs(aComp, allSubs);
1909     std::list<ResultPtr>::iterator aS = allSubs.begin();
1910     for (; aS != allSubs.end(); aS++) {
1911       ResultBodyPtr aSub = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aS);
1912       if (aSub && aSub->numberOfSubs() == 0 && aSub->shape().get() &&
1913         (theAnyValue || aSub->shape()->isSubShape(aSelectedShape))) {
1914         aResult = aSub;
1915         break;
1916       }
1917     }
1918   }
1919   // in case sketch line was selected for wire, but wire was concealed and not such line anymore,
1920   // so, actually, the sketch element was selected (which is never concealed)
1921   if (aResult != theCurrent && aResult->isConcealed())
1922     aResult = theCurrent;
1923   return aResult;
1924 }