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