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