]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
Debug of the external ellipse center selection.
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_AttributeSelection.cpp
4 // Created:     2 Oct 2014
5 // Author:      Mikhail PONIKAROV
6
7 #include "Model_AttributeSelection.h"
8 #include "Model_Application.h"
9 #include "Model_Events.h"
10 #include "Model_Data.h"
11 #include "Model_Document.h"
12 #include "Model_SelectionNaming.h"
13 #include <Model_Objects.h>
14 #include <Model_AttributeSelectionList.h>
15 #include <Model_ResultConstruction.h>
16 #include <ModelAPI_Feature.h>
17 #include <ModelAPI_ResultBody.h>
18 #include <ModelAPI_ResultCompSolid.h>
19 #include <ModelAPI_ResultConstruction.h>
20 #include <ModelAPI_ResultPart.h>
21 #include <ModelAPI_CompositeFeature.h>
22 #include <ModelAPI_Tools.h>
23 #include <ModelAPI_Session.h>
24 #include <Events_InfoMessage.h>
25 #include <GeomAPI_Edge.h>
26 #include <GeomAPI_Vertex.h>
27
28 #include <TNaming_Selector.hxx>
29 #include <TNaming_NamedShape.hxx>
30 #include <TNaming_Tool.hxx>
31 #include <TNaming_Builder.hxx>
32 #include <TNaming_SameShapeIterator.hxx>
33 #include <TNaming_Iterator.hxx>
34 #include <TDataStd_Integer.hxx>
35 #include <TDataStd_UAttribute.hxx>
36 #include <TDataStd_Name.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopExp_Explorer.hxx>
39 #include <BRep_Tool.hxx>
40 #include <TopoDS.hxx>
41 #include <TopExp.hxx>
42 #include <TDF_ChildIterator.hxx>
43 #include <TDF_ChildIDIterator.hxx>
44 #include <TopoDS_Iterator.hxx>
45 #include <Geom_Circle.hxx>
46 #include <Geom_Ellipse.hxx>
47 #include <BRep_Builder.hxx>
48
49 //#define DEB_NAMING 1
50 #ifdef DEB_NAMING
51 #include <BRepTools.hxx>
52 #endif
53 /// added to the index in the packed map to signalize that the vertex of edge is selected
54 /// (multiplied by the index of the edge)
55 static const int kSTART_VERTEX_DELTA = 1000000;
56 // identifier that there is simple reference: selection equals to context
57 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
58 // reference to Part sub-object
59 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
60 // selection is invalid after recomputation
61 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
62
63 // identifier of the selection of the center of circle on edge
64 Standard_GUID kCIRCLE_CENTER("d0d0e0f1-217a-4b95-8fbb-0c4132f23718");
65 // identifier of the selection of the first focus point of ellipse on edge
66 Standard_GUID kELLIPSE_CENTER1("f70df04c-3168-4dc9-87a4-f1f840c1275d");
67 // identifier of the selection of the second focus point of ellipse on edge
68 Standard_GUID kELLIPSE_CENTER2("1395ae73-8e02-4cf8-b204-06ff35873a32");
69
70 // on this label is stored:
71 // TNaming_NamedShape - selected shape
72 // TNaming_Naming - topological selection information (for the body)
73 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
74 // TDataStd_Integer - type of the selected shape (for construction)
75 // TDF_Reference - from ReferenceAttribute, the context
76 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
77   const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
78 {
79   if (theTemporarily) { // just keep the stored without DF update
80     myTmpContext = theContext;
81     myTmpSubShape = theSubShape;
82     owner()->data()->sendAttributeUpdated(this);
83     return;
84   } else {
85     myTmpContext.reset();
86     myTmpSubShape.reset();
87     myTmpCenterType = NOT_CENTER;
88   }
89
90   const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
91   bool isOldContext = theContext == myRef.value();
92   bool isOldShape = isOldContext &&
93     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
94   if (isOldShape) return; // shape is the same, so context is also unchanged
95   // update the referenced object if needed
96   if (!isOldContext) {
97       myRef.setValue(theContext);
98   }
99
100   // do noth use naming if selected shape is result shape itself, but not sub-shape
101   TDF_Label aSelLab = selectionLabel();
102   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
103   aSelLab.ForgetAttribute(kINVALID_SELECTION);
104   aSelLab.ForgetAttribute(kCIRCLE_CENTER);
105   aSelLab.ForgetAttribute(kELLIPSE_CENTER1);
106   aSelLab.ForgetAttribute(kELLIPSE_CENTER2);
107
108   bool isDegeneratedEdge = false;
109   // do not use the degenerated edge as a shape, a null context and shape is used in the case
110   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
111     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
112     if (aSubShape.ShapeType() == TopAbs_EDGE)
113       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
114   }
115   if (!theContext.get() || isDegeneratedEdge) {
116     // to keep the reference attribute label
117     TDF_Label aRefLab = myRef.myRef->Label();
118     aSelLab.ForgetAllAttributes(true);
119     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
120     return;
121   }
122   if (theContext->groupName() == ModelAPI_ResultBody::group()) {
123     // do not select the whole shape for body:it is already must be in the data framework
124     // equal and null selected objects mean the same: object is equal to context,
125     if (theContext->shape().get() &&
126         (theContext->shape()->isEqual(theSubShape) || !theSubShape.get())) {
127       aSelLab.ForgetAllAttributes(true);
128       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
129     } else {
130       selectBody(theContext, theSubShape);
131     }
132   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
133     aSelLab.ForgetAllAttributes(true); // to remove old selection data
134     std::shared_ptr<Model_ResultConstruction> aConstruction =
135       std::dynamic_pointer_cast<Model_ResultConstruction>(theContext);
136     std::shared_ptr<GeomAPI_Shape> aSubShape;
137     if (theSubShape.get() && !theContext->shape()->isEqual(theSubShape))
138       aSubShape = theSubShape; // the whole context
139     int anIndex = aConstruction->select(theSubShape, owner()->document());
140     TDataStd_Integer::Set(aSelLab, anIndex);
141   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
142     aSelLab.ForgetAllAttributes(true);
143     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
144     selectPart(theContext, theSubShape);
145   }
146
147   owner()->data()->sendAttributeUpdated(this);
148 }
149
150 void Model_AttributeSelection::setValueCenter(
151     const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Edge>& theEdge,
152     const CenterType theCenterType, const bool theTemporarily)
153 {
154   setValue(theContext, theEdge, theTemporarily);
155   if (theTemporarily) {
156     myTmpCenterType = theCenterType;
157   } else { // store in the data structure
158     TDF_Label aSelLab = selectionLabel();
159     switch(theCenterType) {
160     case CIRCLE_CENTER:
161       TDataStd_UAttribute::Set(aSelLab, kCIRCLE_CENTER);
162       break;
163     case ELLIPSE_FIRST_FOCUS:
164       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER1);
165       break;
166     case ELLIPSE_SECOND_FOCUS:
167       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER2);
168       break;
169     }
170     owner()->data()->sendAttributeUpdated(this);
171   }
172 }
173
174
175 void Model_AttributeSelection::removeTemporaryValues()
176 {
177   if (myTmpContext.get() || myTmpSubShape.get()) {
178     myTmpContext.reset();
179     myTmpSubShape.reset();
180   }
181 }
182
183 // returns the center of the edge: circular or elliptical
184 GeomShapePtr centerByEdge(GeomShapePtr theEdge, ModelAPI_AttributeSelection::CenterType theType)
185 {
186   if (theType != ModelAPI_AttributeSelection::NOT_CENTER && theEdge.get() != NULL) {
187     TopoDS_Shape aShape = theEdge->impl<TopoDS_Shape>();
188     if (!aShape.IsNull() && aShape.ShapeType() == TopAbs_EDGE) {
189       TopoDS_Edge anEdge = TopoDS::Edge(aShape);
190       double aFirst, aLast;
191       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
192       if (!aCurve.IsNull()) {
193         TopoDS_Vertex aVertex;
194         BRep_Builder aBuilder;
195         if (theType == ModelAPI_AttributeSelection::CIRCLE_CENTER) {
196           Handle(Geom_Circle) aCirc = Handle(Geom_Circle)::DownCast(aCurve);
197           if (!aCirc.IsNull()) {
198             aBuilder.MakeVertex(aVertex, aCirc->Location(), Precision::Confusion());
199           }
200         } else { // ellipse
201           Handle(Geom_Ellipse) anEll = Handle(Geom_Ellipse)::DownCast(aCurve);
202           if (!anEll.IsNull()) {
203             aBuilder.MakeVertex(aVertex,
204               theType == ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS ?
205               anEll->Focus1() : anEll->Focus2(), Precision::Confusion());
206           }
207         }
208         if (!aVertex.IsNull()) {
209           std::shared_ptr<GeomAPI_Vertex> aResult(new GeomAPI_Vertex);
210           aResult->setImpl(new TopoDS_Vertex(aVertex));
211           return aResult;
212         }
213       }
214     }
215   }
216   return theEdge; // no vertex, so, return the initial edge
217 }
218
219 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
220 {
221   GeomShapePtr aResult;
222   if (myTmpContext.get() || myTmpSubShape.get()) {
223     ResultConstructionPtr aResulConstruction =
224       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myTmpContext);
225     if(aResulConstruction.get()) {
226       // it is just reference to construction.
227       return centerByEdge(myTmpSubShape, myTmpCenterType);
228     }
229     return centerByEdge(myTmpSubShape.get() ? myTmpSubShape : myTmpContext->shape(),
230                         myTmpCenterType);
231   }
232
233   TDF_Label aSelLab = selectionLabel();
234   if (aSelLab.IsAttribute(kINVALID_SELECTION))
235     return aResult;
236
237   CenterType aType = NOT_CENTER;
238   if (aSelLab.IsAttribute(kCIRCLE_CENTER))
239     aType = CIRCLE_CENTER;
240   else if (aSelLab.IsAttribute(kELLIPSE_CENTER1))
241     aType = ELLIPSE_FIRST_FOCUS;
242   else if (aSelLab.IsAttribute(kELLIPSE_CENTER2))
243     aType = ELLIPSE_SECOND_FOCUS;
244
245
246   if (myRef.isInitialized()) {
247     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
248       ResultPtr aContext = context();
249       if (!aContext.get())
250         return aResult; // empty result
251       return centerByEdge(aContext->shape(), aType);
252     }
253     if (aSelLab.IsAttribute(kPART_REF_ID)) {
254       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
255       if (!aPart.get() || !aPart->isActivated())
256         return aResult; // postponed naming needed
257       Handle(TDataStd_Integer) anIndex;
258       if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
259         if (anIndex->Get()) { // special selection attribute was created, use it
260           return centerByEdge(aPart->selectionValue(anIndex->Get()), aType);
261         } else { // face with name is already in the data model, so try to take it by name
262           Handle(TDataStd_Name) aName;
263           if (aSelLab.FindAttribute(TDataStd_Name::GetID(), aName)) {
264             std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
265             std::size_t aPartEnd = aSubShapeName.find('/');
266             if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
267               std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
268               int anIndex;
269               std::string aTypeStr; // to reuse already existing selection the type is not needed
270               return centerByEdge(aPart->shapeInPart(aNameInPart, aTypeStr, anIndex), aType);
271             }
272           }
273         }
274       }
275     }
276
277     Handle(TNaming_NamedShape) aSelection;
278     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
279       TopoDS_Shape aSelShape = aSelection->Get();
280       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
281       aResult->setImpl(new TopoDS_Shape(aSelShape));
282       return centerByEdge(aResult, aType);
283     } else { // for simple construction element: just shape of this construction element
284       std::shared_ptr<Model_ResultConstruction> aConstr =
285         std::dynamic_pointer_cast<Model_ResultConstruction>(context());
286       if (aConstr) {
287         Handle(TDataStd_Integer) anIndex;
288         if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
289           if (anIndex->Get() == 0) // it is just reference to construction, nothing is in value
290             return centerByEdge(aResult, aType);
291           return centerByEdge(aConstr->shape(anIndex->Get(), owner()->document()), aType);
292         }
293       }
294     }
295   }
296   return aResult; // empty case
297 }
298
299 bool Model_AttributeSelection::isInvalid()
300 {
301   return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
302 }
303
304 bool Model_AttributeSelection::isInitialized()
305 {
306   if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
307     std::shared_ptr<GeomAPI_Shape> aResult;
308     if (myRef.isInitialized()) {
309       TDF_Label aSelLab = selectionLabel();
310       if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
311         ResultPtr aContext = context();
312         return aContext.get() != NULL;
313       }
314       Handle(TNaming_NamedShape) aSelection;
315       if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
316         return !aSelection->Get().IsNull();
317       } else { // for simple construction element: just shape of this construction element
318         std::shared_ptr<Model_ResultConstruction> aConstr =
319           std::dynamic_pointer_cast<Model_ResultConstruction>(context());
320         if (aConstr.get()) {
321           Handle(TDataStd_Integer) anIndex;
322           if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
323             // for the whole shape it may return null, so, if index exists, returns true
324             return true;
325           }
326         }
327       }
328     }
329   }
330   return false;
331 }
332
333 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
334   : myRef(theLabel)
335 {
336   myIsInitialized = myRef.isInitialized();
337   myParent = NULL;
338 }
339
340 void Model_AttributeSelection::setID(const std::string theID)
341 {
342   myRef.setID(theID);
343   ModelAPI_AttributeSelection::setID(theID);
344 }
345
346 ResultPtr Model_AttributeSelection::context() {
347   if (myTmpContext.get() || myTmpSubShape.get()) {
348     return myTmpContext;
349   }
350
351   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
352   // for parts there could be same-data result, so take the last enabled
353   if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
354     int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
355     for(int a = aSize - 1; a >= 0; a--) {
356       ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
357       if (aPart.get() && aPart->data() == aResult->data()) {
358         ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
359         FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
360         // check that this result is not this-feature result (it is forbidden t oselect itself)
361         if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
362           return aPartResult;
363         }
364       }
365     }
366   }
367   return aResult;
368 }
369
370
371 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
372 {
373   ModelAPI_AttributeSelection::setObject(theObject);
374   myRef.setObject(theObject);
375 }
376
377 TDF_LabelMap& Model_AttributeSelection::scope()
378 {
379   if (myScope.IsEmpty()) { // create a new scope if not yet done
380     // gets all features with named shapes that are before this feature label (before in history)
381     DocumentPtr aMyDoc = owner()->document();
382     std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
383     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
384     bool aMePassed = false;
385     CompositeFeaturePtr aComposite =
386       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
387     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
388     CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
389     if (aFeature.get()) {
390       aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
391       if (aCompositeOwner.get()) {
392          aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
393       }
394     }
395     // for group Scope is not limitet: this is always up to date objects
396     bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
397     for(; aFIter != allFeatures.end(); aFIter++) {
398       if (*aFIter == owner()) {  // the left features are created later (except subs of composite)
399         aMePassed = true;
400         continue;
401       }
402       if (isGroup) aMePassed = false;
403       bool isInScope = !aMePassed;
404       if (!isInScope && aComposite.get()) {
405         // try to add sub-elements of composite if this is composite
406         if (aComposite->isSub(*aFIter))
407           isInScope = true;
408       }
409       // remove the composite-owner of this feature (sketch in extrusion-cut)
410       if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
411         isInScope = false;
412
413       if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
414         TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
415           (*aFIter)->data())->label().Father();
416         TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), true);
417         for(; aNSIter.More(); aNSIter.Next()) {
418           Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
419           if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
420             myScope.Add(aNS->Label());
421           }
422         }
423       }
424     }
425     // also add all naming labels created for external constructions
426     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(aMyDoc);
427     TDF_Label anExtDocLab = aDoc->extConstructionsLabel();
428     TDF_ChildIDIterator aNSIter(anExtDocLab, TNaming_NamedShape::GetID(), true);
429     for(; aNSIter.More(); aNSIter.Next()) {
430       Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
431       if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
432         myScope.Add(aNS->Label());
433       }
434     }
435   }
436   return myScope;
437 }
438
439 /// Sets the invalid flag if flag is false, or removes it if "true"
440 /// Returns theFlag
441 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
442   if (theFlag) {
443     theLab.ForgetAttribute(kINVALID_SELECTION);
444   } else {
445     TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
446   }
447   return theFlag;
448 }
449
450 void Model_AttributeSelection::split(
451   ResultPtr theContext, TopoDS_Shape theNewShape, TopAbs_ShapeEnum theType)
452 {
453   TopTools_ListOfShape aSubs;
454   for(TopoDS_Iterator anExplorer(theNewShape); anExplorer.More(); anExplorer.Next()) {
455     if (!anExplorer.Value().IsNull() &&
456       anExplorer.Value().ShapeType() == theType) {
457         aSubs.Append(anExplorer.Value());
458     } else { // invalid case; bad result shape, so, impossible to split easily
459       aSubs.Clear();
460       break;
461     }
462   }
463   if (aSubs.Extent() > 1) { // ok to split
464     TopTools_ListIteratorOfListOfShape aSub(aSubs);
465     GeomShapePtr aSubSh(new GeomAPI_Shape);
466     aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
467     setValue(theContext, aSubSh);
468     for(aSub.Next(); aSub.More(); aSub.Next()) {
469       GeomShapePtr aSubSh(new GeomAPI_Shape);
470       aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
471       myParent->append(theContext, aSubSh);
472     }
473   }
474 }
475
476 bool Model_AttributeSelection::update()
477 {
478   TDF_Label aSelLab = selectionLabel();
479   ResultPtr aContext = context();
480   if (!aContext.get())
481     return setInvalidIfFalse(aSelLab, false);
482   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
483     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
484   }
485
486   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
487     std::shared_ptr<GeomAPI_Shape> aNoSelection;
488     bool aResult = selectPart(aContext, aNoSelection, true);
489     aResult = setInvalidIfFalse(aSelLab, aResult);
490     if (aResult) {
491       owner()->data()->sendAttributeUpdated(this);
492     }
493     return aResult;
494   }
495
496   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
497     // body: just a named shape, use selection mechanism from OCCT
498     TNaming_Selector aSelector(aSelLab);
499     TopoDS_Shape anOldShape;
500     if (!aSelector.NamedShape().IsNull()) {
501       anOldShape = aSelector.NamedShape()->Get();
502     }
503     bool aResult = aSelector.Solve(scope()) == Standard_True;
504     // must be before sending of updated attribute (1556)
505     aResult = setInvalidIfFalse(aSelLab, aResult);
506     TopoDS_Shape aNewShape;
507     if (!aSelector.NamedShape().IsNull()) {
508       aNewShape = aSelector.NamedShape()->Get();
509     }
510     if (anOldShape.IsNull() || aNewShape.IsNull() ||
511         !anOldShape.IsEqual(aSelector.NamedShape()->Get())) {
512       // shape type shoud not not changed: if shape becomes compound of such shapes, then split
513       if (myParent && !anOldShape.IsNull() && !aNewShape.IsNull() &&
514           anOldShape.ShapeType() != aNewShape.ShapeType() &&
515           (aNewShape.ShapeType() == TopAbs_COMPOUND || aNewShape.ShapeType() == TopAbs_COMPSOLID))
516       {
517         split(aContext, aNewShape, anOldShape.ShapeType());
518       }
519       owner()->data()->sendAttributeUpdated(this);  // send updated if shape is changed
520     }
521     return aResult;
522   }
523
524   if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
525     Handle(TDataStd_Integer) anIndex;
526     if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
527       std::shared_ptr<Model_ResultConstruction> aConstructionContext =
528         std::dynamic_pointer_cast<Model_ResultConstruction>(aContext);
529       bool aModified = true;
530       bool aValid = aConstructionContext->update(anIndex->Get(), owner()->document(), aModified);
531       setInvalidIfFalse(aSelLab, aValid);
532       if (aModified)
533         owner()->data()->sendAttributeUpdated(this);
534       return aValid;
535     }
536   }
537   return setInvalidIfFalse(aSelLab, false); // unknown case
538 }
539
540 void Model_AttributeSelection::selectBody(
541   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
542 {
543   // perform the selection
544   TNaming_Selector aSel(selectionLabel());
545   TopoDS_Shape aContext;
546
547   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theContext);//myRef.value()
548   if (aBody) {
549     aContext = aBody->shape()->impl<TopoDS_Shape>();
550   } else {
551     ResultPtr aResult =
552       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
553     if (aResult) {
554       aContext = aResult->shape()->impl<TopoDS_Shape>();
555     } else {
556       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
557       return;
558     }
559   }
560
561   // with "recover" feature the selected context may be not up to date (issue 1710)
562   Handle(TNaming_NamedShape) aResult;
563   TDF_Label aSelLab = selectionLabel();
564   TopoDS_Shape aNewContext = aContext;
565   bool isUpdated = true;
566   while(!aNewContext.IsNull() && isUpdated) {
567     // searching for the very last shape that was produced from this one
568     isUpdated = false;
569     if (!TNaming_Tool::HasLabel(aSelLab, aNewContext))
570       // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
571       break;
572     for(TNaming_SameShapeIterator anIter(aNewContext, aSelLab); anIter.More(); anIter.Next()) {
573       TDF_Label aNSLab = anIter.Label();
574       if (!scope().Contains(aNSLab))
575         continue;
576       Handle(TNaming_NamedShape) aNS;
577       if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
578         for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
579           if (aShapesIter.Evolution() == TNaming_SELECTED)
580             continue; // don't use the selection evolution
581           if (!aShapesIter.OldShape().IsNull() && aShapesIter.OldShape().IsSame(aNewContext)) {
582              // found the original shape
583             aNewContext = aShapesIter.NewShape(); // go to the newer shape
584             isUpdated = true;
585             break;
586           }
587         }
588       }
589     }
590   }
591   if (aNewContext.IsNull()) { // a context is already deleted
592     setInvalidIfFalse(aSelLab, false);
593     Events_InfoMessage("Model_AttributeSelection", "Failed to select shape already deleted").send();
594     return;
595   }
596
597   TopoDS_Shape aNewSub = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
598   if (!aNewSub.IsEqual(aContext)) { // searching for subshape in the new context
599     bool isFound = false;
600     TopExp_Explorer anExp(aNewContext, aNewSub.ShapeType());
601     for(; anExp.More(); anExp.Next()) {
602       if (anExp.Current().IsEqual(aNewSub)) {
603         isFound = true;
604         break;
605       }
606     }
607     if (!isFound) { // sub-shape is not found in the up-to-date instance of the context shape
608       // if context is sub-result of compound/compsolid, selection of sub-shape better propagate to
609       // the main result (which is may be modified), case is in 1799
610       ResultCompSolidPtr aMain = ModelAPI_Tools::compSolidOwner(theContext);
611       if (aMain.get()) {
612         selectBody(aMain, theSubShape);
613         return;
614       }
615       setInvalidIfFalse(aSelLab, false);
616       Events_InfoMessage("Model_AttributeSelection",
617         "Failed to select sub-shape already modified").send();
618       return;
619     }
620   }
621
622   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
623   if (!aContext.IsNull()) {
624     FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
625     bool aEraseResults = false;
626     if (aFeatureOwner.get()) {
627       aEraseResults = !aFeatureOwner->results().empty();
628       if (aEraseResults) // erase results without flash deleted and redisplay: do it after Select
629         aFeatureOwner->removeResults(0, false, false);
630     }
631     aSel.Select(aNewSub, aNewContext);
632
633     if (aEraseResults) { // flash after Select : in Groups it makes selection with shift working
634       static Events_Loop* aLoop = Events_Loop::loop();
635       static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
636       aLoop->flush(kDeletedEvent);
637     }
638   }
639 }
640
641 bool Model_AttributeSelection::selectPart(
642   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
643   const bool theUpdate)
644 {
645   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
646   if (!aPart.get() || !aPart->isActivated())
647     return true; // postponed naming
648   if (theUpdate) {
649     Handle(TDataStd_Integer) anIndex;
650     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
651       // by internal selection
652       if (anIndex->Get() > 0) {
653         // update the selection by index
654         return aPart->updateInPart(anIndex->Get());
655       } else {
656         return true; // nothing to do, referencing just by name
657       }
658     }
659     return true; // nothing to do, referencing just by name
660   }
661   // store the shape (in case part is not loaded it should be useful
662   TopoDS_Shape aShape;
663   std::string aName = theContext->data()->name();
664   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
665     aShape = theContext->shape()->impl<TopoDS_Shape>();
666   } else {
667     aShape = theSubShape->impl<TopoDS_Shape>();
668     int anIndex;
669     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
670     TDataStd_Integer::Set(selectionLabel(), anIndex);
671   }
672   TNaming_Builder aBuilder(selectionLabel());
673   aBuilder.Select(aShape, aShape);
674   // identify by name in the part
675   TDataStd_Name::Set(selectionLabel(), aName.c_str());
676   return !aName.empty();
677 }
678
679 TDF_Label Model_AttributeSelection::selectionLabel()
680 {
681   return myRef.myRef->Label().FindChild(1);
682 }
683
684 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
685 {
686   std::string aName("");
687   if(!this->isInitialized())
688     return !theDefaultName.empty() ? theDefaultName : aName;
689
690   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
691   ResultPtr aCont = context();
692
693   if (!aCont.get()) // in case of selection of removed result
694     return "";
695
696   Model_SelectionNaming aSelNaming(selectionLabel());
697   return aSelNaming.namingName(
698     aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
699 }
700
701 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
702 void Model_AttributeSelection::selectSubShape(
703   const std::string& theType, const std::string& theSubShapeName)
704 {
705   if(theSubShapeName.empty() || theType.empty()) return;
706
707   // check this is Part-name: 2 delimiters in the name
708   std::size_t aPartEnd = theSubShapeName.find('/');
709   if (aPartEnd != std::string::npos && aPartEnd != theSubShapeName.rfind('/')) {
710     std::string aPartName = theSubShapeName.substr(0, aPartEnd);
711     ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
712     if (aFound.get()) { // found such part, so asking it for the name
713       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
714       std::string aNameInPart = theSubShapeName.substr(aPartEnd + 1);
715       int anIndex;
716       std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, theType, anIndex);
717       if (aSelected.get()) {
718         setValue(aPart, aSelected);
719         TDataStd_Integer::Set(selectionLabel(), anIndex);
720         return;
721       }
722     }
723   }
724
725   Model_SelectionNaming aSelNaming(selectionLabel());
726   std::shared_ptr<Model_Document> aDoc =
727     std::dynamic_pointer_cast<Model_Document>(owner()->document());
728   std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
729   ResultPtr aCont;
730   if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
731     // try to find the last context to find the up to date shape
732     if (aCont->shape().get() && !aCont->shape()->isNull() &&
733       aCont->groupName() == ModelAPI_ResultBody::group() && aDoc == owner()->document()) {
734       const TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
735       if (!aConShape.IsNull()) {
736         Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
737         if (!aNS.IsNull()) {
738           aNS = TNaming_Tool::CurrentNamedShape(aNS);
739           if (!aNS.IsNull()) {
740             TDF_Label aLab = aNS->Label();
741             while(aLab.Depth() != 7 && aLab.Depth() > 5)
742               aLab = aLab.Father();
743             ObjectPtr anObj = aDoc->objects()->object(aLab);
744             if (anObj.get()) {
745               ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
746               if (aRes)
747                 aCont = aRes;
748             }
749           }
750         }
751       }
752     }
753     setValue(aCont, aShapeToBeSelected);
754     return;
755   }
756
757   TDF_Label aSelLab = selectionLabel();
758   setInvalidIfFalse(aSelLab, false);
759   reset();
760 }
761
762 int Model_AttributeSelection::Id()
763 {
764   int anID = 0;
765   std::shared_ptr<GeomAPI_Shape> aSelection = value();
766   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
767   // support for compsolids:
768   if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
769     aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
770
771
772   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
773   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
774   // searching for the latest main shape
775   if (aSelection && !aSelection->isNull() &&
776     aContext   && !aContext->isNull())
777   {
778     std::shared_ptr<Model_Document> aDoc =
779       std::dynamic_pointer_cast<Model_Document>(context()->document());
780     if (aDoc.get()) {
781       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
782       if (!aNS.IsNull()) {
783         aMainShape = TNaming_Tool::CurrentShape(aNS);
784       }
785     }
786
787     TopTools_IndexedMapOfShape aSubShapesMap;
788     TopExp::MapShapes(aMainShape, aSubShapesMap);
789     anID = aSubShapesMap.FindIndex(aSubShape);
790   }
791   return anID;
792 }
793
794 void Model_AttributeSelection::setId(int theID)
795 {
796   const ResultPtr& aContext = context();
797   std::shared_ptr<GeomAPI_Shape> aSelection;
798
799   std::shared_ptr<GeomAPI_Shape> aContextShape = aContext->shape();
800   // support for compsolids:
801   if (aContext.get() && ModelAPI_Tools::compSolidOwner(aContext).get())
802     aContextShape = ModelAPI_Tools::compSolidOwner(aContext)->shape();
803
804   TopoDS_Shape aMainShape = aContextShape->impl<TopoDS_Shape>();
805   // searching for the latest main shape
806   if (theID > 0 &&
807       aContextShape && !aContextShape->isNull())
808   {
809     std::shared_ptr<Model_Document> aDoc =
810       std::dynamic_pointer_cast<Model_Document>(aContext->document());
811     if (aDoc.get()) {
812       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
813       if (!aNS.IsNull()) {
814         aMainShape = TNaming_Tool::CurrentShape(aNS);
815       }
816     }
817
818     TopTools_IndexedMapOfShape aSubShapesMap;
819     TopExp::MapShapes(aMainShape, aSubShapesMap);
820     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
821
822     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
823     aResult->setImpl(new TopoDS_Shape(aSelShape));
824
825     aSelection = aResult;
826   }
827
828   setValue(aContext, aSelection);
829 }
830
831 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
832 {
833   std::string aResult;
834   if (owner()->document() != theContext->document()) {
835     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
836       aResult = theContext->document()->kind() + "/";
837     } else {
838       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
839         ModelAPI_Session::get()->moduleDocument(), theContext->document());
840       if (aDocRes.get()) {
841         aResult = aDocRes->data()->name() + "/";
842       }
843     }
844   }
845   aResult += theContext->data()->name();
846   return aResult;
847 }
848
849 void Model_AttributeSelection::updateInHistory()
850 {
851   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
852   // only bodies may be modified later in the history, don't do anything otherwise
853   if (!aContext.get() || aContext->groupName() != ModelAPI_ResultBody::group())
854     return;
855   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
856   if (!aContData.get() || !aContData->isValid())
857     return;
858   TDF_Label aContLab = aContData->label(); // named shape where the selected context is located
859   Handle(TNaming_NamedShape) aContNS;
860   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS))
861     return;
862   std::shared_ptr<Model_Document> aDoc =
863     std::dynamic_pointer_cast<Model_Document>(aContext->document());
864   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
865   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
866   // iterate the context shape modifications in order to find a feature that is upper in history
867   // that this one and is really modifies the referenced result to refer to it
868   ResultPtr aModifierResFound;
869   TNaming_Iterator aPairIter(aContNS);
870   if (!aPairIter.More())
871     return;
872   TopoDS_Shape aNewShape = aPairIter.NewShape();
873   bool anIterate = true;
874   // trying to update also the sub-shape selected
875   GeomShapePtr aSubShape = value();
876   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
877     aSubShape.reset();
878
879   while(anIterate) {
880     anIterate = false;
881     TNaming_SameShapeIterator aModifIter(aNewShape, aContLab);
882     for(; aModifIter.More(); aModifIter.Next()) {
883       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
884         (aDoc->objects()->object(aModifIter.Label().Father()));
885       if (!aModifierObj.get())
886         break;
887       FeaturePtr aModifierFeat = aDoc->feature(aModifierObj);
888       if (!aModifierFeat.get())
889         break;
890       if (aModifierFeat == aThisFeature || aDoc->objects()->isLater(aModifierFeat, aThisFeature))
891         continue; // the modifier feature is later than this, so, should not be used
892       if (aCurrentModifierFeat == aModifierFeat ||
893         aDoc->objects()->isLater(aCurrentModifierFeat, aModifierFeat))
894         continue; // the current modifier is later than the found, so, useless
895       Handle(TNaming_NamedShape) aNewNS;
896       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
897       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
898         aModifierResFound = aModifierObj;
899         aCurrentModifierFeat = aModifierFeat;
900         TNaming_Iterator aPairIter(aNewNS);
901         aNewShape = aPairIter.NewShape();
902         anIterate = true;
903         break;
904       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is null
905         ResultPtr anEmptyContext;
906         std::shared_ptr<GeomAPI_Shape> anEmptyShape;
907         setValue(anEmptyContext, anEmptyShape); // nullify the selection
908         return;
909       } else { // not-precessed modification => don't support it
910         continue;
911       }
912     }
913   }
914   if (aModifierResFound.get()) {
915     // update scope to reset to a new one
916     myScope.Clear();
917     myRef.setValue(aModifierResFound);
918     // if context shape type is changed to more complicated and this context is selected, split
919     if (myParent &&!aSubShape.get() && aModifierResFound->shape().get() && aContext->shape().get())
920     {
921       TopoDS_Shape anOldShape = aContext->shape()->impl<TopoDS_Shape>();
922       TopoDS_Shape aNewShape = aModifierResFound->shape()->impl<TopoDS_Shape>();
923       if (!anOldShape.IsNull() && !aNewShape.IsNull() &&
924         anOldShape.ShapeType() != aNewShape.ShapeType() &&
925         (aNewShape.ShapeType() == TopAbs_COMPOUND || aNewShape.ShapeType() == TopAbs_COMPSOLID)) {
926         // prepare for split in "update"
927         TDF_Label aSelLab = selectionLabel();
928         split(aContext, aNewShape, anOldShape.ShapeType());
929       }
930     }
931     update(); // it must recompute a new sub-shape automatically
932   }
933 }
934
935 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
936 {
937   myParent = theParent;
938 }