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