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