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