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