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