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