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