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