]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
Fix of the problem of naming name parse if results are referenced in not direct way...
[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 = 0; aSubNum < aComp->numberOfSubs(); 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()) {
885         aFindNewContext = false;
886         // take references to all results: root one, any sub
887         ResultCompSolidPtr aCompContext = ModelAPI_Tools::compSolidOwner(aCont);
888         int aSubsSize = (aCompContext.get() ? aCompContext->numberOfSubs() : 0) + 1;
889         for(int aResultNum = 0; aResultNum < aSubsSize; aResultNum++) {
890           ResultPtr aResCont = aCompContext.get() ? (aResultNum == aSubsSize - 1 ?
891                   aCompContext : aCompContext->subResult(aResultNum)) : aCont;
892           const std::set<AttributePtr>& aRefs = aResCont->data()->refsToMe();
893           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
894           for(; !aFindNewContext && aRef != aRefs.end(); aRef++) {
895             if (!aRef->get() || !(*aRef)->owner().get())
896               continue;
897             // concealed attribute only
898             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
899             if (!ModelAPI_Session::get()->validators()->isConcealed(
900               aRefFeat->getKind(), (*aRef)->id()))
901               continue;
902             // search the feature result that contains sub-shape selected
903             std::list<std::shared_ptr<ModelAPI_Result> > aResults;
904
905             // take all sub-results or one result
906             const std::list<std::shared_ptr<ModelAPI_Result> >& aFResults = aRefFeat->results();
907             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aFResults.begin();
908             for (; aRIter != aFResults.cend(); aRIter++) {
909               // iterate sub-bodies of compsolid
910               ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRIter);
911               if (aComp.get() && aComp->numberOfSubs() > 0) {
912                 int aNumSub = aComp->numberOfSubs();
913                 for(int a = 0; a < aNumSub; a++) {
914                   aResults.push_back(aComp->subResult(a));
915                 }
916               } else {
917                 aResults.push_back(*aRIter);
918               }
919             }
920             std::list<std::shared_ptr<ModelAPI_Result> >::iterator aResIter = aResults.begin();
921             for(; aResIter != aResults.end(); aResIter++) {
922               if (!aResIter->get() || !(*aResIter)->data()->isValid() || (*aResIter)->isDisabled())
923                 continue;
924               GeomShapePtr aShape = (*aResIter)->shape();
925               GeomShapePtr aSelectedShape =
926                 aShapeToBeSelected.get() ? aShapeToBeSelected : aCont->shape();
927               if (aShape.get() && aShape->isSubShape(aSelectedShape, false)) {
928                 aCont = *aResIter; // found new context (produced from this) with same subshape
929                 //if (!aShape->isSubShape(aShapeToBeSelected, true)) // take context orientation
930                 //  aShapeToBeSelected->setOrientation();
931                 aFindNewContext = true; // continue searching futher
932                 break;
933               }
934             }
935           }
936         }
937       }
938
939       if (aCenterType != NOT_CENTER) {
940         if (!aShapeToBeSelected->isEdge())
941           continue;
942         std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aShapeToBeSelected));
943         setValueCenter(aCont, aSelectedEdge, aCenterType);
944       } else
945         setValue(aCont, aShapeToBeSelected);
946       return;
947     }
948   }
949
950   TDF_Label aSelLab = selectionLabel();
951   setInvalidIfFalse(aSelLab, false);
952   reset();
953 }
954
955 int Model_AttributeSelection::Id()
956 {
957   int anID = 0;
958   std::shared_ptr<GeomAPI_Shape> aSelection = value();
959   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
960   // support for compsolids:
961   if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
962     aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
963
964
965   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
966   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
967   // searching for the latest main shape
968   if (aSelection && !aSelection->isNull() &&
969     aContext   && !aContext->isNull())
970   {
971     std::shared_ptr<Model_Document> aDoc =
972       std::dynamic_pointer_cast<Model_Document>(context()->document());
973     if (aDoc.get()) {
974       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
975       if (!aNS.IsNull()) {
976         aMainShape = TNaming_Tool::CurrentShape(aNS);
977       }
978     }
979
980     TopTools_IndexedMapOfShape aSubShapesMap;
981     TopExp::MapShapes(aMainShape, aSubShapesMap);
982     anID = aSubShapesMap.FindIndex(aSubShape);
983   }
984   return anID;
985 }
986
987 void Model_AttributeSelection::setId(int theID)
988 {
989   const ResultPtr& aContext = context();
990   std::shared_ptr<GeomAPI_Shape> aSelection;
991
992   std::shared_ptr<GeomAPI_Shape> aContextShape = aContext->shape();
993   // support for compsolids:
994   if (aContext.get() && ModelAPI_Tools::compSolidOwner(aContext).get())
995     aContextShape = ModelAPI_Tools::compSolidOwner(aContext)->shape();
996
997   TopoDS_Shape aMainShape = aContextShape->impl<TopoDS_Shape>();
998   // searching for the latest main shape
999   if (theID > 0 &&
1000       aContextShape && !aContextShape->isNull())
1001   {
1002     std::shared_ptr<Model_Document> aDoc =
1003       std::dynamic_pointer_cast<Model_Document>(aContext->document());
1004     if (aDoc.get()) {
1005       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1006       if (!aNS.IsNull()) {
1007         aMainShape = TNaming_Tool::CurrentShape(aNS);
1008       }
1009     }
1010
1011     TopTools_IndexedMapOfShape aSubShapesMap;
1012     TopExp::MapShapes(aMainShape, aSubShapesMap);
1013     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1014
1015     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1016     aResult->setImpl(new TopoDS_Shape(aSelShape));
1017
1018     aSelection = aResult;
1019   }
1020
1021   setValue(aContext, aSelection);
1022 }
1023
1024 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1025 {
1026   std::string aResult;
1027   if (owner()->document() != theContext->document()) {
1028     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1029       aResult = theContext->document()->kind() + "/";
1030     } else {
1031       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1032         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1033       if (aDocRes.get()) {
1034         aResult = aDocRes->data()->name() + "/";
1035       }
1036     }
1037   }
1038   aResult += theContext->data()->name();
1039   return aResult;
1040 }
1041
1042 void Model_AttributeSelection::computeValues(
1043   ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
1044   TopTools_ListOfShape& theShapes)
1045 {
1046   bool aWasWholeContext = theValShape.IsNull();
1047   if (aWasWholeContext) {
1048     //theShapes.Append(theValShape);
1049     //return;
1050     theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
1051   }
1052   //TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
1053   TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
1054   //if (anOldContShape.IsSame(theValShape)) { // full context shape substituted by new full context
1055     //theShapes.Append(aNewContShape);
1056     //return;
1057   //}
1058   // if a new value is unchanged in the new context, do nothing: value is correct
1059   TopExp_Explorer aSubExp(aNewContShape, theValShape.ShapeType());
1060   for(; aSubExp.More(); aSubExp.Next()) {
1061     if (aSubExp.Current().IsSame(theValShape)) {
1062       theShapes.Append(theValShape);
1063       return;
1064     }
1065   }
1066   // if new context becomes compsolid, the resulting sub may be in sub-solids
1067   std::list<ResultPtr> aNewToIterate;
1068   aNewToIterate.push_back(theNewContext);
1069   ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theNewContext);
1070   if (aComp.get()) {
1071     for(int a = 0; a < aComp->numberOfSubs(); a++)
1072       aNewToIterate.push_back(aComp->subResult(a, false));
1073   }
1074
1075   // first iteration: searching for the whole shape appearance (like face of the box)
1076   // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
1077   int aToFindPart = 0;
1078   TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
1079   TopTools_MapOfShape anOlds; // to know how many olds produced new containers
1080   for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
1081     std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
1082     for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
1083       std::shared_ptr<Model_Data> aNewData =
1084         std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
1085       TDF_Label aNewLab = aNewData->label();
1086       // searching for produced sub-shape fully on some label
1087       TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID(), Standard_True);
1088       for(; aNSIter.More(); aNSIter.Next()) {
1089         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1090         for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
1091           if (aToFindPart == 0) { // search shape is fully inside
1092             if (aPairIter.OldShape().IsSame(theValShape)) {
1093               if (aPairIter.NewShape().IsNull()) {// value was removed
1094                 theShapes.Clear();
1095                 return;
1096               }
1097               theShapes.Append(aPairIter.NewShape());
1098             }
1099           } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
1100             TopExp_Explorer anExp(aPairIter.OldShape(), theValShape.ShapeType());
1101             for(; anExp.More(); anExp.Next()) {
1102               if (anExp.Current().IsSame(theValShape)) { // found a new container
1103                 if (aPairIter.NewShape().IsNull()) {// value was removed
1104                   theShapes.Clear();
1105                   return;
1106                 }
1107                 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
1108                 anOlds.Add(aPairIter.OldShape());
1109                 break;
1110               }
1111             }
1112           }
1113         }
1114       }
1115     }
1116   }
1117   if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
1118     // map of sub-shapes -> number of occurences of these shapes in containers
1119     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
1120     TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
1121     for(; aContIter.More(); aContIter.Next()) {
1122       TopExp_Explorer aSubExp(aContIter.Key(), theValShape.ShapeType());
1123       for(; aSubExp.More(); aSubExp.Next()) {
1124         if (!aSubs.IsBound(aSubExp.Current())) {
1125           aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
1126         }
1127         // store old to know how many olds produced this shape
1128         aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
1129       }
1130     }
1131     // if sub is appeared same times in containers as the number of old shapes that contain it
1132     int aCountInOld = anOlds.Size();
1133     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
1134       aSubsIter(aSubs);
1135     for(; aSubsIter.More(); aSubsIter.Next()) {
1136       if (aSubsIter.Value().Size() == aCountInOld) {
1137         theShapes.Append(aSubsIter.Key());
1138       }
1139     }
1140   }
1141   if (theShapes.IsEmpty()) { // nothing was changed
1142     theShapes.Append(aWasWholeContext ? TopoDS_Shape() : theValShape);
1143   }
1144 }
1145
1146 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
1147   const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
1148   TDF_Label theAccessLabel,
1149   std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
1150 {
1151   std::set<ResultPtr> aResults; // to avoid duplicates, new context, null if deleted
1152   TopTools_ListOfShape aResContShapes;
1153   // iterate context and shape, but also if it is sub-shape of main shape, check also it
1154   TopTools_ListOfShape aContextList;
1155   aContextList.Append(theContShape);
1156   if (theContext.get()) {
1157     ResultPtr aComposite = ModelAPI_Tools::compSolidOwner(theContext);
1158     if (aComposite.get() && aComposite->shape().get() && !aComposite->shape()->isNull())
1159       aContextList.Append(aComposite->shape()->impl<TopoDS_Shape>());
1160   }
1161   for(TopTools_ListOfShape::Iterator aContIter(aContextList); aContIter.More(); aContIter.Next()) {
1162     TNaming_SameShapeIterator aModifIter(aContIter.ChangeValue(), theAccessLabel);
1163     for(; aModifIter.More(); aModifIter.Next()) {
1164       TDF_Label anObjLab = aModifIter.Label().Father();
1165       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1166         (theDoc->objects()->object(anObjLab));
1167       if (!aModifierObj.get()) {
1168         // #2241: shape may be sub-element of new object, not main (shell created from faces)
1169         if (!anObjLab.IsRoot())
1170           aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1171           (theDoc->objects()->object(anObjLab.Father()));
1172         if (!aModifierObj.get())
1173           continue;
1174       }
1175       FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
1176       if (!aModifierFeat.get())
1177         continue;
1178       FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1179       if (aModifierFeat == aThisFeature || theDoc->objects()->isLater(aModifierFeat, aThisFeature))
1180         continue; // the modifier feature is later than this, so, should not be used
1181       FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
1182       if (aCurrentModifierFeat == aModifierFeat ||
1183         theDoc->objects()->isLater(aCurrentModifierFeat, aModifierFeat))
1184         continue; // the current modifier is later than the found, so, useless
1185       Handle(TNaming_NamedShape) aNewNS;
1186       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1187       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1188         aResults.insert(aModifierObj);
1189         //TNaming_Iterator aPairIter(aNewNS);
1190         //aResContShapes.Append(aPairIter.NewShape());
1191         aResContShapes.Append(aModifierObj->shape()->impl<TopoDS_Shape>());
1192       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
1193         aResults.insert(ResultPtr());
1194       } else { // not-precessed modification => don't support it
1195         continue;
1196       }
1197     }
1198   }
1199   if (aResults.empty())
1200     return false; // no modifications found, must stay the same
1201   // iterate all results to find futher modifications
1202   std::set<ResultPtr>::iterator aResIter = aResults.begin();
1203   for(; aResIter != aResults.end(); aResIter++) {
1204     if (aResIter->get() != NULL) {
1205       // compute new values by two contextes: the old and the new
1206       TopTools_ListOfShape aValShapes;
1207       computeValues(theContext, *aResIter, theValShape, aValShapes);
1208
1209       TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
1210       for(; aNewVal.More(); aNewVal.Next()) {
1211         std::list<ResultPtr> aNewRes;
1212         TopTools_ListOfShape aNewUpdatedVal;
1213         TopoDS_Shape aNewValSh = aNewVal.Value();
1214         TopoDS_Shape aNewContShape = (*aResIter)->shape()->impl<TopoDS_Shape>();
1215         if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
1216           aNewValSh.Nullify();
1217         if (searchNewContext(theDoc, aNewContShape, *aResIter, aNewValSh,
1218                              theAccessLabel, aNewRes, aNewUpdatedVal))
1219         {
1220           // appeand new results instead of the current ones
1221           std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1222           TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1223           for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1224             theResults.push_back(*aNewIter);
1225             theValShapes.Append(aNewUpdVal.Value());
1226           }
1227         } else { // the current result is good
1228           theResults.push_back(*aResIter);
1229           theValShapes.Append(aNewValSh);
1230         }
1231       }
1232     }
1233   }
1234   return true; // theResults must be empty: everything is deleted
1235 }
1236
1237 void Model_AttributeSelection::updateInHistory()
1238 {
1239   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1240   // only bodies and parts may be modified later in the history, don't do anything otherwise
1241   if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
1242       aContext->groupName() != ModelAPI_ResultPart::group()))
1243     return;
1244   std::shared_ptr<Model_Document> aDoc =
1245     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1246   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1247   if (!aContData.get() || !aContData->isValid())
1248     return;
1249   TDF_Label aContLab = aContData->label(); // named shape where the selected context is located
1250   Handle(TNaming_NamedShape) aContNS;
1251   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
1252     bool aFoundNewContext = true;
1253     ResultPtr aNewContext = aContext;
1254     while(aFoundNewContext) {
1255       aFoundNewContext = false;
1256       // parts have no shape in result, so, trace references using the Part info
1257       if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
1258         ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
1259         if (aPartContext.get()) { // searching for the up to date references to the referenced cont
1260           const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
1261           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1262           for(; aRef != aRefs.end(); aRef++) {
1263             // to avoid detection of part changes by local selection only
1264             AttributeSelectionPtr aSel =
1265               std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1266             if (aSel.get() && !aSel->value()->isSame(aSel->context()->shape()))
1267               continue;
1268
1269             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1270             if (aRefFeat.get() && aRefFeat != owner()) {
1271               FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1272               if (aDoc->objects()->isLater(aThisFeature, aRefFeat)) { // found better feature
1273                 aFoundNewContext = true;
1274                 aNewContext = aRefFeat->firstResult();
1275               }
1276             }
1277           }
1278         }
1279       }
1280     }
1281     if (aNewContext != aContext) {
1282       setValue(aNewContext, value());
1283     }
1284     return;
1285   }
1286   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1287   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1288   // iterate the context shape modifications in order to find a feature that is upper in history
1289   // that this one and is really modifies the referenced result to refer to it
1290   ResultPtr aModifierResFound;
1291   TNaming_Iterator aPairIter(aContNS);
1292   if (!aPairIter.More())
1293     return;
1294   TopoDS_Shape aNewCShape = aPairIter.NewShape();
1295   bool anIterate = true;
1296   // trying to update also the sub-shape selected
1297   GeomShapePtr aSubShape = value();
1298   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1299     aSubShape.reset();
1300   TopoDS_Shape aValShape;
1301   if (aSubShape.get()) {
1302     aValShape = aSubShape->impl<TopoDS_Shape>();
1303   }
1304
1305   std::list<ResultPtr> aNewContexts;
1306   TopTools_ListOfShape aValShapes;
1307   if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1308   {
1309     // update scope to reset to a new one
1310     myScope.Clear();
1311
1312     std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1313     TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1314     if (aNewCont == aNewContexts.end()) { // all results were deleted
1315       ResultPtr anEmptyContext;
1316       std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1317       setValue(anEmptyContext, anEmptyShape); // nullify the selection
1318       return;
1319     }
1320
1321     GeomShapePtr aValueShape;
1322     if (!aNewValues.Value().IsNull()) {
1323       aValueShape = std::make_shared<GeomAPI_Shape>();
1324       aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1325     }
1326     setValue(*aNewCont, aValueShape);
1327     // if there are more than one result, put them by "append" into "parent" list
1328     if (myParent) {
1329       for(aNewCont++, aNewValues.Next(); aNewCont != aNewContexts.end();
1330           aNewCont++, aNewValues.Next()) {
1331         GeomShapePtr aValueShape;
1332         if (!aNewValues.Value().IsNull()) {
1333           aValueShape = std::make_shared<GeomAPI_Shape>();
1334           aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1335         }
1336         myParent->append(*aNewCont, aValueShape);
1337       }
1338     }
1339   }
1340 }
1341
1342 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1343 {
1344   myParent = theParent;
1345 }