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