]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
Make Name of result the same as for feature
[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 (aConstructionContext->isInfinite()) {
587         // Update the selected shape.
588         TNaming_Builder aBuilder(aSelLab);
589         aBuilder.Generated(aConstructionContext->shape()->impl<TopoDS_Shape>());
590       }
591       if (aModified)
592         owner()->data()->sendAttributeUpdated(this);
593       return aValid;
594     }
595   }
596   return setInvalidIfFalse(aSelLab, false); // unknown case
597 }
598
599 void Model_AttributeSelection::selectBody(
600   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
601 {
602   // perform the selection
603   TNaming_Selector aSel(selectionLabel());
604   TopoDS_Shape aContext;
605
606   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theContext);//myRef.value()
607   if (aBody) {
608     aContext = aBody->shape()->impl<TopoDS_Shape>();
609   } else {
610     ResultPtr aResult =
611       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
612     if (aResult) {
613       aContext = aResult->shape()->impl<TopoDS_Shape>();
614     } else {
615       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
616       return;
617     }
618   }
619
620   // with "recover" feature the selected context may be not up to date (issue 1710)
621   Handle(TNaming_NamedShape) aResult;
622   TDF_Label aSelLab = selectionLabel();
623   TopoDS_Shape aNewContext = aContext;
624   bool isUpdated = true;
625   while(!aNewContext.IsNull() && isUpdated) {
626     // searching for the very last shape that was produced from this one
627     isUpdated = false;
628     if (!TNaming_Tool::HasLabel(aSelLab, aNewContext))
629       // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
630       break;
631     for(TNaming_SameShapeIterator anIter(aNewContext, aSelLab); anIter.More(); anIter.Next()) {
632       TDF_Label aNSLab = anIter.Label();
633       if (!scope().Contains(aNSLab))
634         continue;
635       Handle(TNaming_NamedShape) aNS;
636       if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
637         for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
638           if (aShapesIter.Evolution() == TNaming_SELECTED)
639             continue; // don't use the selection evolution
640           if (!aShapesIter.OldShape().IsNull() && aShapesIter.OldShape().IsSame(aNewContext)) {
641              // found the original shape
642             aNewContext = aShapesIter.NewShape(); // go to the newer shape
643             isUpdated = true;
644             break;
645           }
646         }
647       }
648     }
649   }
650   if (aNewContext.IsNull()) { // a context is already deleted
651     setInvalidIfFalse(aSelLab, false);
652     Events_InfoMessage("Model_AttributeSelection", "Failed to select shape already deleted").send();
653     return;
654   }
655
656   TopoDS_Shape aNewSub = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
657   if (!aNewSub.IsEqual(aContext)) { // searching for subshape in the new context
658     bool isFound = false;
659     TopExp_Explorer anExp(aNewContext, aNewSub.ShapeType());
660     for(; anExp.More(); anExp.Next()) {
661       if (anExp.Current().IsEqual(aNewSub)) {
662         isFound = true;
663         break;
664       }
665     }
666     if (!isFound) { // sub-shape is not found in the up-to-date instance of the context shape
667       // if context is sub-result of compound/compsolid, selection of sub-shape better propagate to
668       // the main result (which is may be modified), case is in 1799
669       ResultCompSolidPtr aMain = ModelAPI_Tools::compSolidOwner(theContext);
670       if (aMain.get()) {
671         selectBody(aMain, theSubShape);
672         return;
673       }
674       setInvalidIfFalse(aSelLab, false);
675       Events_InfoMessage("Model_AttributeSelection",
676         "Failed to select sub-shape already modified").send();
677       return;
678     }
679   }
680
681   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
682   if (!aContext.IsNull()) {
683     FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
684     bool aEraseResults = false;
685     if (aFeatureOwner.get()) {
686       aEraseResults = !aFeatureOwner->results().empty();
687       if (aEraseResults) // erase results without flash deleted and redisplay: do it after Select
688         aFeatureOwner->removeResults(0, false, false);
689     }
690     aSel.Select(aNewSub, aNewContext);
691
692     if (aEraseResults) { // flash after Select : in Groups it makes selection with shift working
693       static Events_Loop* aLoop = Events_Loop::loop();
694       static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
695       aLoop->flush(kDeletedEvent);
696     }
697   }
698 }
699
700 bool Model_AttributeSelection::selectPart(
701   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
702   const bool theUpdate)
703 {
704   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
705   if (!aPart.get() || !aPart->isActivated())
706     return true; // postponed naming
707   if (theUpdate) {
708     Handle(TDataStd_Integer) anIndex;
709     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
710       // by internal selection
711       if (anIndex->Get() > 0) {
712         // update the selection by index
713         return aPart->updateInPart(anIndex->Get());
714       } else {
715         return true; // nothing to do, referencing just by name
716       }
717     }
718     return true; // nothing to do, referencing just by name
719   }
720   // store the shape (in case part is not loaded it should be useful
721   TopoDS_Shape aShape;
722   std::string aName = theContext->data()->name();
723   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
724     aShape = theContext->shape()->impl<TopoDS_Shape>();
725   } else {
726     aShape = theSubShape->impl<TopoDS_Shape>();
727     int anIndex;
728     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
729     TDataStd_Integer::Set(selectionLabel(), anIndex);
730   }
731   TNaming_Builder aBuilder(selectionLabel());
732   aBuilder.Select(aShape, aShape);
733   // identify by name in the part
734   TDataStd_Name::Set(selectionLabel(), aName.c_str());
735   return !aName.empty();
736 }
737
738 TDF_Label Model_AttributeSelection::selectionLabel()
739 {
740   return myRef.myRef->Label().FindChild(1);
741 }
742
743 /// prefixes of the shape names with centers defined
744 static std::map<ModelAPI_AttributeSelection::CenterType, std::string> kCENTERS_PREFIX;
745
746 /// returns the map that contains all possible prefixes of the center-names
747 static std::map<ModelAPI_AttributeSelection::CenterType, std::string>& centersMap()
748 {
749   if (kCENTERS_PREFIX.empty()) { // fill map by initial values
750     kCENTERS_PREFIX[ModelAPI_AttributeSelection::CIRCLE_CENTER] = "__cc";
751     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS] = "__eff";
752     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_SECOND_FOCUS] = "__esf";
753   }
754   return kCENTERS_PREFIX;
755 }
756
757 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
758 {
759   std::string aName("");
760   if(!this->isInitialized())
761     return !theDefaultName.empty() ? theDefaultName : aName;
762
763   CenterType aCenterType = NOT_CENTER;
764   std::shared_ptr<GeomAPI_Shape> aSubSh = internalValue(aCenterType);
765   ResultPtr aCont = context();
766
767   if (!aCont.get()) // in case of selection of removed result
768     return "";
769
770   Model_SelectionNaming aSelNaming(selectionLabel());
771   std::string aResult = aSelNaming.namingName(
772     aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
773   if (aCenterType != NOT_CENTER) {
774     aResult += centersMap()[aCenterType];
775   }
776   return aResult;
777 }
778
779 // returns the center type and modifies the shape name if this name is center-name
780 static ModelAPI_AttributeSelection::CenterType centerTypeByName(std::string& theShapeName)
781 {
782   std::map<ModelAPI_AttributeSelection::CenterType, std::string>::iterator aPrefixIter =
783     centersMap().begin();
784   for(; aPrefixIter != centersMap().end(); aPrefixIter++) {
785     std::size_t aFound = theShapeName.find(aPrefixIter->second);
786     if (aFound != std::string::npos &&
787         aFound == theShapeName.size() - aPrefixIter->second.size()) {
788       theShapeName = theShapeName.substr(0, aFound);
789       return aPrefixIter->first;
790     }
791   }
792   return ModelAPI_AttributeSelection::NOT_CENTER;
793 }
794
795 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
796 void Model_AttributeSelection::selectSubShape(
797   const std::string& theType, const std::string& theSubShapeName)
798 {
799   if(theSubShapeName.empty() || theType.empty()) return;
800
801   std::string aSubShapeName = theSubShapeName;
802   CenterType aCenterType = theType[0] == 'v' || theType[0] == 'V' ? // only for vertex-type
803     centerTypeByName(aSubShapeName) : NOT_CENTER;
804   std::string aType = aCenterType == NOT_CENTER ? theType : "EDGE"; // search for edge now
805
806   // first iteration is selection by name without center prefix, second - in case of problem,
807   // try with initial name
808   for(int aUseCenter = 1; aUseCenter >= 0; aUseCenter--) {
809     if (aUseCenter == 0 && aCenterType != NOT_CENTER) {
810       aSubShapeName = theSubShapeName;
811       aCenterType = NOT_CENTER;
812       aType = theType;
813     } else if (aUseCenter != 1) continue;
814
815     // check this is Part-name: 2 delimiters in the name
816     std::size_t aPartEnd = aSubShapeName.find('/');
817     if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
818       std::string aPartName = aSubShapeName.substr(0, aPartEnd);
819       ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
820       if (aFound.get()) { // found such part, so asking it for the name
821         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
822         std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
823         int anIndex;
824         std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, aType, anIndex);
825         if (aSelected.get()) {
826           if (aCenterType != NOT_CENTER) {
827             if (!aSelected->isEdge())
828               continue;
829             std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aSelected));
830             setValueCenter(aPart, aSelectedEdge, aCenterType);
831           } else
832             setValue(aPart, aSelected);
833           TDataStd_Integer::Set(selectionLabel(), anIndex);
834           return;
835         }
836       }
837     }
838
839     Model_SelectionNaming aSelNaming(selectionLabel());
840     std::shared_ptr<Model_Document> aDoc =
841       std::dynamic_pointer_cast<Model_Document>(owner()->document());
842     std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
843     ResultPtr aCont;
844     if (aSelNaming.selectSubShape(aType, aSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
845       // try to find the last context to find the up to date shape
846       if (aCont->shape().get() && !aCont->shape()->isNull() &&
847         aCont->groupName() == ModelAPI_ResultBody::group() && aDoc == owner()->document()) {
848         const TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
849         if (!aConShape.IsNull()) {
850           Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
851           if (!aNS.IsNull()) {
852             aNS = TNaming_Tool::CurrentNamedShape(aNS);
853             if (!aNS.IsNull() && scope().Contains(aNS->Label())) { // scope check is for 2228
854               TDF_Label aLab = aNS->Label();
855               while(aLab.Depth() != 7 && aLab.Depth() > 5)
856                 aLab = aLab.Father();
857               ObjectPtr anObj = aDoc->objects()->object(aLab);
858               if (anObj.get()) {
859                 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
860                 if (aRes)
861                   aCont = aRes;
862               }
863             }
864           }
865         }
866       }
867       if (aCenterType != NOT_CENTER) {
868         if (!aShapeToBeSelected->isEdge())
869           continue;
870         std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aShapeToBeSelected));
871         setValueCenter(aCont, aSelectedEdge, aCenterType);
872       } else
873         setValue(aCont, aShapeToBeSelected);
874       return;
875     }
876   }
877
878   TDF_Label aSelLab = selectionLabel();
879   setInvalidIfFalse(aSelLab, false);
880   reset();
881 }
882
883 int Model_AttributeSelection::Id()
884 {
885   int anID = 0;
886   std::shared_ptr<GeomAPI_Shape> aSelection = value();
887   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
888   // support for compsolids:
889   if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
890     aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
891
892
893   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
894   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
895   // searching for the latest main shape
896   if (aSelection && !aSelection->isNull() &&
897     aContext   && !aContext->isNull())
898   {
899     std::shared_ptr<Model_Document> aDoc =
900       std::dynamic_pointer_cast<Model_Document>(context()->document());
901     if (aDoc.get()) {
902       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
903       if (!aNS.IsNull()) {
904         aMainShape = TNaming_Tool::CurrentShape(aNS);
905       }
906     }
907
908     TopTools_IndexedMapOfShape aSubShapesMap;
909     TopExp::MapShapes(aMainShape, aSubShapesMap);
910     anID = aSubShapesMap.FindIndex(aSubShape);
911   }
912   return anID;
913 }
914
915 void Model_AttributeSelection::setId(int theID)
916 {
917   const ResultPtr& aContext = context();
918   std::shared_ptr<GeomAPI_Shape> aSelection;
919
920   std::shared_ptr<GeomAPI_Shape> aContextShape = aContext->shape();
921   // support for compsolids:
922   if (aContext.get() && ModelAPI_Tools::compSolidOwner(aContext).get())
923     aContextShape = ModelAPI_Tools::compSolidOwner(aContext)->shape();
924
925   TopoDS_Shape aMainShape = aContextShape->impl<TopoDS_Shape>();
926   // searching for the latest main shape
927   if (theID > 0 &&
928       aContextShape && !aContextShape->isNull())
929   {
930     std::shared_ptr<Model_Document> aDoc =
931       std::dynamic_pointer_cast<Model_Document>(aContext->document());
932     if (aDoc.get()) {
933       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
934       if (!aNS.IsNull()) {
935         aMainShape = TNaming_Tool::CurrentShape(aNS);
936       }
937     }
938
939     TopTools_IndexedMapOfShape aSubShapesMap;
940     TopExp::MapShapes(aMainShape, aSubShapesMap);
941     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
942
943     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
944     aResult->setImpl(new TopoDS_Shape(aSelShape));
945
946     aSelection = aResult;
947   }
948
949   setValue(aContext, aSelection);
950 }
951
952 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
953 {
954   std::string aResult;
955   if (owner()->document() != theContext->document()) {
956     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
957       aResult = theContext->document()->kind() + "/";
958     } else {
959       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
960         ModelAPI_Session::get()->moduleDocument(), theContext->document());
961       if (aDocRes.get()) {
962         aResult = aDocRes->data()->name() + "/";
963       }
964     }
965   }
966   aResult += theContext->data()->name();
967   return aResult;
968 }
969
970 void Model_AttributeSelection::computeValues(
971   ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
972   TopTools_ListOfShape& theShapes)
973 {
974   bool aWasWholeContext = theValShape.IsNull();
975   if (aWasWholeContext) {
976     //theShapes.Append(theValShape);
977     //return;
978     theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
979   }
980   //TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
981   TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
982   //if (anOldContShape.IsSame(theValShape)) { // full context shape substituted by new full context
983     //theShapes.Append(aNewContShape);
984     //return;
985   //}
986   // if a new value is unchanged in the new context, do nothing: value is correct
987   TopExp_Explorer aSubExp(aNewContShape, theValShape.ShapeType());
988   for(; aSubExp.More(); aSubExp.Next()) {
989     if (aSubExp.Current().IsSame(theValShape)) {
990       theShapes.Append(theValShape);
991       return;
992     }
993   }
994   // if new context becomes compsolid, the resulting sub may be in sub-solids
995   std::list<ResultPtr> aNewToIterate;
996   aNewToIterate.push_back(theNewContext);
997   ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theNewContext);
998   if (aComp.get()) {
999     for(int a = 0; a < aComp->numberOfSubs(); a++)
1000       aNewToIterate.push_back(aComp->subResult(a, false));
1001   }
1002
1003   // first iteration: searching for the whole shape appearance (like face of the box)
1004   // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
1005   int aToFindPart = 0;
1006   TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
1007   TopTools_MapOfShape anOlds; // to know how many olds produced new containers
1008   for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
1009     std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
1010     for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
1011       std::shared_ptr<Model_Data> aNewData =
1012         std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
1013       TDF_Label aNewLab = aNewData->label();
1014       // searching for produced sub-shape fully on some label
1015       TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID(), Standard_True);
1016       for(; aNSIter.More(); aNSIter.Next()) {
1017         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1018         for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
1019           if (aToFindPart == 0) { // search shape is fully inside
1020             if (aPairIter.OldShape().IsSame(theValShape)) {
1021               if (aPairIter.NewShape().IsNull()) {// value was removed
1022                 theShapes.Clear();
1023                 return;
1024               }
1025               theShapes.Append(aPairIter.NewShape());
1026             }
1027           } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
1028             TopExp_Explorer anExp(aPairIter.OldShape(), theValShape.ShapeType());
1029             for(; anExp.More(); anExp.Next()) {
1030               if (anExp.Current().IsSame(theValShape)) { // found a new container
1031                 if (aPairIter.NewShape().IsNull()) {// value was removed
1032                   theShapes.Clear();
1033                   return;
1034                 }
1035                 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
1036                 anOlds.Add(aPairIter.OldShape());
1037                 break;
1038               }
1039             }
1040           }
1041         }
1042       }
1043     }
1044   }
1045   if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
1046     // map of sub-shapes -> number of occurences of these shapes in containers
1047     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
1048     TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
1049     for(; aContIter.More(); aContIter.Next()) {
1050       TopExp_Explorer aSubExp(aContIter.Key(), theValShape.ShapeType());
1051       for(; aSubExp.More(); aSubExp.Next()) {
1052         if (!aSubs.IsBound(aSubExp.Current())) {
1053           aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
1054         }
1055         // store old to know how many olds produced this shape
1056         aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
1057       }
1058     }
1059     // if sub is appeared same times in containers as the number of old shapes that contain it
1060     int aCountInOld = anOlds.Size();
1061     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
1062       aSubsIter(aSubs);
1063     for(; aSubsIter.More(); aSubsIter.Next()) {
1064       if (aSubsIter.Value().Size() == aCountInOld) {
1065         theShapes.Append(aSubsIter.Key());
1066       }
1067     }
1068   }
1069   if (theShapes.IsEmpty()) { // nothing was changed
1070     theShapes.Append(aWasWholeContext ? TopoDS_Shape() : theValShape);
1071   }
1072 }
1073
1074 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
1075   const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
1076   TDF_Label theAccessLabel,
1077   std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
1078 {
1079   std::set<ResultPtr> aResults; // to avoid duplicates, new context, null if deleted
1080   TopTools_ListOfShape aResContShapes;
1081   TNaming_SameShapeIterator aModifIter(theContShape, theAccessLabel);
1082   for(; aModifIter.More(); aModifIter.Next()) {
1083     TDF_Label anObjLab = aModifIter.Label().Father();
1084     ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1085       (theDoc->objects()->object(anObjLab));
1086     if (!aModifierObj.get()) {
1087       // #2241: shape may be sub-element of new object, not main (shell created from faces)
1088       if (!anObjLab.IsRoot())
1089         aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1090         (theDoc->objects()->object(anObjLab.Father()));
1091       if (!aModifierObj.get())
1092         continue;
1093     }
1094     FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
1095     if (!aModifierFeat.get())
1096       continue;
1097     FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1098     if (aModifierFeat == aThisFeature || theDoc->objects()->isLater(aModifierFeat, aThisFeature))
1099       continue; // the modifier feature is later than this, so, should not be used
1100     FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
1101     if (aCurrentModifierFeat == aModifierFeat ||
1102       theDoc->objects()->isLater(aCurrentModifierFeat, aModifierFeat))
1103       continue; // the current modifier is later than the found, so, useless
1104     Handle(TNaming_NamedShape) aNewNS;
1105     aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1106     if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1107       aResults.insert(aModifierObj);
1108       //TNaming_Iterator aPairIter(aNewNS);
1109       //aResContShapes.Append(aPairIter.NewShape());
1110       aResContShapes.Append(aModifierObj->shape()->impl<TopoDS_Shape>());
1111     } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
1112       aResults.insert(ResultPtr());
1113     } else { // not-precessed modification => don't support it
1114       continue;
1115     }
1116   }
1117   if (aResults.empty())
1118     return false; // no modifications found, must stay the same
1119   // iterate all results to find futher modifications
1120   std::set<ResultPtr>::iterator aResIter = aResults.begin();
1121   for(; aResIter != aResults.end(); aResIter++) {
1122     if (aResIter->get() != NULL) {
1123       // compute new values by two contextes: the old and the new
1124       TopTools_ListOfShape aValShapes;
1125       computeValues(theContext, *aResIter, theValShape, aValShapes);
1126
1127       TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
1128       for(; aNewVal.More(); aNewVal.Next()) {
1129         std::list<ResultPtr> aNewRes;
1130         TopTools_ListOfShape aNewUpdatedVal;
1131         TopoDS_Shape aNewValSh = aNewVal.Value();
1132         TopoDS_Shape aNewContShape = (*aResIter)->shape()->impl<TopoDS_Shape>();
1133         if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
1134           aNewValSh.Nullify();
1135         if (searchNewContext(theDoc, aNewContShape, *aResIter, aNewValSh,
1136                              theAccessLabel, aNewRes, aNewUpdatedVal))
1137         {
1138           // appeand new results instead of the current ones
1139           std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1140           TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1141           for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1142             theResults.push_back(*aNewIter);
1143             theValShapes.Append(aNewUpdVal.Value());
1144           }
1145         } else { // the current result is good
1146           theResults.push_back(*aResIter);
1147           theValShapes.Append(aNewValSh);
1148         }
1149       }
1150     }
1151   }
1152   return true; // theResults must be empty: everything is deleted
1153 }
1154
1155 void Model_AttributeSelection::updateInHistory()
1156 {
1157   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1158   // only bodies and parts may be modified later in the history, don't do anything otherwise
1159   if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
1160       aContext->groupName() != ModelAPI_ResultPart::group()))
1161     return;
1162   std::shared_ptr<Model_Document> aDoc =
1163     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1164   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1165   if (!aContData.get() || !aContData->isValid())
1166     return;
1167   TDF_Label aContLab = aContData->label(); // named shape where the selected context is located
1168   Handle(TNaming_NamedShape) aContNS;
1169   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
1170     bool aFoundNewContext = true;
1171     ResultPtr aNewContext = aContext;
1172     while(aFoundNewContext) {
1173       aFoundNewContext = false;
1174       // parts have no shape in result, so, trace references using the Part info
1175       if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
1176         ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
1177         if (aPartContext.get()) { // searching for the up to date references to the referenced cont
1178           const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
1179           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1180           for(; aRef != aRefs.end(); aRef++) {
1181             // to avoid detection of part changes by local selection only
1182             AttributeSelectionPtr aSel =
1183               std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1184             if (aSel.get() && !aSel->value()->isSame(aSel->context()->shape()))
1185               continue;
1186
1187             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1188             if (aRefFeat.get() && aRefFeat != owner()) {
1189               FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1190               if (aDoc->objects()->isLater(aThisFeature, aRefFeat)) { // found better feature
1191                 aFoundNewContext = true;
1192                 aNewContext = aRefFeat->firstResult();
1193               }
1194             }
1195           }
1196         }
1197       }
1198     }
1199     if (aNewContext != aContext) {
1200       setValue(aNewContext, value());
1201     }
1202     return;
1203   }
1204   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1205   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1206   // iterate the context shape modifications in order to find a feature that is upper in history
1207   // that this one and is really modifies the referenced result to refer to it
1208   ResultPtr aModifierResFound;
1209   TNaming_Iterator aPairIter(aContNS);
1210   if (!aPairIter.More())
1211     return;
1212   TopoDS_Shape aNewCShape = aPairIter.NewShape();
1213   bool anIterate = true;
1214   // trying to update also the sub-shape selected
1215   GeomShapePtr aSubShape = value();
1216   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1217     aSubShape.reset();
1218   TopoDS_Shape aValShape;
1219   if (aSubShape.get()) {
1220     aValShape = aSubShape->impl<TopoDS_Shape>();
1221   }
1222
1223   std::list<ResultPtr> aNewContexts;
1224   TopTools_ListOfShape aValShapes;
1225   if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1226   {
1227     // update scope to reset to a new one
1228     myScope.Clear();
1229
1230     std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1231     TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1232     if (aNewCont == aNewContexts.end()) { // all results were deleted
1233       ResultPtr anEmptyContext;
1234       std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1235       setValue(anEmptyContext, anEmptyShape); // nullify the selection
1236       return;
1237     }
1238
1239     GeomShapePtr aValueShape;
1240     if (!aNewValues.Value().IsNull()) {
1241       aValueShape = std::make_shared<GeomAPI_Shape>();
1242       aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1243     }
1244     setValue(*aNewCont, aValueShape);
1245     // if there are more than one result, put them by "append" into "parent" list
1246     if (myParent) {
1247       for(aNewCont++, aNewValues.Next(); aNewCont != aNewContexts.end();
1248           aNewCont++, aNewValues.Next()) {
1249         GeomShapePtr aValueShape;
1250         if (!aNewValues.Value().IsNull()) {
1251           aValueShape = std::make_shared<GeomAPI_Shape>();
1252           aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1253         }
1254         myParent->append(*aNewCont, aValueShape);
1255       }
1256     }
1257   }
1258 }
1259
1260 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1261 {
1262   myParent = theParent;
1263 }