Salome HOME
Issue #2561: CEA 2018-1 Cut
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "Model_AttributeSelection.h"
22 #include "Model_Application.h"
23 #include "Model_Events.h"
24 #include "Model_Data.h"
25 #include "Model_Document.h"
26 #include "Model_SelectionNaming.h"
27 #include <Model_Objects.h>
28 #include <Model_AttributeSelectionList.h>
29 #include <Model_ResultConstruction.h>
30 #include <ModelAPI_Feature.h>
31 #include <ModelAPI_ResultBody.h>
32 #include <ModelAPI_ResultBody.h>
33 #include <ModelAPI_ResultConstruction.h>
34 #include <ModelAPI_ResultPart.h>
35 #include <ModelAPI_CompositeFeature.h>
36 #include <ModelAPI_Tools.h>
37 #include <ModelAPI_Session.h>
38 #include <ModelAPI_Validator.h>
39 #include <Events_InfoMessage.h>
40 #include <GeomAPI_Edge.h>
41 #include <GeomAPI_Vertex.h>
42
43 #include <TNaming_Selector.hxx>
44 #include <TNaming_NamedShape.hxx>
45 #include <TNaming_Tool.hxx>
46 #include <TNaming_Builder.hxx>
47 #include <TNaming_SameShapeIterator.hxx>
48 #include <TNaming_Iterator.hxx>
49 #include <TDataStd_Integer.hxx>
50 #include <TDataStd_UAttribute.hxx>
51 #include <TDataStd_Name.hxx>
52 #include <TopTools_ListOfShape.hxx>
53 #include <TopTools_DataMapOfShapeShape.hxx>
54 #include <TopTools_MapOfShape.hxx>
55 #include <TopExp_Explorer.hxx>
56 #include <BRep_Tool.hxx>
57 #include <TopoDS.hxx>
58 #include <TopExp.hxx>
59 #include <TDF_ChildIterator.hxx>
60 #include <TDF_ChildIDIterator.hxx>
61 #include <TopoDS_Iterator.hxx>
62 #include <TDF_ChildIDIterator.hxx>
63 #include <Geom_Circle.hxx>
64 #include <Geom_Ellipse.hxx>
65 #include <BRep_Builder.hxx>
66
67 //#define DEB_NAMING 1
68 #ifdef DEB_NAMING
69 #include <BRepTools.hxx>
70 #endif
71 /// added to the index in the packed map to signalize that the vertex of edge is selected
72 /// (multiplied by the index of the edge)
73 static const int kSTART_VERTEX_DELTA = 1000000;
74 // identifier that there is simple reference: selection equals to context
75 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
76 // reference to Part sub-object
77 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
78 // selection is invalid after recomputation
79 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
80
81 // identifier of the selection of the center of circle on edge
82 Standard_GUID kCIRCLE_CENTER("d0d0e0f1-217a-4b95-8fbb-0c4132f23718");
83 // identifier of the selection of the first focus point of ellipse on edge
84 Standard_GUID kELLIPSE_CENTER1("f70df04c-3168-4dc9-87a4-f1f840c1275d");
85 // identifier of the selection of the second focus point of ellipse on edge
86 Standard_GUID kELLIPSE_CENTER2("1395ae73-8e02-4cf8-b204-06ff35873a32");
87
88 // on this label is stored:
89 // TNaming_NamedShape - selected shape
90 // TNaming_Naming - topological selection information (for the body)
91 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
92 // TDataStd_Integer - type of the selected shape (for construction)
93 // TDF_Reference - from ReferenceAttribute, the context
94 bool Model_AttributeSelection::setValue(const ObjectPtr& theContext,
95   const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
96 {
97   if (theTemporarily &&
98       (!theContext.get() || theContext->groupName() != ModelAPI_Feature::group())) {
99     // just keep the stored without DF update
100     myTmpContext = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
101     myTmpSubShape = theSubShape;
102     owner()->data()->sendAttributeUpdated(this);
103     return true;
104   } else {
105     myTmpContext.reset();
106     myTmpSubShape.reset();
107     myTmpCenterType = NOT_CENTER;
108   }
109
110   CenterType aType;
111   const std::shared_ptr<GeomAPI_Shape>& anOldShape = internalValue(aType);
112   bool isOldContext = theContext == myRef.value();
113   bool isOldShape = isOldContext &&
114     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
115   if (isOldShape) return false; // shape is the same, so context is also unchanged
116   bool aToUnblock = false;
117   // update the referenced object if needed
118   if (!isOldContext) {
119     aToUnblock = !owner()->data()->blockSendAttributeUpdated(true);
120     myRef.setValue(theContext);
121   }
122
123   // do noth use naming if selected shape is result shape itself, but not sub-shape
124   TDF_Label aSelLab = selectionLabel();
125   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
126   aSelLab.ForgetAttribute(kINVALID_SELECTION);
127   aSelLab.ForgetAttribute(kCIRCLE_CENTER);
128   aSelLab.ForgetAttribute(kELLIPSE_CENTER1);
129   aSelLab.ForgetAttribute(kELLIPSE_CENTER2);
130
131   bool isDegeneratedEdge = false;
132   // do not use the degenerated edge as a shape, a null context and shape is used in the case
133   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
134     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
135     if (aSubShape.ShapeType() == TopAbs_EDGE)
136       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
137   }
138   if (!theContext.get() || isDegeneratedEdge) {
139     // to keep the reference attribute label
140     TDF_Label aRefLab = myRef.myRef->Label();
141     aSelLab.ForgetAllAttributes(true);
142     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
143     if (aToUnblock)
144       owner()->data()->blockSendAttributeUpdated(false);
145     return false;
146   }
147   if (theContext->groupName() == ModelAPI_ResultBody::group()) {
148     ResultBodyPtr aContextBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theContext);
149     // do not select the whole shape for body:it is already must be in the data framework
150     // equal and null selected objects mean the same: object is equal to context,
151     if (aContextBody->shape().get() &&
152         (aContextBody->shape()->isEqual(theSubShape) || !theSubShape.get())) {
153       aSelLab.ForgetAllAttributes(true);
154       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
155     } else {
156       selectBody(aContextBody, theSubShape);
157     }
158   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
159     ResultConstructionPtr aContextConstruction =
160       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
161     aSelLab.ForgetAllAttributes(true); // to remove old selection data
162     std::shared_ptr<Model_ResultConstruction> aConstruction =
163       std::dynamic_pointer_cast<Model_ResultConstruction>(theContext);
164     std::shared_ptr<GeomAPI_Shape> aSubShape;
165     if (theSubShape.get() && !aContextConstruction->shape()->isEqual(theSubShape))
166       aSubShape = theSubShape; // the whole context
167     if (aConstruction->isInfinite()) {
168       // For correct naming selection, put the shape into the naming structure.
169       // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
170       TNaming_Builder aBuilder(aSelLab);
171       aBuilder.Generated(aContextConstruction->shape()->impl<TopoDS_Shape>());
172     }
173     int anIndex = aConstruction->select(theSubShape, owner()->document());
174     TDataStd_Integer::Set(aSelLab, anIndex);
175   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
176     aSelLab.ForgetAllAttributes(true);
177     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
178     selectPart(std::dynamic_pointer_cast<ModelAPI_Result>(theContext), theSubShape);
179   }
180
181   owner()->data()->sendAttributeUpdated(this);
182
183   if (aToUnblock)
184     owner()->data()->blockSendAttributeUpdated(false);
185
186   return true;
187 }
188
189 void Model_AttributeSelection::setValueCenter(
190     const ObjectPtr& theContext, const std::shared_ptr<GeomAPI_Edge>& theEdge,
191     const CenterType theCenterType, const bool theTemporarily)
192 {
193   bool anUpdated = setValue(theContext, theEdge, theTemporarily);
194   if (theTemporarily) {
195     myTmpCenterType = theCenterType;
196   } else { // store in the data structure
197     TDF_Label aSelLab = selectionLabel();
198     switch(theCenterType) {
199     case CIRCLE_CENTER:
200       if (!anUpdated)
201         anUpdated = !aSelLab.IsAttribute(kCIRCLE_CENTER);
202       TDataStd_UAttribute::Set(aSelLab, kCIRCLE_CENTER);
203       break;
204     case ELLIPSE_FIRST_FOCUS:
205       if (!anUpdated)
206         anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER1);
207       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER1);
208       break;
209     case ELLIPSE_SECOND_FOCUS:
210       if (!anUpdated)
211         anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER2);
212       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER2);
213       break;
214     }
215     if (anUpdated)
216       owner()->data()->sendAttributeUpdated(this);
217   }
218 }
219
220 void Model_AttributeSelection::selectValue(
221     const std::shared_ptr<ModelAPI_AttributeSelection>& theSource)
222 {
223   CenterType aType;
224   std::shared_ptr<GeomAPI_Shape> aValue =
225     std::dynamic_pointer_cast<Model_AttributeSelection>(theSource)->internalValue(aType);
226   if (!aValue.get() || aType == NOT_CENTER) {
227     setValue(theSource->context(), aValue);
228   } else {
229     std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge);
230     anEdge->setImpl(new TopoDS_Shape(aValue->impl<TopoDS_Shape>()));
231     setValueCenter(theSource->context(), anEdge, aType);
232   }
233 }
234
235 void Model_AttributeSelection::removeTemporaryValues()
236 {
237   if (myTmpContext.get() || myTmpSubShape.get()) {
238     myTmpContext.reset();
239     myTmpSubShape.reset();
240   }
241 }
242
243 // returns the center of the edge: circular or elliptical
244 GeomShapePtr centerByEdge(GeomShapePtr theEdge, ModelAPI_AttributeSelection::CenterType theType)
245 {
246   if (theType != ModelAPI_AttributeSelection::NOT_CENTER && theEdge.get() != NULL) {
247     TopoDS_Shape aShape = theEdge->impl<TopoDS_Shape>();
248     if (!aShape.IsNull() && aShape.ShapeType() == TopAbs_EDGE) {
249       TopoDS_Edge anEdge = TopoDS::Edge(aShape);
250       double aFirst, aLast;
251       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
252       if (!aCurve.IsNull()) {
253         TopoDS_Vertex aVertex;
254         BRep_Builder aBuilder;
255         if (theType == ModelAPI_AttributeSelection::CIRCLE_CENTER) {
256           Handle(Geom_Circle) aCirc = Handle(Geom_Circle)::DownCast(aCurve);
257           if (!aCirc.IsNull()) {
258             aBuilder.MakeVertex(aVertex, aCirc->Location(), Precision::Confusion());
259           }
260         } else { // ellipse
261           Handle(Geom_Ellipse) anEll = Handle(Geom_Ellipse)::DownCast(aCurve);
262           if (!anEll.IsNull()) {
263             aBuilder.MakeVertex(aVertex,
264               theType == ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS ?
265               anEll->Focus1() : anEll->Focus2(), Precision::Confusion());
266           }
267         }
268         if (!aVertex.IsNull()) {
269           std::shared_ptr<GeomAPI_Vertex> aResult(new GeomAPI_Vertex);
270           aResult->setImpl(new TopoDS_Vertex(aVertex));
271           return aResult;
272         }
273       }
274     }
275   }
276   return theEdge; // no vertex, so, return the initial edge
277 }
278
279 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
280 {
281   if (!ModelAPI_AttributeSelection::isInitialized() && !myTmpContext.get() && !myTmpSubShape.get())
282     return std::shared_ptr<GeomAPI_Shape>();
283   CenterType aType = NOT_CENTER;
284   std::shared_ptr<GeomAPI_Shape> aResult = internalValue(aType);
285   return centerByEdge(aResult, aType);
286 }
287
288 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::internalValue(CenterType& theType)
289 {
290   theType = NOT_CENTER;
291   GeomShapePtr aResult;
292   if (myTmpContext.get() || myTmpSubShape.get()) {
293     theType = myTmpCenterType;
294     ResultConstructionPtr aResulConstruction =
295       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myTmpContext);
296     if(aResulConstruction.get()) {
297       // it is just reference to construction.
298       return myTmpSubShape;
299     }
300     return myTmpSubShape.get() ? myTmpSubShape : myTmpContext->shape();
301   }
302
303   TDF_Label aSelLab = selectionLabel();
304   if (aSelLab.IsAttribute(kINVALID_SELECTION))
305     return aResult;
306
307   if (aSelLab.IsAttribute(kCIRCLE_CENTER))
308     theType = CIRCLE_CENTER;
309   else if (aSelLab.IsAttribute(kELLIPSE_CENTER1))
310     theType = ELLIPSE_FIRST_FOCUS;
311   else if (aSelLab.IsAttribute(kELLIPSE_CENTER2))
312     theType = ELLIPSE_SECOND_FOCUS;
313
314
315   if (myRef.isInitialized()) {
316     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
317       ResultPtr aContext = context();
318       if (!aContext.get())
319         return aResult; // empty result
320       return aContext->shape();
321     }
322     if (aSelLab.IsAttribute(kPART_REF_ID)) {
323       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
324       if (!aPart.get() || !aPart->isActivated())
325         return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
326       Handle(TDataStd_Integer) anIndex;
327       if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
328         if (anIndex->Get()) { // special selection attribute was created, use it
329           return aPart->selectionValue(anIndex->Get());
330         } else { // face with name is already in the data model, so try to take it by name
331           Handle(TDataStd_Name) aName;
332           if (aSelLab.FindAttribute(TDataStd_Name::GetID(), aName)) {
333             std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
334             std::size_t aPartEnd = aSubShapeName.find('/');
335             if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
336               std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
337               int anIndex;
338               std::string aType; // to reuse already existing selection the type is not needed
339               return aPart->shapeInPart(aNameInPart, aType, anIndex);
340             }
341           }
342         }
343       }
344     }
345
346     std::shared_ptr<Model_ResultConstruction> aConstr =
347       std::dynamic_pointer_cast<Model_ResultConstruction>(context());
348     if (aConstr) {
349       if (aConstr->isInfinite())
350         return aResult; // empty result
351     }
352     Handle(TNaming_NamedShape) aSelection;
353     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
354       TopoDS_Shape aSelShape = aSelection->Get();
355       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
356       aResult->setImpl(new TopoDS_Shape(aSelShape));
357     } else if (aConstr) { // simple construction element: just shape of this construction element
358       Handle(TDataStd_Integer) anIndex;
359       if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
360         if (anIndex->Get() == 0) // it is just reference to construction, nothing is in value
361           return aResult;
362         return aConstr->shape(anIndex->Get(), owner()->document());
363       }
364     }
365   }
366   return aResult;
367 }
368
369 bool Model_AttributeSelection::isInvalid()
370 {
371   return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
372 }
373
374 bool Model_AttributeSelection::isInitialized()
375 {
376   if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
377     std::shared_ptr<GeomAPI_Shape> aResult;
378     if (myRef.isInitialized()) {
379       TDF_Label aSelLab = selectionLabel();
380       if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
381         ResultPtr aContext = context();
382         return aContext.get() != NULL;
383       }
384       Handle(TNaming_NamedShape) aSelection;
385       if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
386         return !aSelection->Get().IsNull();
387       } else { // for simple construction element: just shape of this construction element
388         std::shared_ptr<Model_ResultConstruction> aConstr =
389           std::dynamic_pointer_cast<Model_ResultConstruction>(context());
390         if (aConstr.get()) {
391           Handle(TDataStd_Integer) anIndex;
392           if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
393             // for the whole shape it may return null, so, if index exists, returns true
394             return true;
395           }
396         }
397       }
398     }
399   }
400   return false;
401 }
402
403 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
404   : myRef(theLabel)
405 {
406   myIsInitialized = myRef.isInitialized();
407   myParent = NULL;
408 }
409
410 void Model_AttributeSelection::setID(const std::string theID)
411 {
412   myRef.setID(theID);
413   ModelAPI_AttributeSelection::setID(theID);
414 }
415
416 ResultPtr Model_AttributeSelection::context()
417 {
418   if (!ModelAPI_AttributeSelection::isInitialized() && !myTmpContext.get() && !myTmpSubShape.get())
419     return ResultPtr();
420
421   if (myTmpContext.get() || myTmpSubShape.get()) {
422     return myTmpContext;
423   }
424
425   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
426   // for parts there could be same-data result, so take the last enabled
427   if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
428     int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
429     for(int a = aSize - 1; a >= 0; a--) {
430       ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
431       if (aPart.get() && aPart->data() == aResult->data()) {
432         ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
433         FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
434         // check that this result is not this-feature result (it is forbidden t oselect itself)
435         if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
436           return aPartResult;
437         }
438       }
439     }
440   }
441   return aResult;
442 }
443
444 FeaturePtr Model_AttributeSelection::contextFeature() {
445   if (myTmpContext.get() || myTmpSubShape.get()) {
446     return FeaturePtr(); // feature can not be selected temporarily
447   }
448   return std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
449
450 }
451
452
453
454 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
455 {
456   ModelAPI_AttributeSelection::setObject(theObject);
457   myRef.setObject(theObject);
458 }
459
460 TDF_LabelMap& Model_AttributeSelection::scope()
461 {
462   if (myScope.IsEmpty()) { // create a new scope if not yet done
463     // gets all features with named shapes that are before this feature label (before in history)
464     DocumentPtr aMyDoc = owner()->document();
465     std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
466     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
467     bool aMePassed = false;
468     CompositeFeaturePtr aComposite =
469       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
470     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
471     CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
472     if (aFeature.get()) {
473       aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
474       if (aCompositeOwner.get()) {
475          aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
476       }
477     }
478     // for group Scope is not limitet: this is always up to date objects
479     // this causes problem in galeries.py
480     //bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
481     for(; aFIter != allFeatures.end(); aFIter++) {
482       if (*aFIter == owner()) {  // the left features are created later (except subs of composite)
483         aMePassed = true;
484         continue;
485       }
486       //if (isGroup) aMePassed = false;
487       bool isInScope = !aMePassed;
488       if (!isInScope && aComposite.get()) {
489         // try to add sub-elements of composite if this is composite
490         if (aComposite->isSub(*aFIter))
491           isInScope = true;
492       }
493       // remove the composite-owner of this feature (sketch in extrusion-cut)
494       if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
495         isInScope = false;
496
497       if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
498         TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
499           (*aFIter)->data())->label().Father();
500         TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), true);
501         for(; aNSIter.More(); aNSIter.Next()) {
502           Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
503           if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
504             myScope.Add(aNS->Label());
505           }
506         }
507       }
508     }
509     // also add all naming labels created for external constructions
510     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(aMyDoc);
511     TDF_Label anExtDocLab = aDoc->extConstructionsLabel();
512     TDF_ChildIDIterator aNSIter(anExtDocLab, TNaming_NamedShape::GetID(), true);
513     for(; aNSIter.More(); aNSIter.Next()) {
514       Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
515       if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
516         myScope.Add(aNS->Label());
517       }
518     }
519   }
520   return myScope;
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   TDF_Label aSelLab = selectionLabel();
563   ResultPtr aContext = context();
564   if (!aContext.get())
565     return setInvalidIfFalse(aSelLab, false);
566   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
567     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
568   }
569
570   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
571     std::shared_ptr<GeomAPI_Shape> aNoSelection;
572     bool aResult = selectPart(aContext, aNoSelection, true);
573     aResult = setInvalidIfFalse(aSelLab, aResult);
574     if (aResult) {
575       owner()->data()->sendAttributeUpdated(this);
576     }
577     return aResult;
578   }
579
580   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
581     // body: just a named shape, use selection mechanism from OCCT
582     TNaming_Selector aSelector(aSelLab);
583     TopoDS_Shape anOldShape;
584     if (!aSelector.NamedShape().IsNull()) {
585       anOldShape = aSelector.NamedShape()->Get();
586     }
587     bool aResult = aSelector.Solve(scope()) == Standard_True;
588     // must be before sending of updated attribute (1556)
589     aResult = setInvalidIfFalse(aSelLab, aResult);
590     TopoDS_Shape aNewShape;
591     if (!aSelector.NamedShape().IsNull()) {
592       aNewShape = aSelector.NamedShape()->Get();
593     }
594     if (anOldShape.IsNull() || aNewShape.IsNull() ||
595         !anOldShape.IsEqual(aSelector.NamedShape()->Get())) {
596       // shape type shoud not not 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 || aNewShape.ShapeType() == TopAbs_COMPSOLID))
600       {
601         split(aContext, aNewShape, anOldShape.ShapeType());
602       }
603       owner()->data()->sendAttributeUpdated(this);  // send updated if shape is changed
604     }
605     return aResult;
606   }
607
608   if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
609     Handle(TDataStd_Integer) anIndex;
610     if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
611       std::shared_ptr<Model_ResultConstruction> aConstructionContext =
612         std::dynamic_pointer_cast<Model_ResultConstruction>(aContext);
613       bool aModified = true;
614       bool aValid = aConstructionContext->update(anIndex->Get(), owner()->document(), aModified);
615       setInvalidIfFalse(aSelLab, aValid);
616       if (aConstructionContext->isInfinite()) {
617         // Update the selected shape.
618         TNaming_Builder aBuilder(aSelLab);
619         aBuilder.Generated(aConstructionContext->shape()->impl<TopoDS_Shape>());
620       }
621       if (aModified)
622         owner()->data()->sendAttributeUpdated(this);
623       return aValid;
624     }
625   }
626   return setInvalidIfFalse(aSelLab, false); // unknown case
627 }
628
629 void Model_AttributeSelection::selectBody(
630   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
631 {
632   // perform the selection
633   TNaming_Selector aSel(selectionLabel());
634   TopoDS_Shape aContext;
635
636   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theContext);//myRef.value()
637   if (aBody) {
638     aContext = aBody->shape()->impl<TopoDS_Shape>();
639   } else {
640     ResultPtr aResult =
641       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
642     if (aResult) {
643       aContext = aResult->shape()->impl<TopoDS_Shape>();
644     } else {
645       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
646       return;
647     }
648   }
649
650   // with "recover" feature the selected context may be not up to date (issue 1710)
651   Handle(TNaming_NamedShape) aResult;
652   TDF_Label aSelLab = selectionLabel();
653   TopoDS_Shape aNewContext = aContext;
654   bool isUpdated = true;
655   while(!aNewContext.IsNull() && isUpdated) {
656     // searching for the very last shape that was produced from this one
657     isUpdated = false;
658     if (!TNaming_Tool::HasLabel(aSelLab, aNewContext))
659       // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
660       break;
661     for(TNaming_SameShapeIterator anIter(aNewContext, aSelLab); anIter.More(); anIter.Next()) {
662       TDF_Label aNSLab = anIter.Label();
663       if (!scope().Contains(aNSLab))
664         continue;
665       Handle(TNaming_NamedShape) aNS;
666       if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
667         for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
668           if (aShapesIter.Evolution() == TNaming_SELECTED)
669             continue; // don't use the selection evolution
670           if (!aShapesIter.OldShape().IsNull() && aShapesIter.OldShape().IsSame(aNewContext)) {
671              // found the original shape
672             aNewContext = aShapesIter.NewShape(); // go to the newer shape
673             isUpdated = true;
674             break;
675           }
676         }
677       }
678     }
679   }
680   if (aNewContext.IsNull()) { // a context is already deleted
681     setInvalidIfFalse(aSelLab, false);
682     Events_InfoMessage("Model_AttributeSelection", "Failed to select shape already deleted").send();
683     return;
684   }
685
686   TopoDS_Shape aNewSub = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
687   if (!aNewSub.IsEqual(aContext)) { // searching for subshape in the new context
688     bool isFound = false;
689     TopExp_Explorer anExp(aNewContext, aNewSub.ShapeType());
690     for(; anExp.More(); anExp.Next()) {
691       if (anExp.Current().IsSame(aNewSub)) {
692         isFound = true;
693         break;
694       }
695     }
696     if (!isFound) { // sub-shape is not found in the up-to-date instance of the context shape
697       // if context is sub-result of compound/compsolid, selection of sub-shape better propagate to
698       // the main result (which is may be modified); the case is in 1799
699       ResultBodyPtr aMain = ModelAPI_Tools::bodyOwner(theContext);
700       while(ModelAPI_Tools::bodyOwner(aMain).get())
701         aMain = ModelAPI_Tools::bodyOwner(theContext);
702       if (aMain.get()) {
703         selectBody(aMain, theSubShape);
704         return;
705       }
706       setInvalidIfFalse(aSelLab, false);
707       Events_InfoMessage("Model_AttributeSelection",
708         "Failed to select sub-shape already modified").send();
709       return;
710     }
711   }
712
713   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
714   if (!aContext.IsNull()) {
715     FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
716     bool aEraseResults = false;
717     if (aFeatureOwner.get()) {
718       aEraseResults = !aFeatureOwner->results().empty();
719       if (aEraseResults) // erase results without flash deleted and redisplay: do it after Select
720         aFeatureOwner->removeResults(0, false, false);
721     }
722     aSel.Select(aNewSub, aNewContext);
723
724     if (aEraseResults) { // flash after Select : in Groups it makes selection with shift working
725       static Events_Loop* aLoop = Events_Loop::loop();
726       static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
727       aLoop->flush(kDeletedEvent);
728     }
729   }
730 }
731
732 bool Model_AttributeSelection::selectPart(
733   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
734   const bool theUpdate)
735 {
736   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
737   if (!aPart.get() || !aPart->isActivated())
738     return true; // postponed naming
739   if (theUpdate) {
740     Handle(TDataStd_Integer) anIndex;
741     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
742       // by internal selection
743       if (anIndex->Get() > 0) {
744         // update the selection by index
745         return aPart->updateInPart(anIndex->Get());
746       } else {
747         return true; // nothing to do, referencing just by name
748       }
749     }
750     return true; // nothing to do, referencing just by name
751   }
752   // store the shape (in case part is not loaded it should be useful
753   TopoDS_Shape aShape;
754   std::string aName = theContext->data()->name();
755   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
756     aShape = theContext->shape()->impl<TopoDS_Shape>();
757   } else {
758     aShape = theSubShape->impl<TopoDS_Shape>();
759     int anIndex;
760     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
761     TDataStd_Integer::Set(selectionLabel(), anIndex);
762   }
763   TNaming_Builder aBuilder(selectionLabel());
764   aBuilder.Select(aShape, aShape);
765   // identify by name in the part
766   TDataStd_Name::Set(selectionLabel(), aName.c_str());
767   return !aName.empty();
768 }
769
770 TDF_Label Model_AttributeSelection::selectionLabel()
771 {
772   return myRef.myRef->Label().FindChild(1);
773 }
774
775 /// prefixes of the shape names with centers defined
776 static std::map<ModelAPI_AttributeSelection::CenterType, std::string> kCENTERS_PREFIX;
777
778 /// returns the map that contains all possible prefixes of the center-names
779 static std::map<ModelAPI_AttributeSelection::CenterType, std::string>& centersMap()
780 {
781   if (kCENTERS_PREFIX.empty()) { // fill map by initial values
782     kCENTERS_PREFIX[ModelAPI_AttributeSelection::CIRCLE_CENTER] = "__cc";
783     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS] = "__eff";
784     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_SECOND_FOCUS] = "__esf";
785   }
786   return kCENTERS_PREFIX;
787 }
788
789 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
790 {
791   std::string aName("");
792   if(!this->isInitialized())
793     return !theDefaultName.empty() ? theDefaultName : aName;
794
795   CenterType aCenterType = NOT_CENTER;
796   std::shared_ptr<GeomAPI_Shape> aSubSh = internalValue(aCenterType);
797   ResultPtr aCont = context();
798
799   if (!aCont.get()) // in case of selection of removed result
800     return "";
801
802   Model_SelectionNaming aSelNaming(selectionLabel());
803   std::string aResult = aSelNaming.namingName(
804     aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
805   if (aCenterType != NOT_CENTER) {
806     aResult += centersMap()[aCenterType];
807   }
808   return aResult;
809 }
810
811 // returns the center type and modifies the shape name if this name is center-name
812 static ModelAPI_AttributeSelection::CenterType centerTypeByName(std::string& theShapeName)
813 {
814   std::map<ModelAPI_AttributeSelection::CenterType, std::string>::iterator aPrefixIter =
815     centersMap().begin();
816   for(; aPrefixIter != centersMap().end(); aPrefixIter++) {
817     std::size_t aFound = theShapeName.find(aPrefixIter->second);
818     if (aFound != std::string::npos &&
819         aFound == theShapeName.size() - aPrefixIter->second.size()) {
820       theShapeName = theShapeName.substr(0, aFound);
821       return aPrefixIter->first;
822     }
823   }
824   return ModelAPI_AttributeSelection::NOT_CENTER;
825 }
826
827 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
828 void Model_AttributeSelection::selectSubShape(
829   const std::string& theType, const std::string& theSubShapeName)
830 {
831   if(theSubShapeName.empty() || theType.empty()) return;
832
833   std::string aSubShapeName = theSubShapeName;
834   CenterType aCenterType = theType[0] == 'v' || theType[0] == 'V' ? // only for vertex-type
835     centerTypeByName(aSubShapeName) : NOT_CENTER;
836   std::string aType = aCenterType == NOT_CENTER ? theType : "EDGE"; // search for edge now
837
838   // first iteration is selection by name without center prefix, second - in case of problem,
839   // try with initial name
840   for(int aUseCenter = 1; aUseCenter >= 0; aUseCenter--) {
841     if (aUseCenter == 0 && aCenterType != NOT_CENTER) {
842       aSubShapeName = theSubShapeName;
843       aCenterType = NOT_CENTER;
844       aType = theType;
845     } else if (aUseCenter != 1) continue;
846
847     // check this is Part-name: 2 delimiters in the name
848     std::size_t aPartEnd = aSubShapeName.find('/');
849     if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
850       std::string aPartName = aSubShapeName.substr(0, aPartEnd);
851       ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
852       if (aFound.get()) { // found such part, so asking it for the name
853         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
854         std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
855         int anIndex;
856         std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, aType, anIndex);
857         if (aSelected.get()) {
858           if (aCenterType != NOT_CENTER) {
859             if (!aSelected->isEdge())
860               continue;
861             std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aSelected));
862             setValueCenter(aPart, aSelectedEdge, aCenterType);
863           } else
864             setValue(aPart, aSelected);
865           TDataStd_Integer::Set(selectionLabel(), anIndex);
866           return;
867         }
868       }
869     }
870
871     Model_SelectionNaming aSelNaming(selectionLabel());
872     std::shared_ptr<Model_Document> aDoc =
873       std::dynamic_pointer_cast<Model_Document>(owner()->document());
874     std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
875     ResultPtr aCont;
876     if (aSelNaming.selectSubShape(aType, aSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
877       // try to find the last context to find the up to date shape
878       if (aCont->shape().get() && !aCont->shape()->isNull() &&
879         aCont->groupName() == ModelAPI_ResultBody::group() && aDoc == owner()->document()) {
880         const TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
881         if (!aConShape.IsNull()) {
882           Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
883           if (!aNS.IsNull()) {
884             aNS = TNaming_Tool::CurrentNamedShape(aNS);
885             if (!aNS.IsNull() && scope().Contains(aNS->Label())) { // scope check is for 2228
886               TDF_Label aLab = aNS->Label();
887               while(aLab.Depth() != 7 && aLab.Depth() > 5)
888                 aLab = aLab.Father();
889               ObjectPtr anObj = aDoc->objects()->object(aLab);
890               if (anObj.get()) {
891                 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
892                 if (aRes)
893                   aCont = aRes;
894               }
895             }
896           }
897         }
898       }
899       // if compsolid is context, try to take sub-solid as context: like in GUI and scripts
900       if (aCont.get() && aShapeToBeSelected.get()) {
901         ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aCont);
902         if (aComp && aComp->numberOfSubs()) {
903           std::list<ResultPtr> allSubs;
904           ModelAPI_Tools::allSubs(aComp, allSubs);
905           std::list<ResultPtr>::reverse_iterator aS = allSubs.rbegin(); // iterate from lower level
906           for(; aS != allSubs.rend(); aS++) {
907             ResultPtr aSub = *aS;
908             if (aSub && aSub->shape().get() && aSub->shape()->isSubShape(aShapeToBeSelected)) {
909               aCont = aSub;
910               break;
911             }
912           }
913         }
914       }
915       // try to find the latest active result that must be used instead of the selected
916       // to set the active context (like in GUI selection), not concealed one
917       bool aFindNewContext = true;
918       while(aFindNewContext && aCont.get()) {
919         aFindNewContext = false;
920         // take references to all results: root one, any sub
921         ResultBodyPtr aCompContext = ModelAPI_Tools::bodyOwner(aCont);
922         std::list<ResultPtr> allRes;
923         if (aCompContext.get())
924           ModelAPI_Tools::allSubs(aCompContext, allRes);
925         allRes.push_back(aCont);
926         for(std::list<ResultPtr>::iterator aSub = allRes.begin(); aSub != allRes.end(); aSub++) {
927           ResultPtr aResCont = *aSub;
928           const std::set<AttributePtr>& aRefs = aResCont->data()->refsToMe();
929           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
930           for(; !aFindNewContext && aRef != aRefs.end(); aRef++) {
931             if (!aRef->get() || !(*aRef)->owner().get())
932               continue;
933             // concealed attribute only
934             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
935             if (!ModelAPI_Session::get()->validators()->isConcealed(
936               aRefFeat->getKind(), (*aRef)->id()))
937               continue;
938             // search the feature result that contains sub-shape selected
939             std::list<std::shared_ptr<ModelAPI_Result> > aResults;
940
941             // take all sub-results or one result
942             std::list<ResultPtr> aRefFeatResults;
943             ModelAPI_Tools::allResults(aRefFeat, aRefFeatResults);
944             std::list<ResultPtr>::iterator aRefResIter = aRefFeatResults.begin();
945             for(; aRefResIter != aRefFeatResults.end(); aRefResIter++) {
946               ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRefResIter);
947               if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
948                 aResults.push_back(aBody);
949             }
950             std::list<std::shared_ptr<ModelAPI_Result> >::iterator aResIter = aResults.begin();
951             for(; aResIter != aResults.end(); aResIter++) {
952               if (!aResIter->get() || !(*aResIter)->data()->isValid() || (*aResIter)->isDisabled())
953                 continue;
954               GeomShapePtr aShape = (*aResIter)->shape();
955               GeomShapePtr aSelectedShape =
956                 aShapeToBeSelected.get() ? aShapeToBeSelected : aCont->shape();
957               if (aShape.get() && aShape->isSubShape(aSelectedShape, false)) {
958                 aCont = *aResIter; // found new context (produced from this) with same subshape
959                 aFindNewContext = true; // continue searching futher
960                 break;
961               }
962             }
963           }
964         }
965       }
966
967       if (aCenterType != NOT_CENTER) {
968         if (!aShapeToBeSelected->isEdge())
969           continue;
970         std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aShapeToBeSelected));
971         setValueCenter(aCont, aSelectedEdge, aCenterType);
972       } else
973         setValue(aCont, aShapeToBeSelected);
974       return;
975     }
976   }
977
978   TDF_Label aSelLab = selectionLabel();
979   setInvalidIfFalse(aSelLab, false);
980   reset();
981 }
982
983 int Model_AttributeSelection::Id()
984 {
985   int anID = 0;
986   std::shared_ptr<GeomAPI_Shape> aSelection = value();
987   ResultPtr aContextRes = context();
988   // support for compsolids:
989   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
990     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
991   }
992   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
993
994
995   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
996   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
997   // searching for the latest main shape
998   if (aSelection && !aSelection->isNull() && aContext && !aContext->isNull())
999   {
1000     std::shared_ptr<Model_Document> aDoc =
1001       std::dynamic_pointer_cast<Model_Document>(context()->document());
1002     if (aDoc.get()) {
1003       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1004       if (!aNS.IsNull()) {
1005         aMainShape = TNaming_Tool::CurrentShape(aNS);
1006       }
1007     }
1008
1009     TopTools_IndexedMapOfShape aSubShapesMap;
1010     TopExp::MapShapes(aMainShape, aSubShapesMap);
1011     anID = aSubShapesMap.FindIndex(aSubShape);
1012   }
1013   return anID;
1014 }
1015
1016 void Model_AttributeSelection::setId(int theID)
1017 {
1018   std::shared_ptr<GeomAPI_Shape> aSelection;
1019
1020   ResultPtr aContextRes = context();
1021   // support for compsolids:
1022   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1023     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1024   }
1025   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1026
1027   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1028   // searching for the latest main shape
1029   if (theID > 0 && aContext && !aContext->isNull())
1030   {
1031     std::shared_ptr<Model_Document> aDoc =
1032       std::dynamic_pointer_cast<Model_Document>(aContextRes->document());
1033     if (aDoc.get()) {
1034       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1035       if (!aNS.IsNull()) {
1036         aMainShape = TNaming_Tool::CurrentShape(aNS);
1037       }
1038     }
1039
1040     TopTools_IndexedMapOfShape aSubShapesMap;
1041     TopExp::MapShapes(aMainShape, aSubShapesMap);
1042     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1043
1044     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1045     aResult->setImpl(new TopoDS_Shape(aSelShape));
1046
1047     aSelection = aResult;
1048   }
1049
1050   setValue(aContextRes, aSelection);
1051 }
1052
1053 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1054 {
1055   std::string aResult;
1056   if (owner()->document() != theContext->document()) {
1057     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1058       aResult = theContext->document()->kind() + "/";
1059     } else {
1060       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1061         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1062       if (aDocRes.get()) {
1063         aResult = aDocRes->data()->name() + "/";
1064       }
1065     }
1066   }
1067   aResult += theContext->data()->name();
1068   return aResult;
1069 }
1070
1071 void Model_AttributeSelection::computeValues(
1072   ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
1073   TopTools_ListOfShape& theShapes)
1074 {
1075   bool aWasWholeContext = theValShape.IsNull();
1076   if (aWasWholeContext) {
1077     //theShapes.Append(theValShape);
1078     //return;
1079     theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
1080   }
1081   //TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
1082   TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
1083   //if (anOldContShape.IsSame(theValShape)) { // full context shape substituted by new full context
1084     //theShapes.Append(aNewContShape);
1085     //return;
1086   //}
1087   // if a new value is unchanged in the new context, do nothing: value is correct
1088   TopExp_Explorer aSubExp(aNewContShape, theValShape.ShapeType());
1089   for(; aSubExp.More(); aSubExp.Next()) {
1090     if (aSubExp.Current().IsSame(theValShape)) {
1091       theShapes.Append(theValShape);
1092       return;
1093     }
1094   }
1095   // if new context becomes compsolid, the resulting sub may be in sub-solids
1096   std::list<ResultPtr> aNewToIterate;
1097   aNewToIterate.push_back(theNewContext);
1098   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theNewContext);
1099   if (aComp.get()) {
1100     std::list<ResultPtr> allNewContextSubs;
1101     ModelAPI_Tools::allSubs(aComp, allNewContextSubs);
1102     std::list<ResultPtr>::iterator aSub = allNewContextSubs.begin();
1103     for(; aSub != allNewContextSubs.end(); aSub++) {
1104       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aSub);
1105       if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1106         aNewToIterate.push_back(aBody);
1107     }
1108   }
1109
1110   // first iteration: searching for the whole shape appearance (like face of the box)
1111   // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
1112   int aToFindPart = 0;
1113   TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
1114   TopTools_MapOfShape anOlds; // to know how many olds produced new containers
1115   for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
1116     std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
1117     for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
1118       std::shared_ptr<Model_Data> aNewData =
1119         std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
1120       TDF_Label aNewLab = aNewData->label();
1121       // searching for produced sub-shape fully on some label
1122       TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID(), Standard_True);
1123       for(; aNSIter.More(); aNSIter.Next()) {
1124         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1125         for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
1126           if (aToFindPart == 0) { // search shape is fully inside
1127             if (aPairIter.OldShape().IsSame(theValShape)) {
1128               if (aPairIter.NewShape().IsNull()) {// value was removed
1129                 theShapes.Clear();
1130                 return;
1131               }
1132               theShapes.Append(aPairIter.NewShape());
1133             }
1134           } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
1135             TopExp_Explorer anExp(aPairIter.OldShape(), theValShape.ShapeType());
1136             for(; anExp.More(); anExp.Next()) {
1137               if (anExp.Current().IsSame(theValShape)) { // found a new container
1138                 if (aPairIter.NewShape().IsNull()) {// value was removed
1139                   theShapes.Clear();
1140                   return;
1141                 }
1142                 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
1143                 anOlds.Add(aPairIter.OldShape());
1144                 break;
1145               }
1146             }
1147           }
1148         }
1149       }
1150     }
1151   }
1152   if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
1153     // map of sub-shapes -> number of occurences of these shapes in containers
1154     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
1155     TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
1156     for(; aContIter.More(); aContIter.Next()) {
1157       TopExp_Explorer aSubExp(aContIter.Key(), theValShape.ShapeType());
1158       for(; aSubExp.More(); aSubExp.Next()) {
1159         if (!aSubs.IsBound(aSubExp.Current())) {
1160           aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
1161         }
1162         // store old to know how many olds produced this shape
1163         aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
1164       }
1165     }
1166     // if sub is appeared same times in containers as the number of old shapes that contain it
1167     int aCountInOld = anOlds.Size();
1168     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
1169       aSubsIter(aSubs);
1170     for(; aSubsIter.More(); aSubsIter.Next()) {
1171       if (aSubsIter.Value().Size() == aCountInOld) {
1172         theShapes.Append(aSubsIter.Key());
1173       }
1174     }
1175   }
1176   if (theShapes.IsEmpty()) { // nothing was changed
1177     theShapes.Append(aWasWholeContext ? TopoDS_Shape() : theValShape);
1178   }
1179 }
1180
1181 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
1182   const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
1183   TDF_Label theAccessLabel,
1184   std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
1185 {
1186   std::set<ResultPtr> aResults; // to avoid duplicates, new context, null if deleted
1187   TopTools_ListOfShape aResContShapes;
1188   // iterate context and shape, but also if it is sub-shape of main shape, check also it
1189   TopTools_ListOfShape aContextList;
1190   aContextList.Append(theContShape);
1191   if (theContext.get()) {
1192     ResultPtr aComposite = ModelAPI_Tools::bodyOwner(theContext);
1193     if (aComposite.get() && aComposite->shape().get() && !aComposite->shape()->isNull())
1194       aContextList.Append(aComposite->shape()->impl<TopoDS_Shape>());
1195   }
1196   for(TopTools_ListOfShape::Iterator aContIter(aContextList); aContIter.More(); aContIter.Next()) {
1197     TNaming_SameShapeIterator aModifIter(aContIter.ChangeValue(), theAccessLabel);
1198     for(; aModifIter.More(); aModifIter.Next()) {
1199       TDF_Label anObjLab = aModifIter.Label().Father();
1200       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1201         (theDoc->objects()->object(anObjLab));
1202       if (!aModifierObj.get()) {
1203         // #2241: shape may be sub-element of new object, not main (shell created from faces)
1204         if (!anObjLab.IsRoot())
1205           aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1206           (theDoc->objects()->object(anObjLab.Father()));
1207         if (!aModifierObj.get())
1208           continue;
1209       }
1210       FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
1211       if (!aModifierFeat.get())
1212         continue;
1213       FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1214       if (aModifierFeat == aThisFeature || theDoc->objects()->isLater(aModifierFeat, aThisFeature))
1215         continue; // the modifier feature is later than this, so, should not be used
1216       FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
1217       if (aCurrentModifierFeat == aModifierFeat ||
1218         theDoc->objects()->isLater(aCurrentModifierFeat, aModifierFeat))
1219         continue; // the current modifier is later than the found, so, useless
1220       Handle(TNaming_NamedShape) aNewNS;
1221       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1222       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1223         aResults.insert(aModifierObj);
1224         //TNaming_Iterator aPairIter(aNewNS);
1225         //aResContShapes.Append(aPairIter.NewShape());
1226         aResContShapes.Append(aModifierObj->shape()->impl<TopoDS_Shape>());
1227       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
1228         aResults.insert(ResultPtr());
1229       } else { // not-precessed modification => don't support it
1230         continue;
1231       }
1232     }
1233   }
1234   if (aResults.empty())
1235     return false; // no modifications found, must stay the same
1236   // iterate all results to find futher modifications
1237   std::set<ResultPtr>::iterator aResIter = aResults.begin();
1238   for(; aResIter != aResults.end(); aResIter++) {
1239     if (aResIter->get() != NULL) {
1240       // compute new values by two contextes: the old and the new
1241       TopTools_ListOfShape aValShapes;
1242       computeValues(theContext, *aResIter, theValShape, aValShapes);
1243
1244       TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
1245       for(; aNewVal.More(); aNewVal.Next()) {
1246         std::list<ResultPtr> aNewRes;
1247         TopTools_ListOfShape aNewUpdatedVal;
1248         TopoDS_Shape aNewValSh = aNewVal.Value();
1249         TopoDS_Shape aNewContShape = (*aResIter)->shape()->impl<TopoDS_Shape>();
1250         if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
1251           aNewValSh.Nullify();
1252         if (searchNewContext(theDoc, aNewContShape, *aResIter, aNewValSh,
1253                              theAccessLabel, aNewRes, aNewUpdatedVal))
1254         {
1255           // appeand new results instead of the current ones
1256           std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1257           TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1258           for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1259             theResults.push_back(*aNewIter);
1260             theValShapes.Append(aNewUpdVal.Value());
1261           }
1262         } else { // the current result is good
1263           theResults.push_back(*aResIter);
1264           theValShapes.Append(aNewValSh);
1265         }
1266       }
1267     }
1268   }
1269   return true; // theResults must be empty: everything is deleted
1270 }
1271
1272 void Model_AttributeSelection::updateInHistory()
1273 {
1274   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1275   // only bodies and parts may be modified later in the history, don't do anything otherwise
1276   if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
1277       aContext->groupName() != ModelAPI_ResultPart::group()))
1278     return;
1279   std::shared_ptr<Model_Document> aDoc =
1280     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1281   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1282   if (!aContData.get() || !aContData->isValid())
1283     return;
1284   TDF_Label aContLab = aContData->label(); // named shape where the selected context is located
1285   Handle(TNaming_NamedShape) aContNS;
1286   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
1287     bool aFoundNewContext = true;
1288     ResultPtr aNewContext = aContext;
1289     while(aFoundNewContext) {
1290       aFoundNewContext = false;
1291       // parts have no shape in result, so, trace references using the Part info
1292       if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
1293         ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
1294         if (aPartContext.get()) { // searching for the up to date references to the referenced cont
1295           const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
1296           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1297           for(; aRef != aRefs.end(); aRef++) {
1298             // to avoid detection of part changes by local selection only
1299             AttributeSelectionPtr aSel =
1300               std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1301             if (aSel.get() && !aSel->value()->isSame(aSel->context()->shape()))
1302               continue;
1303
1304             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1305             if (aRefFeat.get() && aRefFeat != owner()) {
1306               FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1307               if (aDoc->objects()->isLater(aThisFeature, aRefFeat)) { // found better feature
1308                 aFoundNewContext = true;
1309                 aNewContext = aRefFeat->firstResult();
1310               }
1311             }
1312           }
1313         }
1314       }
1315     }
1316     if (aNewContext != aContext) {
1317       setValue(aNewContext, value());
1318     }
1319     return;
1320   }
1321   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1322   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1323   // iterate the context shape modifications in order to find a feature that is upper in history
1324   // that this one and is really modifies the referenced result to refer to it
1325   ResultPtr aModifierResFound;
1326   TNaming_Iterator aPairIter(aContNS);
1327   if (!aPairIter.More())
1328     return;
1329   TopoDS_Shape aNewCShape = aPairIter.NewShape();
1330   bool anIterate = true;
1331   // trying to update also the sub-shape selected
1332   GeomShapePtr aSubShape = value();
1333   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1334     aSubShape.reset();
1335   TopoDS_Shape aValShape;
1336   if (aSubShape.get()) {
1337     aValShape = aSubShape->impl<TopoDS_Shape>();
1338   }
1339
1340   std::list<ResultPtr> aNewContexts;
1341   TopTools_ListOfShape aValShapes;
1342   if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1343   {
1344     // update scope to reset to a new one
1345     myScope.Clear();
1346
1347     std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1348     TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1349     if (aNewCont == aNewContexts.end()) { // all results were deleted
1350       ResultPtr anEmptyContext;
1351       std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1352       setValue(anEmptyContext, anEmptyShape); // nullify the selection
1353       return;
1354     }
1355
1356     GeomShapePtr aValueShape;
1357     if (!aNewValues.Value().IsNull()) {
1358       aValueShape = std::make_shared<GeomAPI_Shape>();
1359       aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1360     }
1361     setValue(*aNewCont, aValueShape);
1362     // if there are more than one result, put them by "append" into "parent" list
1363     if (myParent) {
1364       for(aNewCont++, aNewValues.Next(); aNewCont != aNewContexts.end();
1365           aNewCont++, aNewValues.Next()) {
1366         GeomShapePtr aValueShape;
1367         if (!aNewValues.Value().IsNull()) {
1368           aValueShape = std::make_shared<GeomAPI_Shape>();
1369           aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1370         }
1371
1372         // Check that list has the same type of shape selection before adding.
1373         GeomAPI_Shape::ShapeType aListShapeType = GeomAPI_Shape::SHAPE;
1374         if (myParent->selectionType() == "VERTEX") aListShapeType = GeomAPI_Shape::VERTEX;
1375         else if (myParent->selectionType() == "EDGE") aListShapeType = GeomAPI_Shape::EDGE;
1376         else if (myParent->selectionType() == "FACE") aListShapeType = GeomAPI_Shape::FACE;
1377
1378         GeomAPI_Shape::ShapeType aShapeShapeType = GeomAPI_Shape::SHAPE;
1379         if (aValueShape.get()) {
1380           aShapeShapeType = aValueShape->shapeType();
1381         } else {
1382           (*aNewCont)->shape()->shapeType();
1383         }
1384
1385         if (aListShapeType != GeomAPI_Shape::SHAPE && aListShapeType != aShapeShapeType) {
1386           continue;
1387         }
1388
1389         myParent->append(*aNewCont, aValueShape);
1390       }
1391     }
1392   }
1393 }
1394
1395 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1396 {
1397   myParent = theParent;
1398 }