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