]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
Update of the ExportToGEOM test
[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     // this causes problem in galeries.py
452     //bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
453     for(; aFIter != allFeatures.end(); aFIter++) {
454       if (*aFIter == owner()) {  // the left features are created later (except subs of composite)
455         aMePassed = true;
456         continue;
457       }
458       //if (isGroup) aMePassed = false;
459       bool isInScope = !aMePassed;
460       if (!isInScope && aComposite.get()) {
461         // try to add sub-elements of composite if this is composite
462         if (aComposite->isSub(*aFIter))
463           isInScope = true;
464       }
465       // remove the composite-owner of this feature (sketch in extrusion-cut)
466       if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
467         isInScope = false;
468
469       if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
470         TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
471           (*aFIter)->data())->label().Father();
472         TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), true);
473         for(; aNSIter.More(); aNSIter.Next()) {
474           Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
475           if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
476             myScope.Add(aNS->Label());
477           }
478         }
479       }
480     }
481     // also add all naming labels created for external constructions
482     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(aMyDoc);
483     TDF_Label anExtDocLab = aDoc->extConstructionsLabel();
484     TDF_ChildIDIterator aNSIter(anExtDocLab, TNaming_NamedShape::GetID(), true);
485     for(; aNSIter.More(); aNSIter.Next()) {
486       Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
487       if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
488         myScope.Add(aNS->Label());
489       }
490     }
491   }
492   return myScope;
493 }
494
495 /// Sets the invalid flag if flag is false, or removes it if "true"
496 /// Returns theFlag
497 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
498   if (theFlag) {
499     theLab.ForgetAttribute(kINVALID_SELECTION);
500   } else {
501     TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
502   }
503   return theFlag;
504 }
505
506 void Model_AttributeSelection::split(
507   ResultPtr theContext, TopoDS_Shape theNewShape, TopAbs_ShapeEnum theType)
508 {
509   TopTools_ListOfShape aSubs;
510   for(TopoDS_Iterator anExplorer(theNewShape); anExplorer.More(); anExplorer.Next()) {
511     if (!anExplorer.Value().IsNull() &&
512       anExplorer.Value().ShapeType() == theType) {
513         aSubs.Append(anExplorer.Value());
514     } else { // invalid case; bad result shape, so, impossible to split easily
515       aSubs.Clear();
516       break;
517     }
518   }
519   if (aSubs.Extent() > 1) { // ok to split
520     TopTools_ListIteratorOfListOfShape aSub(aSubs);
521     GeomShapePtr aSubSh(new GeomAPI_Shape);
522     aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
523     setValue(theContext, aSubSh);
524     for(aSub.Next(); aSub.More(); aSub.Next()) {
525       GeomShapePtr aSubSh(new GeomAPI_Shape);
526       aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
527       myParent->append(theContext, aSubSh);
528     }
529   }
530 }
531
532 bool Model_AttributeSelection::update()
533 {
534   TDF_Label aSelLab = selectionLabel();
535   ResultPtr aContext = context();
536   if (!aContext.get())
537     return setInvalidIfFalse(aSelLab, false);
538   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
539     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
540   }
541
542   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
543     std::shared_ptr<GeomAPI_Shape> aNoSelection;
544     bool aResult = selectPart(aContext, aNoSelection, true);
545     aResult = setInvalidIfFalse(aSelLab, aResult);
546     if (aResult) {
547       owner()->data()->sendAttributeUpdated(this);
548     }
549     return aResult;
550   }
551
552   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
553     // body: just a named shape, use selection mechanism from OCCT
554     TNaming_Selector aSelector(aSelLab);
555     TopoDS_Shape anOldShape;
556     if (!aSelector.NamedShape().IsNull()) {
557       anOldShape = aSelector.NamedShape()->Get();
558     }
559     bool aResult = aSelector.Solve(scope()) == Standard_True;
560     // must be before sending of updated attribute (1556)
561     aResult = setInvalidIfFalse(aSelLab, aResult);
562     TopoDS_Shape aNewShape;
563     if (!aSelector.NamedShape().IsNull()) {
564       aNewShape = aSelector.NamedShape()->Get();
565     }
566     if (anOldShape.IsNull() || aNewShape.IsNull() ||
567         !anOldShape.IsEqual(aSelector.NamedShape()->Get())) {
568       // shape type shoud not not changed: if shape becomes compound of such shapes, then split
569       if (myParent && !anOldShape.IsNull() && !aNewShape.IsNull() &&
570           anOldShape.ShapeType() != aNewShape.ShapeType() &&
571           (aNewShape.ShapeType() == TopAbs_COMPOUND || aNewShape.ShapeType() == TopAbs_COMPSOLID))
572       {
573         split(aContext, aNewShape, anOldShape.ShapeType());
574       }
575       owner()->data()->sendAttributeUpdated(this);  // send updated if shape is changed
576     }
577     return aResult;
578   }
579
580   if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
581     Handle(TDataStd_Integer) anIndex;
582     if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
583       std::shared_ptr<Model_ResultConstruction> aConstructionContext =
584         std::dynamic_pointer_cast<Model_ResultConstruction>(aContext);
585       bool aModified = true;
586       bool aValid = aConstructionContext->update(anIndex->Get(), owner()->document(), aModified);
587       setInvalidIfFalse(aSelLab, aValid);
588       if (aConstructionContext->isInfinite()) {
589         // Update the selected shape.
590         TNaming_Builder aBuilder(aSelLab);
591         aBuilder.Generated(aConstructionContext->shape()->impl<TopoDS_Shape>());
592       }
593       if (aModified)
594         owner()->data()->sendAttributeUpdated(this);
595       return aValid;
596     }
597   }
598   return setInvalidIfFalse(aSelLab, false); // unknown case
599 }
600
601 void Model_AttributeSelection::selectBody(
602   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
603 {
604   // perform the selection
605   TNaming_Selector aSel(selectionLabel());
606   TopoDS_Shape aContext;
607
608   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theContext);//myRef.value()
609   if (aBody) {
610     aContext = aBody->shape()->impl<TopoDS_Shape>();
611   } else {
612     ResultPtr aResult =
613       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
614     if (aResult) {
615       aContext = aResult->shape()->impl<TopoDS_Shape>();
616     } else {
617       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
618       return;
619     }
620   }
621
622   // with "recover" feature the selected context may be not up to date (issue 1710)
623   Handle(TNaming_NamedShape) aResult;
624   TDF_Label aSelLab = selectionLabel();
625   TopoDS_Shape aNewContext = aContext;
626   bool isUpdated = true;
627   while(!aNewContext.IsNull() && isUpdated) {
628     // searching for the very last shape that was produced from this one
629     isUpdated = false;
630     if (!TNaming_Tool::HasLabel(aSelLab, aNewContext))
631       // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
632       break;
633     for(TNaming_SameShapeIterator anIter(aNewContext, aSelLab); anIter.More(); anIter.Next()) {
634       TDF_Label aNSLab = anIter.Label();
635       if (!scope().Contains(aNSLab))
636         continue;
637       Handle(TNaming_NamedShape) aNS;
638       if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
639         for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
640           if (aShapesIter.Evolution() == TNaming_SELECTED)
641             continue; // don't use the selection evolution
642           if (!aShapesIter.OldShape().IsNull() && aShapesIter.OldShape().IsSame(aNewContext)) {
643              // found the original shape
644             aNewContext = aShapesIter.NewShape(); // go to the newer shape
645             isUpdated = true;
646             break;
647           }
648         }
649       }
650     }
651   }
652   if (aNewContext.IsNull()) { // a context is already deleted
653     setInvalidIfFalse(aSelLab, false);
654     Events_InfoMessage("Model_AttributeSelection", "Failed to select shape already deleted").send();
655     return;
656   }
657
658   TopoDS_Shape aNewSub = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
659   if (!aNewSub.IsEqual(aContext)) { // searching for subshape in the new context
660     bool isFound = false;
661     TopExp_Explorer anExp(aNewContext, aNewSub.ShapeType());
662     for(; anExp.More(); anExp.Next()) {
663       if (anExp.Current().IsSame(aNewSub)) {
664         isFound = true;
665         break;
666       }
667     }
668     if (!isFound) { // sub-shape is not found in the up-to-date instance of the context shape
669       // if context is sub-result of compound/compsolid, selection of sub-shape better propagate to
670       // the main result (which is may be modified), case is in 1799
671       ResultCompSolidPtr aMain = ModelAPI_Tools::compSolidOwner(theContext);
672       if (aMain.get()) {
673         selectBody(aMain, theSubShape);
674         return;
675       }
676       setInvalidIfFalse(aSelLab, false);
677       Events_InfoMessage("Model_AttributeSelection",
678         "Failed to select sub-shape already modified").send();
679       return;
680     }
681   }
682
683   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
684   if (!aContext.IsNull()) {
685     FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
686     bool aEraseResults = false;
687     if (aFeatureOwner.get()) {
688       aEraseResults = !aFeatureOwner->results().empty();
689       if (aEraseResults) // erase results without flash deleted and redisplay: do it after Select
690         aFeatureOwner->removeResults(0, false, false);
691     }
692     aSel.Select(aNewSub, aNewContext);
693
694     if (aEraseResults) { // flash after Select : in Groups it makes selection with shift working
695       static Events_Loop* aLoop = Events_Loop::loop();
696       static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
697       aLoop->flush(kDeletedEvent);
698     }
699   }
700 }
701
702 bool Model_AttributeSelection::selectPart(
703   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
704   const bool theUpdate)
705 {
706   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
707   if (!aPart.get() || !aPart->isActivated())
708     return true; // postponed naming
709   if (theUpdate) {
710     Handle(TDataStd_Integer) anIndex;
711     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
712       // by internal selection
713       if (anIndex->Get() > 0) {
714         // update the selection by index
715         return aPart->updateInPart(anIndex->Get());
716       } else {
717         return true; // nothing to do, referencing just by name
718       }
719     }
720     return true; // nothing to do, referencing just by name
721   }
722   // store the shape (in case part is not loaded it should be useful
723   TopoDS_Shape aShape;
724   std::string aName = theContext->data()->name();
725   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
726     aShape = theContext->shape()->impl<TopoDS_Shape>();
727   } else {
728     aShape = theSubShape->impl<TopoDS_Shape>();
729     int anIndex;
730     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
731     TDataStd_Integer::Set(selectionLabel(), anIndex);
732   }
733   TNaming_Builder aBuilder(selectionLabel());
734   aBuilder.Select(aShape, aShape);
735   // identify by name in the part
736   TDataStd_Name::Set(selectionLabel(), aName.c_str());
737   return !aName.empty();
738 }
739
740 TDF_Label Model_AttributeSelection::selectionLabel()
741 {
742   return myRef.myRef->Label().FindChild(1);
743 }
744
745 /// prefixes of the shape names with centers defined
746 static std::map<ModelAPI_AttributeSelection::CenterType, std::string> kCENTERS_PREFIX;
747
748 /// returns the map that contains all possible prefixes of the center-names
749 static std::map<ModelAPI_AttributeSelection::CenterType, std::string>& centersMap()
750 {
751   if (kCENTERS_PREFIX.empty()) { // fill map by initial values
752     kCENTERS_PREFIX[ModelAPI_AttributeSelection::CIRCLE_CENTER] = "__cc";
753     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS] = "__eff";
754     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_SECOND_FOCUS] = "__esf";
755   }
756   return kCENTERS_PREFIX;
757 }
758
759 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
760 {
761   std::string aName("");
762   if(!this->isInitialized())
763     return !theDefaultName.empty() ? theDefaultName : aName;
764
765   CenterType aCenterType = NOT_CENTER;
766   std::shared_ptr<GeomAPI_Shape> aSubSh = internalValue(aCenterType);
767   ResultPtr aCont = context();
768
769   if (!aCont.get()) // in case of selection of removed result
770     return "";
771
772   Model_SelectionNaming aSelNaming(selectionLabel());
773   std::string aResult = aSelNaming.namingName(
774     aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
775   if (aCenterType != NOT_CENTER) {
776     aResult += centersMap()[aCenterType];
777   }
778   return aResult;
779 }
780
781 // returns the center type and modifies the shape name if this name is center-name
782 static ModelAPI_AttributeSelection::CenterType centerTypeByName(std::string& theShapeName)
783 {
784   std::map<ModelAPI_AttributeSelection::CenterType, std::string>::iterator aPrefixIter =
785     centersMap().begin();
786   for(; aPrefixIter != centersMap().end(); aPrefixIter++) {
787     std::size_t aFound = theShapeName.find(aPrefixIter->second);
788     if (aFound != std::string::npos &&
789         aFound == theShapeName.size() - aPrefixIter->second.size()) {
790       theShapeName = theShapeName.substr(0, aFound);
791       return aPrefixIter->first;
792     }
793   }
794   return ModelAPI_AttributeSelection::NOT_CENTER;
795 }
796
797 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
798 void Model_AttributeSelection::selectSubShape(
799   const std::string& theType, const std::string& theSubShapeName)
800 {
801   if(theSubShapeName.empty() || theType.empty()) return;
802
803   std::string aSubShapeName = theSubShapeName;
804   CenterType aCenterType = theType[0] == 'v' || theType[0] == 'V' ? // only for vertex-type
805     centerTypeByName(aSubShapeName) : NOT_CENTER;
806   std::string aType = aCenterType == NOT_CENTER ? theType : "EDGE"; // search for edge now
807
808   // first iteration is selection by name without center prefix, second - in case of problem,
809   // try with initial name
810   for(int aUseCenter = 1; aUseCenter >= 0; aUseCenter--) {
811     if (aUseCenter == 0 && aCenterType != NOT_CENTER) {
812       aSubShapeName = theSubShapeName;
813       aCenterType = NOT_CENTER;
814       aType = theType;
815     } else if (aUseCenter != 1) continue;
816
817     // check this is Part-name: 2 delimiters in the name
818     std::size_t aPartEnd = aSubShapeName.find('/');
819     if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
820       std::string aPartName = aSubShapeName.substr(0, aPartEnd);
821       ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
822       if (aFound.get()) { // found such part, so asking it for the name
823         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
824         std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
825         int anIndex;
826         std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, aType, anIndex);
827         if (aSelected.get()) {
828           if (aCenterType != NOT_CENTER) {
829             if (!aSelected->isEdge())
830               continue;
831             std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aSelected));
832             setValueCenter(aPart, aSelectedEdge, aCenterType);
833           } else
834             setValue(aPart, aSelected);
835           TDataStd_Integer::Set(selectionLabel(), anIndex);
836           return;
837         }
838       }
839     }
840
841     Model_SelectionNaming aSelNaming(selectionLabel());
842     std::shared_ptr<Model_Document> aDoc =
843       std::dynamic_pointer_cast<Model_Document>(owner()->document());
844     std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
845     ResultPtr aCont;
846     if (aSelNaming.selectSubShape(aType, aSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
847       // try to find the last context to find the up to date shape
848       if (aCont->shape().get() && !aCont->shape()->isNull() &&
849         aCont->groupName() == ModelAPI_ResultBody::group() && aDoc == owner()->document()) {
850         const TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
851         if (!aConShape.IsNull()) {
852           Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
853           if (!aNS.IsNull()) {
854             aNS = TNaming_Tool::CurrentNamedShape(aNS);
855             if (!aNS.IsNull() && scope().Contains(aNS->Label())) { // scope check is for 2228
856               TDF_Label aLab = aNS->Label();
857               while(aLab.Depth() != 7 && aLab.Depth() > 5)
858                 aLab = aLab.Father();
859               ObjectPtr anObj = aDoc->objects()->object(aLab);
860               if (anObj.get()) {
861                 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
862                 if (aRes)
863                   aCont = aRes;
864               }
865             }
866           }
867         }
868       }
869       // if compsolid is context, try to take sub-solid as context: like in GUI and scripts
870       if (aCont.get() && aShapeToBeSelected.get()) {
871         ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aCont);
872         if (aComp && aComp->numberOfSubs()) {
873           for(int aSubNum = 0; aSubNum < aComp->numberOfSubs(); aSubNum++) {
874             ResultPtr aSub = aComp->subResult(aSubNum);
875             if (aSub && aSub->shape().get() && aSub->shape()->isSubShape(aShapeToBeSelected)) {
876               aCont = aSub;
877               break;
878             }
879           }
880         }
881       }
882       // try to find the latest active result that must be used instead of the selected
883       // to set the active context (like in GUI selection), not concealed one
884       bool aFindNewContext = true;
885       while(aFindNewContext && aCont.get()) {
886         aFindNewContext = false;
887         // take references to all results: root one, any sub
888         ResultCompSolidPtr aCompContext = ModelAPI_Tools::compSolidOwner(aCont);
889         int aSubsSize = (aCompContext.get() ? aCompContext->numberOfSubs() : 0) + 1;
890         for(int aResultNum = 0; aResultNum < aSubsSize; aResultNum++) {
891           ResultPtr aResCont = aCont;
892           if (aCompContext.get())
893             if (aResultNum == aSubsSize - 1)
894               aResCont = aCompContext;
895             else aResCont = aCompContext->subResult(aResultNum);
896           const std::set<AttributePtr>& aRefs = aResCont->data()->refsToMe();
897           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
898           for(; !aFindNewContext && aRef != aRefs.end(); aRef++) {
899             if (!aRef->get() || !(*aRef)->owner().get())
900               continue;
901             // concealed attribute only
902             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
903             if (!ModelAPI_Session::get()->validators()->isConcealed(
904               aRefFeat->getKind(), (*aRef)->id()))
905               continue;
906             // search the feature result that contains sub-shape selected
907             std::list<std::shared_ptr<ModelAPI_Result> > aResults;
908
909             // take all sub-results or one result
910             const std::list<std::shared_ptr<ModelAPI_Result> >& aFResults = aRefFeat->results();
911             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aFResults.begin();
912             for (; aRIter != aFResults.cend(); aRIter++) {
913               // iterate sub-bodies of compsolid
914               ResultCompSolidPtr aComp =
915                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRIter);
916               if (aComp.get() && aComp->numberOfSubs() > 0) {
917                 int aNumSub = aComp->numberOfSubs();
918                 for(int a = 0; a < aNumSub; a++) {
919                   aResults.push_back(aComp->subResult(a));
920                 }
921               } else {
922                 aResults.push_back(*aRIter);
923               }
924             }
925             std::list<std::shared_ptr<ModelAPI_Result> >::iterator aResIter = aResults.begin();
926             for(; aResIter != aResults.end(); aResIter++) {
927               if (!aResIter->get() || !(*aResIter)->data()->isValid() || (*aResIter)->isDisabled())
928                 continue;
929               GeomShapePtr aShape = (*aResIter)->shape();
930               GeomShapePtr aSelectedShape =
931                 aShapeToBeSelected.get() ? aShapeToBeSelected : aCont->shape();
932               if (aShape.get() && aShape->isSubShape(aSelectedShape, false)) {
933                 aCont = *aResIter; // found new context (produced from this) with same subshape
934                 //if (!aShape->isSubShape(aShapeToBeSelected, true)) // take context orientation
935                 //  aShapeToBeSelected->setOrientation();
936                 aFindNewContext = true; // continue searching futher
937                 break;
938               }
939             }
940           }
941         }
942       }
943
944       if (aCenterType != NOT_CENTER) {
945         if (!aShapeToBeSelected->isEdge())
946           continue;
947         std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aShapeToBeSelected));
948         setValueCenter(aCont, aSelectedEdge, aCenterType);
949       } else
950         setValue(aCont, aShapeToBeSelected);
951       return;
952     }
953   }
954
955   TDF_Label aSelLab = selectionLabel();
956   setInvalidIfFalse(aSelLab, false);
957   reset();
958 }
959
960 int Model_AttributeSelection::Id()
961 {
962   int anID = 0;
963   std::shared_ptr<GeomAPI_Shape> aSelection = value();
964   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
965   // support for compsolids:
966   if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
967     aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
968
969
970   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
971   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
972   // searching for the latest main shape
973   if (aSelection && !aSelection->isNull() &&
974     aContext   && !aContext->isNull())
975   {
976     std::shared_ptr<Model_Document> aDoc =
977       std::dynamic_pointer_cast<Model_Document>(context()->document());
978     if (aDoc.get()) {
979       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
980       if (!aNS.IsNull()) {
981         aMainShape = TNaming_Tool::CurrentShape(aNS);
982       }
983     }
984
985     TopTools_IndexedMapOfShape aSubShapesMap;
986     TopExp::MapShapes(aMainShape, aSubShapesMap);
987     anID = aSubShapesMap.FindIndex(aSubShape);
988   }
989   return anID;
990 }
991
992 void Model_AttributeSelection::setId(int theID)
993 {
994   const ResultPtr& aContext = context();
995   std::shared_ptr<GeomAPI_Shape> aSelection;
996
997   std::shared_ptr<GeomAPI_Shape> aContextShape = aContext->shape();
998   // support for compsolids:
999   if (aContext.get() && ModelAPI_Tools::compSolidOwner(aContext).get())
1000     aContextShape = ModelAPI_Tools::compSolidOwner(aContext)->shape();
1001
1002   TopoDS_Shape aMainShape = aContextShape->impl<TopoDS_Shape>();
1003   // searching for the latest main shape
1004   if (theID > 0 &&
1005       aContextShape && !aContextShape->isNull())
1006   {
1007     std::shared_ptr<Model_Document> aDoc =
1008       std::dynamic_pointer_cast<Model_Document>(aContext->document());
1009     if (aDoc.get()) {
1010       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1011       if (!aNS.IsNull()) {
1012         aMainShape = TNaming_Tool::CurrentShape(aNS);
1013       }
1014     }
1015
1016     TopTools_IndexedMapOfShape aSubShapesMap;
1017     TopExp::MapShapes(aMainShape, aSubShapesMap);
1018     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1019
1020     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1021     aResult->setImpl(new TopoDS_Shape(aSelShape));
1022
1023     aSelection = aResult;
1024   }
1025
1026   setValue(aContext, aSelection);
1027 }
1028
1029 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1030 {
1031   std::string aResult;
1032   if (owner()->document() != theContext->document()) {
1033     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1034       aResult = theContext->document()->kind() + "/";
1035     } else {
1036       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1037         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1038       if (aDocRes.get()) {
1039         aResult = aDocRes->data()->name() + "/";
1040       }
1041     }
1042   }
1043   aResult += theContext->data()->name();
1044   return aResult;
1045 }
1046
1047 void Model_AttributeSelection::computeValues(
1048   ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
1049   TopTools_ListOfShape& theShapes)
1050 {
1051   bool aWasWholeContext = theValShape.IsNull();
1052   if (aWasWholeContext) {
1053     //theShapes.Append(theValShape);
1054     //return;
1055     theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
1056   }
1057   //TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
1058   TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
1059   //if (anOldContShape.IsSame(theValShape)) { // full context shape substituted by new full context
1060     //theShapes.Append(aNewContShape);
1061     //return;
1062   //}
1063   // if a new value is unchanged in the new context, do nothing: value is correct
1064   TopExp_Explorer aSubExp(aNewContShape, theValShape.ShapeType());
1065   for(; aSubExp.More(); aSubExp.Next()) {
1066     if (aSubExp.Current().IsSame(theValShape)) {
1067       theShapes.Append(theValShape);
1068       return;
1069     }
1070   }
1071   // if new context becomes compsolid, the resulting sub may be in sub-solids
1072   std::list<ResultPtr> aNewToIterate;
1073   aNewToIterate.push_back(theNewContext);
1074   ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theNewContext);
1075   if (aComp.get()) {
1076     for(int a = 0; a < aComp->numberOfSubs(); a++)
1077       aNewToIterate.push_back(aComp->subResult(a, false));
1078   }
1079
1080   // first iteration: searching for the whole shape appearance (like face of the box)
1081   // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
1082   int aToFindPart = 0;
1083   TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
1084   TopTools_MapOfShape anOlds; // to know how many olds produced new containers
1085   for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
1086     std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
1087     for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
1088       std::shared_ptr<Model_Data> aNewData =
1089         std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
1090       TDF_Label aNewLab = aNewData->label();
1091       // searching for produced sub-shape fully on some label
1092       TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID(), Standard_True);
1093       for(; aNSIter.More(); aNSIter.Next()) {
1094         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1095         for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
1096           if (aToFindPart == 0) { // search shape is fully inside
1097             if (aPairIter.OldShape().IsSame(theValShape)) {
1098               if (aPairIter.NewShape().IsNull()) {// value was removed
1099                 theShapes.Clear();
1100                 return;
1101               }
1102               theShapes.Append(aPairIter.NewShape());
1103             }
1104           } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
1105             TopExp_Explorer anExp(aPairIter.OldShape(), theValShape.ShapeType());
1106             for(; anExp.More(); anExp.Next()) {
1107               if (anExp.Current().IsSame(theValShape)) { // found a new container
1108                 if (aPairIter.NewShape().IsNull()) {// value was removed
1109                   theShapes.Clear();
1110                   return;
1111                 }
1112                 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
1113                 anOlds.Add(aPairIter.OldShape());
1114                 break;
1115               }
1116             }
1117           }
1118         }
1119       }
1120     }
1121   }
1122   if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
1123     // map of sub-shapes -> number of occurences of these shapes in containers
1124     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
1125     TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
1126     for(; aContIter.More(); aContIter.Next()) {
1127       TopExp_Explorer aSubExp(aContIter.Key(), theValShape.ShapeType());
1128       for(; aSubExp.More(); aSubExp.Next()) {
1129         if (!aSubs.IsBound(aSubExp.Current())) {
1130           aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
1131         }
1132         // store old to know how many olds produced this shape
1133         aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
1134       }
1135     }
1136     // if sub is appeared same times in containers as the number of old shapes that contain it
1137     int aCountInOld = anOlds.Size();
1138     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
1139       aSubsIter(aSubs);
1140     for(; aSubsIter.More(); aSubsIter.Next()) {
1141       if (aSubsIter.Value().Size() == aCountInOld) {
1142         theShapes.Append(aSubsIter.Key());
1143       }
1144     }
1145   }
1146   if (theShapes.IsEmpty()) { // nothing was changed
1147     theShapes.Append(aWasWholeContext ? TopoDS_Shape() : theValShape);
1148   }
1149 }
1150
1151 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
1152   const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
1153   TDF_Label theAccessLabel,
1154   std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
1155 {
1156   std::set<ResultPtr> aResults; // to avoid duplicates, new context, null if deleted
1157   TopTools_ListOfShape aResContShapes;
1158   // iterate context and shape, but also if it is sub-shape of main shape, check also it
1159   TopTools_ListOfShape aContextList;
1160   aContextList.Append(theContShape);
1161   if (theContext.get()) {
1162     ResultPtr aComposite = ModelAPI_Tools::compSolidOwner(theContext);
1163     if (aComposite.get() && aComposite->shape().get() && !aComposite->shape()->isNull())
1164       aContextList.Append(aComposite->shape()->impl<TopoDS_Shape>());
1165   }
1166   for(TopTools_ListOfShape::Iterator aContIter(aContextList); aContIter.More(); aContIter.Next()) {
1167     TNaming_SameShapeIterator aModifIter(aContIter.ChangeValue(), theAccessLabel);
1168     for(; aModifIter.More(); aModifIter.Next()) {
1169       TDF_Label anObjLab = aModifIter.Label().Father();
1170       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1171         (theDoc->objects()->object(anObjLab));
1172       if (!aModifierObj.get()) {
1173         // #2241: shape may be sub-element of new object, not main (shell created from faces)
1174         if (!anObjLab.IsRoot())
1175           aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1176           (theDoc->objects()->object(anObjLab.Father()));
1177         if (!aModifierObj.get())
1178           continue;
1179       }
1180       FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
1181       if (!aModifierFeat.get())
1182         continue;
1183       FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1184       if (aModifierFeat == aThisFeature || theDoc->objects()->isLater(aModifierFeat, aThisFeature))
1185         continue; // the modifier feature is later than this, so, should not be used
1186       FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
1187       if (aCurrentModifierFeat == aModifierFeat ||
1188         theDoc->objects()->isLater(aCurrentModifierFeat, aModifierFeat))
1189         continue; // the current modifier is later than the found, so, useless
1190       Handle(TNaming_NamedShape) aNewNS;
1191       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1192       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1193         aResults.insert(aModifierObj);
1194         //TNaming_Iterator aPairIter(aNewNS);
1195         //aResContShapes.Append(aPairIter.NewShape());
1196         aResContShapes.Append(aModifierObj->shape()->impl<TopoDS_Shape>());
1197       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
1198         aResults.insert(ResultPtr());
1199       } else { // not-precessed modification => don't support it
1200         continue;
1201       }
1202     }
1203   }
1204   if (aResults.empty())
1205     return false; // no modifications found, must stay the same
1206   // iterate all results to find futher modifications
1207   std::set<ResultPtr>::iterator aResIter = aResults.begin();
1208   for(; aResIter != aResults.end(); aResIter++) {
1209     if (aResIter->get() != NULL) {
1210       // compute new values by two contextes: the old and the new
1211       TopTools_ListOfShape aValShapes;
1212       computeValues(theContext, *aResIter, theValShape, aValShapes);
1213
1214       TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
1215       for(; aNewVal.More(); aNewVal.Next()) {
1216         std::list<ResultPtr> aNewRes;
1217         TopTools_ListOfShape aNewUpdatedVal;
1218         TopoDS_Shape aNewValSh = aNewVal.Value();
1219         TopoDS_Shape aNewContShape = (*aResIter)->shape()->impl<TopoDS_Shape>();
1220         if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
1221           aNewValSh.Nullify();
1222         if (searchNewContext(theDoc, aNewContShape, *aResIter, aNewValSh,
1223                              theAccessLabel, aNewRes, aNewUpdatedVal))
1224         {
1225           // appeand new results instead of the current ones
1226           std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1227           TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1228           for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1229             theResults.push_back(*aNewIter);
1230             theValShapes.Append(aNewUpdVal.Value());
1231           }
1232         } else { // the current result is good
1233           theResults.push_back(*aResIter);
1234           theValShapes.Append(aNewValSh);
1235         }
1236       }
1237     }
1238   }
1239   return true; // theResults must be empty: everything is deleted
1240 }
1241
1242 void Model_AttributeSelection::updateInHistory()
1243 {
1244   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1245   // only bodies and parts may be modified later in the history, don't do anything otherwise
1246   if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
1247       aContext->groupName() != ModelAPI_ResultPart::group()))
1248     return;
1249   std::shared_ptr<Model_Document> aDoc =
1250     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1251   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1252   if (!aContData.get() || !aContData->isValid())
1253     return;
1254   TDF_Label aContLab = aContData->label(); // named shape where the selected context is located
1255   Handle(TNaming_NamedShape) aContNS;
1256   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
1257     bool aFoundNewContext = true;
1258     ResultPtr aNewContext = aContext;
1259     while(aFoundNewContext) {
1260       aFoundNewContext = false;
1261       // parts have no shape in result, so, trace references using the Part info
1262       if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
1263         ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
1264         if (aPartContext.get()) { // searching for the up to date references to the referenced cont
1265           const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
1266           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1267           for(; aRef != aRefs.end(); aRef++) {
1268             // to avoid detection of part changes by local selection only
1269             AttributeSelectionPtr aSel =
1270               std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1271             if (aSel.get() && !aSel->value()->isSame(aSel->context()->shape()))
1272               continue;
1273
1274             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1275             if (aRefFeat.get() && aRefFeat != owner()) {
1276               FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1277               if (aDoc->objects()->isLater(aThisFeature, aRefFeat)) { // found better feature
1278                 aFoundNewContext = true;
1279                 aNewContext = aRefFeat->firstResult();
1280               }
1281             }
1282           }
1283         }
1284       }
1285     }
1286     if (aNewContext != aContext) {
1287       setValue(aNewContext, value());
1288     }
1289     return;
1290   }
1291   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1292   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1293   // iterate the context shape modifications in order to find a feature that is upper in history
1294   // that this one and is really modifies the referenced result to refer to it
1295   ResultPtr aModifierResFound;
1296   TNaming_Iterator aPairIter(aContNS);
1297   if (!aPairIter.More())
1298     return;
1299   TopoDS_Shape aNewCShape = aPairIter.NewShape();
1300   bool anIterate = true;
1301   // trying to update also the sub-shape selected
1302   GeomShapePtr aSubShape = value();
1303   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1304     aSubShape.reset();
1305   TopoDS_Shape aValShape;
1306   if (aSubShape.get()) {
1307     aValShape = aSubShape->impl<TopoDS_Shape>();
1308   }
1309
1310   std::list<ResultPtr> aNewContexts;
1311   TopTools_ListOfShape aValShapes;
1312   if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1313   {
1314     // update scope to reset to a new one
1315     myScope.Clear();
1316
1317     std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1318     TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1319     if (aNewCont == aNewContexts.end()) { // all results were deleted
1320       ResultPtr anEmptyContext;
1321       std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1322       setValue(anEmptyContext, anEmptyShape); // nullify the selection
1323       return;
1324     }
1325
1326     GeomShapePtr aValueShape;
1327     if (!aNewValues.Value().IsNull()) {
1328       aValueShape = std::make_shared<GeomAPI_Shape>();
1329       aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1330     }
1331     setValue(*aNewCont, aValueShape);
1332     // if there are more than one result, put them by "append" into "parent" list
1333     if (myParent) {
1334       for(aNewCont++, aNewValues.Next(); aNewCont != aNewContexts.end();
1335           aNewCont++, aNewValues.Next()) {
1336         GeomShapePtr aValueShape;
1337         if (!aNewValues.Value().IsNull()) {
1338           aValueShape = std::make_shared<GeomAPI_Shape>();
1339           aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1340         }
1341         myParent->append(*aNewCont, aValueShape);
1342       }
1343     }
1344   }
1345 }
1346
1347 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1348 {
1349   myParent = theParent;
1350 }