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