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