Salome HOME
Fix for issue #2718: Fatal error when open study with box rotated, translated and...
[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_Objects.h>
27 #include <Model_AttributeSelectionList.h>
28 #include <Model_ResultConstruction.h>
29 #include <ModelAPI_Feature.h>
30 #include <ModelAPI_ResultBody.h>
31 #include <ModelAPI_ResultBody.h>
32 #include <ModelAPI_ResultConstruction.h>
33 #include <ModelAPI_ResultPart.h>
34 #include <ModelAPI_CompositeFeature.h>
35 #include <ModelAPI_Tools.h>
36 #include <ModelAPI_Session.h>
37 #include <ModelAPI_Validator.h>
38 #include <ModelGeomAlgo_Shape.h>
39 #include <Events_InfoMessage.h>
40 #include <GeomAPI_Edge.h>
41 #include <GeomAPI_Pnt.h>
42 #include <GeomAPI_Vertex.h>
43 #include <GeomAPI_ShapeExplorer.h>
44 #include <GeomAlgoAPI_CompoundBuilder.h>
45 #include <GeomAlgoAPI_NExplode.h>
46 #include <Selector_Selector.h>
47
48 #include <TNaming_NamedShape.hxx>
49 #include <TNaming_Tool.hxx>
50 #include <TNaming_Builder.hxx>
51 #include <TNaming_SameShapeIterator.hxx>
52 #include <TNaming_Iterator.hxx>
53 #include <TDataStd_Integer.hxx>
54 #include <TDataStd_UAttribute.hxx>
55 #include <TDataStd_Name.hxx>
56 #include <TopTools_ListOfShape.hxx>
57 #include <TopTools_DataMapOfShapeShape.hxx>
58 #include <TopTools_MapOfShape.hxx>
59 #include <TopExp_Explorer.hxx>
60 #include <BRep_Tool.hxx>
61 #include <TopoDS.hxx>
62 #include <TopoDS_Edge.hxx>
63 #include <TopExp.hxx>
64 #include <TDF_ChildIterator.hxx>
65 #include <TDF_ChildIDIterator.hxx>
66 #include <TopoDS_Iterator.hxx>
67 #include <TDF_ChildIDIterator.hxx>
68 #include <Geom_Circle.hxx>
69 #include <Geom_Ellipse.hxx>
70 #include <BRep_Builder.hxx>
71
72 //#define DEB_NAMING 1
73 #ifdef DEB_NAMING
74 #include <BRepTools.hxx>
75 #endif
76 /// added to the index in the packed map to signalize that the vertex of edge is selected
77 /// (multiplied by the index of the edge)
78 static const int kSTART_VERTEX_DELTA = 1000000;
79 // identifier that there is simple reference: selection equals to context
80 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
81 // reference to Part sub-object
82 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
83 // selection is invalid after recomputation
84 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
85
86 // identifier of the selection of the center of circle on edge
87 Standard_GUID kCIRCLE_CENTER("d0d0e0f1-217a-4b95-8fbb-0c4132f23718");
88 // identifier of the selection of the first focus point of ellipse on edge
89 Standard_GUID kELLIPSE_CENTER1("f70df04c-3168-4dc9-87a4-f1f840c1275d");
90 // identifier of the selection of the second focus point of ellipse on edge
91 Standard_GUID kELLIPSE_CENTER2("1395ae73-8e02-4cf8-b204-06ff35873a32");
92 // reference to the external sketch face
93 Standard_GUID kEXT_SKETCH_FACE("ba32aa31-bde7-422f-80b4-79c757c77b49");
94 // reference to the external sketch edge
95 Standard_GUID kEXT_SKETCH_EDGE("ba32aa31-bde7-422f-80b4-79c757c77b48");
96 // reference to the external sketch vertex
97 Standard_GUID kEXT_SKETCH_VERT("ba32aa31-bde7-422f-80b4-79c757c77b47");
98
99 // prefix for the whole feature context identification
100 const static std::string kWHOLE_FEATURE = "all-in-";
101
102 // on this label is stored:
103 // TNaming_NamedShape - selected shape
104 // TNaming_Naming - topological selection information (for the body)
105 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
106 // TDataStd_Integer - type of the selected shape (for construction)
107 // TDF_Reference - from ReferenceAttribute, the context
108 bool Model_AttributeSelection::setValue(const ObjectPtr& theContext,
109   const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
110 {
111   if (theTemporarily &&
112       (!theContext.get() || theContext->groupName() != ModelAPI_Feature::group())) {
113     // just keep the stored without DF update
114     myTmpContext = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
115     myTmpSubShape = theSubShape;
116     owner()->data()->sendAttributeUpdated(this);
117     return true;
118   } else {
119     myTmpContext.reset();
120     myTmpSubShape.reset();
121     myTmpCenterType = NOT_CENTER;
122   }
123
124   CenterType aType;
125   const std::shared_ptr<GeomAPI_Shape>& anOldShape = internalValue(aType);
126   bool isOldContext = theContext == myRef.value();
127   bool isOldShape = isOldContext &&
128     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
129   if (isOldShape) return false; // shape is the same, so context is also unchanged
130   bool aToUnblock = false;
131   // update the referenced object if needed
132   if (!isOldContext) {
133     aToUnblock = !owner()->data()->blockSendAttributeUpdated(true);
134     myRef.setValue(theContext);
135   }
136
137   // do noth use naming if selected shape is result shape itself, but not sub-shape
138   TDF_Label aSelLab = selectionLabel();
139   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
140   aSelLab.ForgetAttribute(kINVALID_SELECTION);
141   aSelLab.ForgetAttribute(kCIRCLE_CENTER);
142   aSelLab.ForgetAttribute(kELLIPSE_CENTER1);
143   aSelLab.ForgetAttribute(kELLIPSE_CENTER2);
144   aSelLab.ForgetAttribute(kEXT_SKETCH_FACE);
145   aSelLab.ForgetAttribute(kEXT_SKETCH_EDGE);
146   aSelLab.ForgetAttribute(kEXT_SKETCH_VERT);
147
148   bool isDegeneratedEdge = false;
149   // do not use the degenerated edge as a shape, a null context and shape is used in the case
150   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
151     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
152     if (aSubShape.ShapeType() == TopAbs_EDGE)
153       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
154   }
155   if (!theContext.get() || isDegeneratedEdge) {
156     // to keep the reference attribute label
157     TDF_Label aRefLab = myRef.myRef->Label();
158     aSelLab.ForgetAllAttributes(true);
159     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
160     if (aToUnblock)
161       owner()->data()->blockSendAttributeUpdated(false);
162     return false;
163   }
164   bool isSelectBody = theContext->groupName() == ModelAPI_ResultBody::group();
165   if (!isSelectBody) {
166     ResultConstructionPtr aContextConstruction =
167       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
168     isSelectBody = aContextConstruction.get() && !aContextConstruction->isInfinite();
169   }
170   if (isSelectBody) {
171     ResultPtr aContextResult = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);
172     GeomShapePtr aContextShape = aContextResult->shape();
173     // do not select the whole shape for body:it is already must be in the data framework
174     // equal and null selected objects mean the same: object is equal to context,
175     if (aContextShape.get() && (aContextShape->isEqual(theSubShape) || !theSubShape.get())) {
176       aSelLab.ForgetAllAttributes(true);
177       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
178     } else {
179       selectBody(aContextResult, theSubShape);
180     }
181   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
182     aSelLab.ForgetAllAttributes(true); // to remove old selection data
183     std::shared_ptr<Model_ResultConstruction> aConstruction =
184       std::dynamic_pointer_cast<Model_ResultConstruction>(theContext);
185     std::shared_ptr<GeomAPI_Shape> aSubShape;
186     if (theSubShape.get() && !aConstruction->shape()->isEqual(theSubShape))
187       aSubShape = theSubShape; // the whole context
188     if (aConstruction->isInfinite()) {
189       // For correct naming selection, put the shape into the naming structure.
190       // It seems sub-shapes are not needed: only this shape is (and can be) selected.
191       TNaming_Builder aBuilder(aSelLab);
192       aBuilder.Generated(aConstruction->shape()->impl<TopoDS_Shape>());
193     }
194   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
195     aSelLab.ForgetAllAttributes(true);
196     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
197     selectPart(std::dynamic_pointer_cast<ModelAPI_Result>(theContext), theSubShape);
198   } else { // check the feature context: parent-Part of this feature should not be used
199     FeaturePtr aFeatureContext = std::dynamic_pointer_cast<ModelAPI_Feature>(theContext);
200     if (aFeatureContext.get()) {
201       if (owner()->document() != aFeatureContext->document()) {
202         aSelLab.ForgetAllAttributes(true);
203         myRef.setValue(ObjectPtr());
204         if (aToUnblock)
205           owner()->data()->blockSendAttributeUpdated(false);
206         return false;
207       }
208     }
209   }
210
211   owner()->data()->sendAttributeUpdated(this);
212
213   if (aToUnblock)
214     owner()->data()->blockSendAttributeUpdated(false);
215
216   return true;
217 }
218
219 void Model_AttributeSelection::setValueCenter(
220     const ObjectPtr& theContext, const std::shared_ptr<GeomAPI_Edge>& theEdge,
221     const CenterType theCenterType, const bool theTemporarily)
222 {
223   bool anUpdated = setValue(theContext, theEdge, theTemporarily);
224   if (theTemporarily) {
225     myTmpCenterType = theCenterType;
226   } else { // store in the data structure
227     TDF_Label aSelLab = selectionLabel();
228     switch(theCenterType) {
229     case CIRCLE_CENTER:
230       if (!anUpdated)
231         anUpdated = !aSelLab.IsAttribute(kCIRCLE_CENTER);
232       TDataStd_UAttribute::Set(aSelLab, kCIRCLE_CENTER);
233       break;
234     case ELLIPSE_FIRST_FOCUS:
235       if (!anUpdated)
236         anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER1);
237       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER1);
238       break;
239     case ELLIPSE_SECOND_FOCUS:
240       if (!anUpdated)
241         anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER2);
242       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER2);
243       break;
244     }
245     if (anUpdated)
246       owner()->data()->sendAttributeUpdated(this);
247   }
248 }
249
250 void Model_AttributeSelection::selectValue(
251     const std::shared_ptr<ModelAPI_AttributeSelection>& theSource)
252 {
253   CenterType aType;
254   std::shared_ptr<GeomAPI_Shape> aValue =
255     std::dynamic_pointer_cast<Model_AttributeSelection>(theSource)->internalValue(aType);
256   if (!aValue.get() || aType == NOT_CENTER) {
257     setValue(theSource->context(), aValue);
258   } else {
259     std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge);
260     anEdge->setImpl(new TopoDS_Shape(aValue->impl<TopoDS_Shape>()));
261     setValueCenter(theSource->context(), anEdge, aType);
262   }
263 }
264
265 void Model_AttributeSelection::removeTemporaryValues()
266 {
267   if (myTmpContext.get() || myTmpSubShape.get()) {
268     myTmpContext.reset();
269     myTmpSubShape.reset();
270   }
271 }
272
273 // returns the center of the edge: circular or elliptical
274 GeomShapePtr centerByEdge(GeomShapePtr theEdge, ModelAPI_AttributeSelection::CenterType theType)
275 {
276   if (theType != ModelAPI_AttributeSelection::NOT_CENTER && theEdge.get() != NULL) {
277     TopoDS_Shape aShape = theEdge->impl<TopoDS_Shape>();
278     if (!aShape.IsNull() && aShape.ShapeType() == TopAbs_EDGE) {
279       TopoDS_Edge anEdge = TopoDS::Edge(aShape);
280       double aFirst, aLast;
281       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
282       if (!aCurve.IsNull()) {
283         TopoDS_Vertex aVertex;
284         BRep_Builder aBuilder;
285         if (theType == ModelAPI_AttributeSelection::CIRCLE_CENTER) {
286           Handle(Geom_Circle) aCirc = Handle(Geom_Circle)::DownCast(aCurve);
287           if (!aCirc.IsNull()) {
288             aBuilder.MakeVertex(aVertex, aCirc->Location(), Precision::Confusion());
289           }
290         } else { // ellipse
291           Handle(Geom_Ellipse) anEll = Handle(Geom_Ellipse)::DownCast(aCurve);
292           if (!anEll.IsNull()) {
293             aBuilder.MakeVertex(aVertex,
294               theType == ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS ?
295               anEll->Focus1() : anEll->Focus2(), Precision::Confusion());
296           }
297         }
298         if (!aVertex.IsNull()) {
299           std::shared_ptr<GeomAPI_Vertex> aResult(new GeomAPI_Vertex);
300           aResult->setImpl(new TopoDS_Vertex(aVertex));
301           return aResult;
302         }
303       }
304     }
305   }
306   return theEdge; // no vertex, so, return the initial edge
307 }
308
309 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
310 {
311   if (!ModelAPI_AttributeSelection::isInitialized() && !myTmpContext.get() && !myTmpSubShape.get())
312     return std::shared_ptr<GeomAPI_Shape>();
313   CenterType aType = NOT_CENTER;
314   std::shared_ptr<GeomAPI_Shape> aResult = internalValue(aType);
315   return centerByEdge(aResult, aType);
316 }
317
318 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::internalValue(CenterType& theType)
319 {
320   theType = NOT_CENTER;
321   GeomShapePtr aResult;
322   if (myTmpContext.get() || myTmpSubShape.get()) {
323     theType = myTmpCenterType;
324     ResultConstructionPtr aResulConstruction =
325       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myTmpContext);
326     if(aResulConstruction.get()) {
327       // it is just reference to construction.
328       return myTmpSubShape;
329     }
330     return myTmpSubShape.get() ? myTmpSubShape : myTmpContext->shape();
331   }
332
333   TDF_Label aSelLab = selectionLabel();
334   if (aSelLab.IsAttribute(kINVALID_SELECTION))
335     return aResult;
336
337   if (aSelLab.IsAttribute(kCIRCLE_CENTER))
338     theType = CIRCLE_CENTER;
339   else if (aSelLab.IsAttribute(kELLIPSE_CENTER1))
340     theType = ELLIPSE_FIRST_FOCUS;
341   else if (aSelLab.IsAttribute(kELLIPSE_CENTER2))
342     theType = ELLIPSE_SECOND_FOCUS;
343
344
345   if (myRef.isInitialized()) {
346     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
347       ResultPtr aContext = context();
348       if (!aContext.get() || aContext->groupName() == ModelAPI_ResultConstruction::group())
349         return aResult; // empty result, for whole construction selection also
350       return aContext->shape();
351     }
352     if (aSelLab.IsAttribute(kPART_REF_ID)) {
353       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
354       if (!aPart.get() || !aPart->isActivated())
355         return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
356       Handle(TDataStd_Integer) anIndex;
357       if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
358         if (anIndex->Get()) { // special selection attribute was created, use it
359           return aPart->selectionValue(anIndex->Get());
360         } else { // face with name is already in the data model, so try to take it by name
361           Handle(TDataStd_Name) aName;
362           if (aSelLab.FindAttribute(TDataStd_Name::GetID(), aName)) {
363             std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
364             std::size_t aPartEnd = aSubShapeName.find('/');
365             if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
366               std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
367               int anIndex;
368               std::string aType; // to reuse already existing selection the type is not needed
369               return aPart->shapeInPart(aNameInPart, aType, anIndex);
370             }
371           }
372         }
373       }
374     }
375
376     std::shared_ptr<Model_ResultConstruction> aConstr =
377       std::dynamic_pointer_cast<Model_ResultConstruction>(context());
378     if (aConstr) {
379       if (aConstr->isInfinite())
380         return aResult; // empty result
381       // external sketch face
382       Handle(TDataStd_Integer) anIndex;
383       if (aSelLab.FindAttribute(kEXT_SKETCH_FACE, anIndex)) {
384         return aConstr->face(anIndex->Get());
385       }
386       if (aSelLab.FindAttribute(kEXT_SKETCH_EDGE, anIndex) ||
387           aSelLab.FindAttribute(kEXT_SKETCH_VERT, anIndex)) {
388         bool isVert = anIndex->ID() == kEXT_SKETCH_VERT; // vertex is selected
389         CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(
390           aConstr->document()->feature(aConstr));
391         if (aComposite.get()) {
392           int aSubNum = anIndex->Get() % 1000000;
393           int aVertShape = (anIndex->Get() - aSubNum) / 1000000;
394           FeaturePtr aSubFeat = aComposite->subFeature(aSubNum);
395           if (aSubFeat.get()) {
396             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSubFeat->results();
397             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
398             for (; aRes != aResults.cend(); aRes++) {
399               ResultConstructionPtr aConstr =
400                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
401               if (aConstr->shape()) {
402                 if (!isVert && aConstr->shape()->isEdge())
403                   return aConstr->shape();
404                 else if (isVert && aVertShape == 0 && aConstr->shape()->isVertex())
405                   return aConstr->shape();
406                 else if (isVert && aVertShape > 1 && aConstr->shape()->isEdge()) {
407                   GeomAPI_ShapeExplorer anExp(aConstr->shape(), GeomAPI_Shape::VERTEX);
408                   for(; anExp.more(); anExp.next()) {
409                     if (aVertShape == 1)
410                       return anExp.current();
411                     aVertShape--;
412                   }
413                 }
414               }
415             }
416           }
417         }
418       }
419     }
420     if (!aConstr.get()) { // for construction context, return empty result as usual even
421       // the whole feature is selected
422       FeaturePtr aFeature = contextFeature();
423       if (aFeature.get()) {
424         std::list<GeomShapePtr> allShapes;
425         std::list<ResultPtr>::const_iterator aRes = aFeature->results().cbegin();
426         for (; aRes != aFeature->results().cend(); aRes++) {
427           if (aRes->get() && !(*aRes)->isDisabled()) {
428             GeomShapePtr aShape = (*aRes)->shape();
429             if (aShape.get() && !aShape->isNull()) {
430               allShapes.push_back(aShape);
431             }
432           }
433         }
434         return GeomAlgoAPI_CompoundBuilder::compound(allShapes);
435       }
436     }
437
438     Handle(TNaming_NamedShape) aSelection;
439     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
440       TopoDS_Shape aSelShape = aSelection->Get();
441       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
442       aResult->setImpl(new TopoDS_Shape(aSelShape));
443     } else if (aConstr) { // simple construction element: just shape of this construction element
444       aResult = aConstr->shape();
445     }
446   }
447   return aResult;
448 }
449
450 bool Model_AttributeSelection::isInvalid()
451 {
452   return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
453 }
454
455 bool Model_AttributeSelection::isInitialized()
456 {
457   if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
458     std::shared_ptr<GeomAPI_Shape> aResult;
459     if (myRef.isInitialized()) {
460       TDF_Label aSelLab = selectionLabel();
461       if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
462         ResultPtr aContext = context();
463         return aContext.get() != NULL;
464       }
465       Handle(TNaming_NamedShape) aSelection;
466       if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
467         return !aSelection->Get().IsNull();
468       } else { // for simple construction element: just shape of this construction element
469         std::shared_ptr<Model_ResultConstruction> aConstr =
470           std::dynamic_pointer_cast<Model_ResultConstruction>(context());
471         if (aConstr.get()) {
472             return true;
473         }
474         // for the whole feature, a feature object
475         FeaturePtr aFeat = contextFeature();
476         if (aFeat.get())
477           return true;
478       }
479     }
480   }
481   return false;
482 }
483
484 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
485   : myRef(theLabel)
486 {
487   myIsInitialized = myRef.isInitialized();
488   myParent = NULL;
489 }
490
491 void Model_AttributeSelection::setID(const std::string theID)
492 {
493   myRef.setID(theID);
494   ModelAPI_AttributeSelection::setID(theID);
495 }
496
497 ResultPtr Model_AttributeSelection::context()
498 {
499   if (!ModelAPI_AttributeSelection::isInitialized() && !myTmpContext.get() && !myTmpSubShape.get())
500     return ResultPtr();
501
502   if (myTmpContext.get() || myTmpSubShape.get()) {
503     return myTmpContext;
504   }
505
506   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
507   // for parts there could be same-data result, so take the last enabled
508   if (aResult.get()) {
509     if(aResult->groupName() == ModelAPI_ResultPart::group()) {
510       int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
511       for(int a = aSize - 1; a >= 0; a--) {
512         ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
513         if(aPart.get() && aPart->data() == aResult->data()) {
514           ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
515           FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
516           // check that this result is not this-feature result (it is forbidden t oselect itself)
517           if(anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
518             return aPartResult;
519           }
520         }
521       }
522     }
523   } else { // if feature - construction is selected, it has only one result, return this result
524     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
525     if (aFeature.get() && aFeature->results().size() == 1 &&
526         aFeature->firstResult()->groupName() == ModelAPI_ResultConstruction::group())
527       return aFeature->firstResult();
528   }
529   return aResult;
530 }
531
532 FeaturePtr Model_AttributeSelection::contextFeature() {
533   if (myTmpContext.get() || myTmpSubShape.get()) {
534     return FeaturePtr(); // feature can not be selected temporarily
535   }
536   return std::dynamic_pointer_cast<ModelAPI_Feature>(myRef.value());
537 }
538 ObjectPtr Model_AttributeSelection::contextObject() {
539   FeaturePtr aRes = contextFeature();
540   if (aRes.get())
541     return aRes;
542   return context();
543 }
544
545
546 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
547 {
548   ModelAPI_AttributeSelection::setObject(theObject);
549   myRef.setObject(theObject);
550 }
551
552 /// Sets the invalid flag if flag is false, or removes it if "true"
553 /// Returns theFlag
554 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
555   if (theFlag) {
556     theLab.ForgetAttribute(kINVALID_SELECTION);
557   } else {
558     TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
559   }
560   return theFlag;
561 }
562
563 void Model_AttributeSelection::split(
564   ResultPtr theContext, TopoDS_Shape theNewShape, TopAbs_ShapeEnum theType)
565 {
566   TopTools_ListOfShape aSubs;
567   for(TopoDS_Iterator anExplorer(theNewShape); anExplorer.More(); anExplorer.Next()) {
568     if (!anExplorer.Value().IsNull() &&
569       anExplorer.Value().ShapeType() == theType) {
570         aSubs.Append(anExplorer.Value());
571     } else { // invalid case; bad result shape, so, impossible to split easily
572       aSubs.Clear();
573       break;
574     }
575   }
576   if (aSubs.Extent() > 1) { // ok to split
577     TopTools_ListIteratorOfListOfShape aSub(aSubs);
578     GeomShapePtr aSubSh(new GeomAPI_Shape);
579     aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
580     setValue(theContext, aSubSh);
581     for(aSub.Next(); aSub.More(); aSub.Next()) {
582       GeomShapePtr aSubSh(new GeomAPI_Shape);
583       aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
584       myParent->append(theContext, aSubSh);
585     }
586   }
587 }
588
589 bool Model_AttributeSelection::update()
590 {
591   FeaturePtr aContextFeature = contextFeature();
592   if (aContextFeature.get()) {
593     owner()->data()->sendAttributeUpdated(this);  // send updated if "update" called in any way
594     return true;
595   }
596   TDF_Label aSelLab = selectionLabel();
597   ResultPtr aContext = context();
598   if (!aContext.get())
599     return setInvalidIfFalse(aSelLab, false);
600   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
601     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
602   }
603
604   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
605     std::shared_ptr<GeomAPI_Shape> aNoSelection;
606     bool aResult = selectPart(aContext, aNoSelection, true);
607     aResult = setInvalidIfFalse(aSelLab, aResult);
608     if (aResult) {
609       owner()->data()->sendAttributeUpdated(this);
610     }
611     return aResult;
612   }
613
614   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
615     // body: just a named shape, use topological selection mechanism
616     bool aResult = false;
617     TopoDS_Shape anOldShape;
618     Handle(TNaming_NamedShape) aNS;
619     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
620       anOldShape = aNS->Get();
621
622     Selector_Selector aSelector(aSelLab);
623     if (aSelector.restore()) { // it is stored in old OCCT format, use TNaming_Selector
624       TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
625       aResult = aSelector.solve(aContextShape);
626     }
627     aResult = setInvalidIfFalse(aSelLab, aResult);
628
629     TopoDS_Shape aNewShape;
630     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aNS))
631       aNewShape = aNS->Get();
632
633     if (anOldShape.IsNull() || aNewShape.IsNull() || !anOldShape.IsEqual(aNewShape)) {
634       // shape type shoud not not changed: if shape becomes compound of such shapes, then split
635       if (myParent && !anOldShape.IsNull() && !aNewShape.IsNull() &&
636           anOldShape.ShapeType() != aNewShape.ShapeType() &&
637           (aNewShape.ShapeType() == TopAbs_COMPOUND || aNewShape.ShapeType() == TopAbs_COMPSOLID))
638       {
639         split(aContext, aNewShape, anOldShape.ShapeType());
640       }
641       owner()->data()->sendAttributeUpdated(this);  // send updated if shape is changed
642     }
643     return aResult;
644   }
645
646   if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
647     bool aResult = true;
648     std::shared_ptr<Model_ResultConstruction> aConstructionContext =
649       std::dynamic_pointer_cast<Model_ResultConstruction>(aContext);
650     if (!aConstructionContext->isInfinite()) {
651       // external sketch face
652       Handle(TDataStd_Integer) anIndex;
653       if (aSelLab.FindAttribute(kEXT_SKETCH_FACE, anIndex)) {
654         return setInvalidIfFalse(aSelLab, anIndex->Get() < aConstructionContext->facesNum());
655       }
656       if (aSelLab.FindAttribute(kEXT_SKETCH_EDGE, anIndex) ||
657           aSelLab.FindAttribute(kEXT_SKETCH_VERT, anIndex)) {
658         CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(
659           aConstructionContext->document()->feature(aConstructionContext));
660         if (aComposite.get()) {
661           FeaturePtr aSubFeat = aComposite->subFeature(anIndex->Get() % 1000000);
662           return setInvalidIfFalse(aSelLab, aSubFeat.get() != NULL);
663         }
664         return setInvalidIfFalse(aSelLab, false); // composite sub-feature is not found
665       }
666       Selector_Selector aSelector(aSelLab);
667       aResult = aSelector.restore();
668       TopoDS_Shape anOldShape = aSelector.value();
669       if (aResult) {
670         TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
671         aResult = aSelector.solve(aContextShape);
672       }
673       aResult = setInvalidIfFalse(aSelLab, aResult);
674       if (aResult && !anOldShape.IsEqual(aSelector.value()))
675         owner()->data()->sendAttributeUpdated(this);  // send updated if shape is changed
676     } else {
677       owner()->data()->sendAttributeUpdated(this);  // send updated if "update" called in any way
678     }
679     return aResult;
680   }
681   return setInvalidIfFalse(aSelLab, false); // unknown case
682 }
683
684 void Model_AttributeSelection::selectBody(
685   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
686 {
687   // perform the selection
688   TopoDS_Shape aContext;
689
690   ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(theContext);//myRef.value()
691   if (aBody) {
692     aContext = aBody->shape()->impl<TopoDS_Shape>();
693   } else {
694     ResultPtr aResult =
695       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
696     if (aResult) {
697       aContext = aResult->shape()->impl<TopoDS_Shape>();
698     } else {
699       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
700       return;
701     }
702   }
703
704   if (!aContext.IsNull()) {
705     TDF_Label aSelLab = selectionLabel();
706     TopoDS_Shape aNewSub = theSubShape->impl<TopoDS_Shape>();
707     FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
708     if (aFeatureOwner->document() != theContext->document()) { // reference to the sketch face
709       if (theSubShape->shapeType() == GeomAPI_Shape::FACE) { // sketch face
710         ResultConstructionPtr aConstr =
711           std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(theContext);
712         int aFaceIndex = -1, aFacesNum = aConstr->facesNum();
713         for(int a = 0; a < aFacesNum; a++) {
714           if (aConstr->face(a)->isEqual(theSubShape)) {
715             aFaceIndex = a;
716             break;
717           }
718         }
719         if (aFaceIndex >= 0) {
720           TDataStd_Integer::Set(aSelLab, kEXT_SKETCH_FACE, aFaceIndex); // store index of the face
721           return;
722         }
723       } else if (theSubShape->shapeType() == GeomAPI_Shape::EDGE ||// sketch result edge (full one)
724                  theSubShape->shapeType() == GeomAPI_Shape::VERTEX) { // or start/end vertex
725         bool isVertex = theSubShape->shapeType() == GeomAPI_Shape::VERTEX;
726         CompositeFeaturePtr aComposite = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(
727           theContext->document()->feature(theContext));
728         if (aComposite.get()) { // iterate edges of composite to find index of matched with value
729           int aSub, anEdgeIndex = -1, aSubNum = aComposite->numberOfSubs();
730           int aVertIndex = -1, aVertShape = -1; // shape: 0 full, 1 start, 2 end
731           for(aSub = 0; aSub < aSubNum && anEdgeIndex == -1; aSub++) {
732             FeaturePtr aSubFeat = aComposite->subFeature(aSub);
733             const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSubFeat->results();
734             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
735             for (; aRes != aResults.cend(); aRes++) {
736               ResultConstructionPtr aConstr =
737                 std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
738               if (aConstr->shape() && aConstr->shape()->isEdge()) {
739                 if (isVertex) {
740                   GeomAPI_ShapeExplorer aVertExp(aConstr->shape(), GeomAPI_Shape::VERTEX);
741                   for(int aNum = 1; aVertExp.more(); aVertExp.next(), aNum++) {
742                     if (aVertExp.current()->isSame(theSubShape) && aVertShape != 0) {
743                       aVertIndex = aSub;
744                       aVertShape = aNum;
745                     }
746                   }
747                 } else {
748                   if (aConstr->shape()->isSame(theSubShape)) {
749                     anEdgeIndex = aSub;
750                     break;
751                   }
752                 }
753               } else if (isVertex && aConstr->shape() && aConstr->shape()->isVertex()) {
754                 if (aConstr->shape()->isSame(theSubShape)) {
755                   aVertIndex = aSub;
756                   aVertShape = 0;
757                 }
758               }
759             }
760           }
761           if (anEdgeIndex >= 0) {
762             TDataStd_Integer::Set(aSelLab, kEXT_SKETCH_EDGE, anEdgeIndex); // store index of edge
763             return;
764           } else if (aVertIndex >= 0) {
765             aVertIndex += aVertShape * 1000000; // to store both integers: index and shape
766             TDataStd_Integer::Set(aSelLab, kEXT_SKETCH_VERT, aVertIndex); // store index of edge
767             return;
768           }
769         }
770       }
771     }
772     bool aSelectorOk = true;
773     Selector_Selector aSel(aSelLab);
774     try {
775       aSelectorOk = aSel.select(aContext, aNewSub);
776       if (aSelectorOk) {
777         aSel.store();
778         aSelectorOk = aSel.solve(aContext);
779       }
780     } catch(...) {
781       aSelectorOk = false;
782     }
783     Handle(TNaming_NamedShape) aSelectorShape;
784     if (aSelectorOk && aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aSelectorShape))
785     {
786       TopoDS_Shape aShape = aSelectorShape->Get();
787       if (aShape.IsNull() || aShape.ShapeType() != aNewSub.ShapeType())
788         aSelectorOk = false;
789     }
790     if (!aSelectorOk) {
791       setInvalidIfFalse(aSelLab, false);
792     }
793   }
794 }
795
796 bool Model_AttributeSelection::selectPart(
797   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
798   const bool theUpdate)
799 {
800   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
801   if (!aPart.get() || !aPart->isActivated())
802     return true; // postponed naming
803   if (theUpdate) {
804     Handle(TDataStd_Integer) anIndex;
805     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
806       // by internal selection
807       if (anIndex->Get() > 0) {
808         // update the selection by index
809         return aPart->updateInPart(anIndex->Get());
810       } else {
811         return true; // nothing to do, referencing just by name
812       }
813     }
814     return true; // nothing to do, referencing just by name
815   }
816   // store the shape (in case part is not loaded it should be useful
817   TopoDS_Shape aShape;
818   std::string aName = theContext->data()->name();
819   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
820     aShape = theContext->shape()->impl<TopoDS_Shape>();
821   } else {
822     aShape = theSubShape->impl<TopoDS_Shape>();
823     int anIndex;
824     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
825     TDataStd_Integer::Set(selectionLabel(), anIndex);
826   }
827   TNaming_Builder aBuilder(selectionLabel());
828   aBuilder.Select(aShape, aShape);
829   // identify by name in the part
830   TDataStd_Name::Set(selectionLabel(), aName.c_str());
831   return !aName.empty();
832 }
833
834 TDF_Label Model_AttributeSelection::selectionLabel()
835 {
836   return myRef.myRef->Label().FindChild(1);
837 }
838
839 /// prefixes of the shape names with centers defined
840 static std::map<ModelAPI_AttributeSelection::CenterType, std::string> kCENTERS_PREFIX;
841
842 /// returns the map that contains all possible prefixes of the center-names
843 static std::map<ModelAPI_AttributeSelection::CenterType, std::string>& centersMap()
844 {
845   if (kCENTERS_PREFIX.empty()) { // fill map by initial values
846     kCENTERS_PREFIX[ModelAPI_AttributeSelection::CIRCLE_CENTER] = "__cc";
847     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS] = "__eff";
848     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_SECOND_FOCUS] = "__esf";
849   }
850   return kCENTERS_PREFIX;
851 }
852
853 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
854 {
855   std::string aName("");
856   if(!this->isInitialized())
857     return !theDefaultName.empty() ? theDefaultName : aName;
858
859   CenterType aCenterType = NOT_CENTER;
860   std::shared_ptr<GeomAPI_Shape> aSubSh = internalValue(aCenterType);
861   ResultPtr aCont = context();
862
863   if (!aCont.get() ||
864       (aCont->groupName() == ModelAPI_ResultConstruction::group() && contextFeature().get())) {
865     // selection of a full feature
866     FeaturePtr aFeatureCont = contextFeature();
867     if (aFeatureCont.get()) {
868       return kWHOLE_FEATURE + aFeatureCont->name();
869     }
870     // in case of selection of removed result
871     return "";
872   }
873
874   TDF_Label aSelLab = selectionLabel();
875   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // whole context, no value
876     return contextName(aCont);
877   }
878
879   // if it is in result of another part
880   if (aCont->groupName() == ModelAPI_ResultPart::group()) {
881     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aCont);
882     int anIndex;
883     GeomShapePtr aValue = value();
884     if (aValue.get())
885       return aPart->data()->name() + "/" + aPart->nameInPart(aValue, anIndex);
886     else
887       return aPart->data()->name();
888   }
889
890
891   // whole infinitive construction
892   if (aCont->groupName() == ModelAPI_ResultConstruction::group()) {
893     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<Model_ResultConstruction>(aCont);
894     if (aConstr->isInfinite()) {
895       return contextName(aCont);
896     } else {
897       // external sketch face
898       Handle(TDataStd_Integer) anIndex;
899       if (aSelLab.FindAttribute(kEXT_SKETCH_FACE, anIndex) ||
900           aSelLab.FindAttribute(kEXT_SKETCH_EDGE, anIndex) ||
901           aSelLab.FindAttribute(kEXT_SKETCH_VERT, anIndex)) {
902         std::shared_ptr<Model_Document> anExtDoc =
903           std::dynamic_pointer_cast<Model_Document>(aCont->document());
904         Selector_Selector aSelector(anExtDoc->extConstructionsLabel());
905         TopoDS_Shape aContShape = aConstr->shape()->impl<TopoDS_Shape>();
906         TopoDS_Shape aValShape = value()->impl<TopoDS_Shape>();
907         aSelector.select(aContShape, aValShape);
908         myRestoreDocument = anExtDoc;
909         std::string aName = anExtDoc->kind() + "/" + aSelector.name(this);
910         myRestoreDocument.reset();
911         return aName;
912       }
913     }
914   }
915
916   Selector_Selector aSelector(aSelLab);
917   std::string aResult;
918   if (aSelector.restore())
919     aResult = aSelector.name(this);
920   /*
921   Model_SelectionNaming aSelNaming(aSelLab);
922   std::string aResult = aSelNaming.namingName(
923     aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
924     */
925   if (aCenterType != NOT_CENTER) {
926     aResult += centersMap()[aCenterType];
927   }
928   return aResult;
929 }
930
931 // returns the center type and modifies the shape name if this name is center-name
932 static ModelAPI_AttributeSelection::CenterType centerTypeByName(std::string& theShapeName)
933 {
934   std::map<ModelAPI_AttributeSelection::CenterType, std::string>::iterator aPrefixIter =
935     centersMap().begin();
936   for(; aPrefixIter != centersMap().end(); aPrefixIter++) {
937     std::size_t aFound = theShapeName.find(aPrefixIter->second);
938     if (aFound != std::string::npos &&
939         aFound == theShapeName.size() - aPrefixIter->second.size()) {
940       theShapeName = theShapeName.substr(0, aFound);
941       return aPrefixIter->first;
942     }
943   }
944   return ModelAPI_AttributeSelection::NOT_CENTER;
945 }
946
947 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
948 void Model_AttributeSelection::selectSubShape(
949   const std::string& theType, const std::string& theSubShapeName)
950 {
951   if(theSubShapeName.empty() || theType.empty()) return;
952
953   std::string aSubShapeName = theSubShapeName;
954   CenterType aCenterType = theType[0] == 'v' || theType[0] == 'V' ? // only for vertex-type
955     centerTypeByName(aSubShapeName) : NOT_CENTER;
956   std::string aType = aCenterType == NOT_CENTER ? theType : "EDGE"; // search for edge now
957   static const GeomShapePtr anEmptyShape;
958
959   // first iteration is selection by name without center prefix, second - in case of problem,
960   // try with initial name
961   for(int aUseCenter = 1; aUseCenter >= 0; aUseCenter--)  {
962     if (aUseCenter == 0 && aCenterType != NOT_CENTER) {
963       aSubShapeName = theSubShapeName;
964       aCenterType = NOT_CENTER;
965       aType = theType;
966     } else if (aUseCenter != 1) continue;
967     TopAbs_ShapeEnum aShapeType =  TopAbs_ShapeEnum(GeomAPI_Shape::shapeTypeByStr(aType));
968
969     std::shared_ptr<Model_Document> aDoc =
970       std::dynamic_pointer_cast<Model_Document>(owner()->document());
971     // check this is Part-name: 2 delimiters in the name
972     std::size_t aPartEnd = aSubShapeName.find('/');
973     if (aPartEnd != std::string::npos) {
974       std::string aPartName = aSubShapeName.substr(0, aPartEnd);
975       DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
976       if (aPartName == aRootDoc->kind()) {
977         aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
978         aSubShapeName = aSubShapeName.substr(aPartEnd + 1);
979       } else {
980         ObjectPtr aFound =
981           owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
982         if (aFound.get()) { // found such part, so asking it for the name
983           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
984           aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
985           aSubShapeName = aSubShapeName.substr(aPartEnd +1);
986           if (aSubShapeName.empty()) { // the whole Part result
987             setValue(aPart, anEmptyShape);
988             return;
989           }
990         }
991       }
992     }
993
994     // check this is a whole feature context
995     if (aSubShapeName.size() > kWHOLE_FEATURE.size() &&
996       aSubShapeName.substr(0, kWHOLE_FEATURE.size()) == kWHOLE_FEATURE) {
997       std::string aFeatureName = aSubShapeName.substr(kWHOLE_FEATURE.size());
998       ObjectPtr anObj = aDoc->objectByName(ModelAPI_Feature::group(), aFeatureName);
999       if (anObj.get()) {
1000         setValue(anObj, anEmptyShape);
1001         return;
1002       }
1003     }
1004
1005     // the whole result selection check
1006     if (aSubShapeName.find('/') == std::string::npos) {
1007       ObjectPtr aRes = aDoc->objectByName(ModelAPI_ResultConstruction::group(), aSubShapeName);
1008       if (!aRes.get())
1009         aRes = aDoc->objectByName(ModelAPI_ResultBody::group(), aSubShapeName);
1010       if (aRes.get()) {
1011         setValue(aRes, anEmptyShape);
1012         return;
1013       }
1014     }
1015
1016     Selector_Selector aSelector(aDoc->generalLabel());
1017     myRestoreDocument = aDoc;
1018     TDF_Label aContextLabel = aSelector.restoreByName(aSubShapeName, aShapeType, this);
1019     myRestoreDocument.reset();
1020     if (!aContextLabel.IsNull()) {
1021       ResultPtr aContext = aDoc->resultByLab(aContextLabel); // any label for document access
1022       if (aContext.get() && aContext->shape().get()) {
1023         TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
1024         if (aSelector.solve(aContextShape)) {
1025           GeomShapePtr aShapeToBeSelected(new GeomAPI_Shape);
1026           aShapeToBeSelected->setImpl<TopoDS_Shape>(new TopoDS_Shape(aSelector.value()));
1027           if (aCenterType != NOT_CENTER) {
1028             if (!aShapeToBeSelected->isEdge())
1029               continue;
1030             std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aShapeToBeSelected));
1031             setValueCenter(aContext, aSelectedEdge, aCenterType);
1032           }
1033           else
1034             setValue(aContext, aShapeToBeSelected);
1035           return;
1036         }
1037       }
1038     }
1039   }
1040   // invalid
1041   TDF_Label aSelLab = selectionLabel();
1042   setInvalidIfFalse(aSelLab, false);
1043   reset();
1044 }
1045
1046 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1047                                               const GeomPointPtr& thePoint)
1048 {
1049   if (theType.empty() || !thePoint)
1050     return;
1051
1052   // list of parent features
1053   FeaturePtr anOwner = ModelAPI_Feature::feature(owner());
1054   std::set<FeaturePtr> aParents = ModelAPI_Tools::getParents(anOwner);
1055
1056   int aSelectionIndex = 0;
1057   GeomAPI_Shape::ShapeType aType = GeomAPI_Shape::shapeTypeByStr(theType);
1058   if (aType == GeomAPI_Shape::SHAPE) {
1059     // possibly, the string consists of the type and the index,
1060     // thus, try to separate them
1061     size_t aUndersporePos = theType.find_first_of('_');
1062     if (aUndersporePos != std::string::npos)
1063       aType = GeomAPI_Shape::shapeTypeByStr(theType.substr(0, aUndersporePos));
1064
1065     if (aType != GeomAPI_Shape::SHAPE) {
1066       for (std::string::const_iterator aChar = theType.begin() + aUndersporePos + 1;
1067            aChar != theType.end(); ++aChar) {
1068         if (std::isdigit(*aChar))
1069           aSelectionIndex = aSelectionIndex * 10 + (*aChar - '0');
1070         else {
1071           aSelectionIndex = 1;
1072           break;
1073         }
1074       }
1075       aSelectionIndex -= 1;
1076     }
1077   }
1078
1079   std::list<ModelGeomAlgo_Shape::SubshapeOfResult> anAppropriate;
1080
1081   // collect features from PartSet and the current part
1082   SessionPtr aSession = ModelAPI_Session::get();
1083   std::list<FeaturePtr> aFeatures = aSession->moduleDocument()->allFeatures();
1084   if (aSession->moduleDocument() != owner()->document()) {
1085     std::list<FeaturePtr> aPartFeatures = owner()->document()->allFeatures();
1086     aFeatures.insert(aFeatures.end(), aPartFeatures.begin(), aPartFeatures.end());
1087   }
1088   // Process results of all features from the last to the first
1089   // to find appropriate sub-shape
1090   for (std::list<FeaturePtr>::const_reverse_iterator anIt = aFeatures.rbegin();
1091        anIt != aFeatures.rend(); ++anIt) {
1092     // selection cannot be linked to the parent features
1093     if (aParents.find(*anIt) != aParents.end())
1094       continue;
1095     // check the feature is a part of composite feature (like sketch elements),
1096     // then do not process it, it will be processed in scope of composite feature
1097     bool isSubOfComposite = false;
1098     const std::set<AttributePtr>& aRefs = (*anIt)->data()->refsToMe();
1099     for (std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
1100          aRefIt != aRefs.end() && !isSubOfComposite; ++aRefIt) {
1101       FeaturePtr aFeature = ModelAPI_Feature::feature((*aRefIt)->owner());
1102       CompositeFeaturePtr aCompFeature =
1103           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
1104       isSubOfComposite = aCompFeature && aCompFeature->isSub(*anIt);
1105     }
1106     if (isSubOfComposite)
1107       continue;
1108
1109     // process results of the current feature to find appropriate sub-shape
1110     if (ModelGeomAlgo_Shape::findSubshapeByPoint(*anIt, thePoint, aType, anAppropriate)) {
1111       std::list<ModelGeomAlgo_Shape::SubshapeOfResult>::iterator anApIt = anAppropriate.begin();
1112       for (; aSelectionIndex > 0 && anApIt != anAppropriate.end(); --aSelectionIndex)
1113         ++anApIt; // skip this shape, because one of the previous is selected
1114
1115       if (anApIt != anAppropriate.end()) {
1116         if (anApIt->myCenterType == (int)ModelAPI_AttributeSelection::NOT_CENTER)
1117           setValue(anApIt->myResult, anApIt->mySubshape);
1118         else
1119           setValueCenter(anApIt->myResult, anApIt->mySubshape->edge(),
1120                          (ModelAPI_AttributeSelection::CenterType)anApIt->myCenterType);
1121         return;
1122       }
1123     }
1124   }
1125
1126   TDF_Label aSelLab = selectionLabel();
1127   setInvalidIfFalse(aSelLab, false);
1128   reset();
1129 }
1130
1131 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1132   const std::string& theContextName, const int theIndex)
1133 {
1134   // selection of context by name
1135   //std::string aNamingContextName = theContextName + "/";
1136   //selectSubShape(theType, aNamingContextName);
1137   std::shared_ptr<Model_Document> aDoc =
1138     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1139   if (aDoc.get()) {
1140     bool aUnique = true;
1141     std::string aContextName = theContextName;
1142     std::string anEmptySub = "";
1143     ResultPtr aContext = aDoc->findByName(aContextName, anEmptySub, aUnique);
1144     //ResultPtr aContext = context();
1145     if (aContext.get()) {
1146       GeomShapePtr aContShape = aContext->shape();
1147       if (aContShape.get()) {
1148         GeomAlgoAPI_NExplode aNExp(aContShape, GeomAPI_Shape::shapeTypeByStr(theType));
1149         GeomShapePtr aValue = aNExp.shape(theIndex);
1150         if (aValue.get())
1151           setValue(aContext, aValue);
1152       }
1153     }
1154   }
1155 }
1156
1157 int Model_AttributeSelection::Id()
1158 {
1159   int anID = 0;
1160   std::shared_ptr<GeomAPI_Shape> aSelection = value();
1161   ResultPtr aContextRes = context();
1162   // support for compsolids:
1163   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1164     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1165   }
1166   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1167
1168
1169   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1170   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1171   // searching for the latest main shape
1172   if (aSelection && !aSelection->isNull() && aContext && !aContext->isNull())
1173   {
1174     std::shared_ptr<Model_Document> aDoc =
1175       std::dynamic_pointer_cast<Model_Document>(context()->document());
1176     if (aDoc.get()) {
1177       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1178       if (!aNS.IsNull()) {
1179         aMainShape = TNaming_Tool::CurrentShape(aNS);
1180       }
1181     }
1182
1183     TopTools_IndexedMapOfShape aSubShapesMap;
1184     TopExp::MapShapes(aMainShape, aSubShapesMap);
1185     anID = aSubShapesMap.FindIndex(aSubShape);
1186   }
1187   return anID;
1188 }
1189
1190 void Model_AttributeSelection::setId(int theID)
1191 {
1192   std::shared_ptr<GeomAPI_Shape> aSelection;
1193
1194   ResultPtr aContextRes = context();
1195   // support for compsolids:
1196   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1197     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1198   }
1199   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1200
1201   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1202   // searching for the latest main shape
1203   if (theID > 0 && aContext && !aContext->isNull())
1204   {
1205     std::shared_ptr<Model_Document> aDoc =
1206       std::dynamic_pointer_cast<Model_Document>(aContextRes->document());
1207     if (aDoc.get()) {
1208       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1209       if (!aNS.IsNull()) {
1210         aMainShape = TNaming_Tool::CurrentShape(aNS);
1211       }
1212     }
1213
1214     TopTools_IndexedMapOfShape aSubShapesMap;
1215     TopExp::MapShapes(aMainShape, aSubShapesMap);
1216     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1217
1218     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1219     aResult->setImpl(new TopoDS_Shape(aSelShape));
1220
1221     aSelection = aResult;
1222   }
1223
1224   setValue(aContextRes, aSelection);
1225 }
1226
1227 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1228 {
1229   std::string aResult;
1230   if (owner()->document() != theContext->document()) {
1231     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1232       aResult = theContext->document()->kind() + "/";
1233     } else {
1234       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1235         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1236       if (aDocRes.get()) {
1237         aResult = aDocRes->data()->name() + "/";
1238       }
1239     }
1240   }
1241   aResult += theContext->data()->name();
1242   return aResult;
1243 }
1244
1245 void Model_AttributeSelection::computeValues(
1246   ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
1247   TopTools_ListOfShape& theShapes)
1248 {
1249   bool aWasWholeContext = theValShape.IsNull();
1250   if (aWasWholeContext) {
1251     //theShapes.Append(theValShape);
1252     //return;
1253     theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
1254   }
1255   //TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
1256   TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
1257   //if (anOldContShape.IsSame(theValShape)) { // full context shape substituted by new full context
1258     //theShapes.Append(aNewContShape);
1259     //return;
1260   //}
1261   // if a new value is unchanged in the new context, do nothing: value is correct
1262   TopExp_Explorer aSubExp(aNewContShape, theValShape.ShapeType());
1263   for(; aSubExp.More(); aSubExp.Next()) {
1264     if (aSubExp.Current().IsSame(theValShape)) {
1265       theShapes.Append(theValShape);
1266       return;
1267     }
1268   }
1269   // if new context becomes compsolid, the resulting sub may be in sub-solids
1270   std::list<ResultPtr> aNewToIterate;
1271   aNewToIterate.push_back(theNewContext);
1272   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theNewContext);
1273   if (aComp.get()) {
1274     std::list<ResultPtr> allNewContextSubs;
1275     ModelAPI_Tools::allSubs(aComp, allNewContextSubs);
1276     std::list<ResultPtr>::iterator aSub = allNewContextSubs.begin();
1277     for(; aSub != allNewContextSubs.end(); aSub++) {
1278       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aSub);
1279       if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1280         aNewToIterate.push_back(aBody);
1281     }
1282   }
1283
1284   // first iteration: searching for the whole shape appearance (like face of the box)
1285   // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
1286   int aToFindPart = 0;
1287   TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
1288   TopTools_MapOfShape anOlds; // to know how many olds produced new containers
1289   for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
1290     std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
1291     for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
1292       std::shared_ptr<Model_Data> aNewData =
1293         std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
1294       TDF_Label aNewLab = aNewData->shapeLab();
1295       // searching for produced sub-shape fully on some label
1296       TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID(), Standard_True);
1297       for(; aNSIter.More(); aNSIter.Next()) {
1298         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1299         for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
1300           if (aToFindPart == 0) { // search shape is fully inside
1301             if (aPairIter.OldShape().IsSame(theValShape)) {
1302               if (aPairIter.NewShape().IsNull()) {// value was removed
1303                 theShapes.Clear();
1304                 return;
1305               }
1306               theShapes.Append(aPairIter.NewShape());
1307             }
1308           } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
1309             TopExp_Explorer anExp(aPairIter.OldShape(), theValShape.ShapeType());
1310             for(; anExp.More(); anExp.Next()) {
1311               if (anExp.Current().IsSame(theValShape)) { // found a new container
1312                 if (aPairIter.NewShape().IsNull()) {// value was removed
1313                   theShapes.Clear();
1314                   return;
1315                 }
1316                 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
1317                 anOlds.Add(aPairIter.OldShape());
1318                 break;
1319               }
1320             }
1321           }
1322         }
1323       }
1324     }
1325   }
1326   if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
1327     // map of sub-shapes -> number of occurences of these shapes in containers
1328     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
1329     TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
1330     for(; aContIter.More(); aContIter.Next()) {
1331       TopExp_Explorer aSubExp(aContIter.Key(), theValShape.ShapeType());
1332       for(; aSubExp.More(); aSubExp.Next()) {
1333         if (!aSubs.IsBound(aSubExp.Current())) {
1334           aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
1335         }
1336         // store old to know how many olds produced this shape
1337         aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
1338       }
1339     }
1340     // if sub is appeared same times in containers as the number of old shapes that contain it
1341     int aCountInOld = anOlds.Size();
1342     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
1343       aSubsIter(aSubs);
1344     for(; aSubsIter.More(); aSubsIter.Next()) {
1345       if (aSubsIter.Value().Size() == aCountInOld) {
1346         theShapes.Append(aSubsIter.Key());
1347       }
1348     }
1349   }
1350   if (theShapes.IsEmpty()) { // nothing was changed
1351     theShapes.Append(aWasWholeContext ? TopoDS_Shape() : theValShape);
1352   }
1353 }
1354
1355 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
1356   const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
1357   TDF_Label theAccessLabel,
1358   std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
1359 {
1360   std::set<ResultPtr> aResults; // to avoid duplicates, new context, null if deleted
1361   TopTools_ListOfShape aResContShapes;
1362   // iterate context and shape, but also if it is sub-shape of main shape, check also it
1363   TopTools_ListOfShape aContextList;
1364   aContextList.Append(theContShape);
1365   if (theContext.get()) {
1366     ResultPtr aComposite = ModelAPI_Tools::bodyOwner(theContext);
1367     if (aComposite.get() && aComposite->shape().get() && !aComposite->shape()->isNull())
1368       aContextList.Append(aComposite->shape()->impl<TopoDS_Shape>());
1369   }
1370   for(TopTools_ListOfShape::Iterator aContIter(aContextList); aContIter.More(); aContIter.Next()) {
1371     TNaming_SameShapeIterator aModifIter(aContIter.ChangeValue(), theAccessLabel);
1372     for(; aModifIter.More(); aModifIter.Next()) {
1373       TDF_Label anObjLab = aModifIter.Label().Father();
1374       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1375         (theDoc->objects()->object(anObjLab));
1376       if (!aModifierObj.get()) {
1377         // #2241: shape may be sub-element of new object, not main (shell created from faces)
1378         if (!anObjLab.IsRoot())
1379           aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1380           (theDoc->objects()->object(anObjLab.Father()));
1381         if (!aModifierObj.get())
1382           continue;
1383       }
1384       FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
1385       if (!aModifierFeat.get())
1386         continue;
1387       FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1388       if (aModifierFeat == aThisFeature || !theDoc->isLaterByDep(aThisFeature, aModifierFeat))
1389         continue; // the modifier feature is later than this, so, should not be used
1390       FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
1391       if (aCurrentModifierFeat == aModifierFeat ||
1392         !theDoc->isLaterByDep(aModifierFeat, aCurrentModifierFeat))
1393         continue; // the current modifier is later than the found, so, useless
1394       Handle(TNaming_NamedShape) aNewNS;
1395       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1396       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1397         aResults.insert(aModifierObj);
1398         //TNaming_Iterator aPairIter(aNewNS);
1399         //aResContShapes.Append(aPairIter.NewShape());
1400         aResContShapes.Append(aModifierObj->shape()->impl<TopoDS_Shape>());
1401       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
1402         aResults.insert(ResultPtr());
1403       } else { // not-processed modification => don't support it
1404         continue;
1405       }
1406     }
1407   }
1408   if (aResults.empty())
1409     return false; // no modifications found, must stay the same
1410   // iterate all results to find futher modifications
1411   std::set<ResultPtr>::iterator aResIter = aResults.begin();
1412   for(; aResIter != aResults.end(); aResIter++) {
1413     if (aResIter->get() != NULL) {
1414       // compute new values by two contextes: the old and the new
1415       TopTools_ListOfShape aValShapes;
1416       computeValues(theContext, *aResIter, theValShape, aValShapes);
1417
1418       TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
1419       for(; aNewVal.More(); aNewVal.Next()) {
1420         std::list<ResultPtr> aNewRes;
1421         TopTools_ListOfShape aNewUpdatedVal;
1422         TopoDS_Shape aNewValSh = aNewVal.Value();
1423         TopoDS_Shape aNewContShape = (*aResIter)->shape()->impl<TopoDS_Shape>();
1424         if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
1425           aNewValSh.Nullify();
1426         if (searchNewContext(theDoc, aNewContShape, *aResIter, aNewValSh,
1427                              theAccessLabel, aNewRes, aNewUpdatedVal))
1428         {
1429           // appeand new results instead of the current ones
1430           std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1431           TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1432           for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1433             theResults.push_back(*aNewIter);
1434             theValShapes.Append(aNewUpdVal.Value());
1435           }
1436         } else { // the current result is good
1437           theResults.push_back(*aResIter);
1438           theValShapes.Append(aNewValSh);
1439         }
1440       }
1441     }
1442   }
1443   return true; // theResults must be empty: everything is deleted
1444 }
1445
1446 void Model_AttributeSelection::updateInHistory()
1447 {
1448   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1449   // only bodies and parts may be modified later in the history, don't do anything otherwise
1450   if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
1451       aContext->groupName() != ModelAPI_ResultPart::group()))
1452     return;
1453   std::shared_ptr<Model_Document> aDoc =
1454     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1455   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1456   if (!aContData.get() || !aContData->isValid())
1457     return;
1458   TDF_Label aContLab = aContData->shapeLab(); // named shape where the selected context is located
1459   Handle(TNaming_NamedShape) aContNS;
1460   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
1461     bool aFoundNewContext = true;
1462     ResultPtr aNewContext = aContext;
1463     while(aFoundNewContext) {
1464       aFoundNewContext = false;
1465       // parts have no shape in result, so, trace references using the Part info
1466       if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
1467         ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
1468         if (aPartContext.get()) { // searching for the up to date references to the referenced cont
1469           const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
1470           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1471           for(; aRef != aRefs.end(); aRef++) {
1472             // to avoid detection of part changes by local selection only
1473             AttributeSelectionPtr aSel =
1474               std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1475             if (aSel.get() && aSel->value().get() &&
1476                 !aSel->value()->isSame(aSel->context()->shape()))
1477               continue;
1478
1479             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1480             if (aRefFeat.get() && aRefFeat != owner()) {
1481               FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1482               if (!aDoc->isLaterByDep(aRefFeat, aThisFeature)) { // found better feature
1483                 aFoundNewContext = true;
1484                 aNewContext = aRefFeat->firstResult();
1485               }
1486             }
1487           }
1488         }
1489       }
1490     }
1491     if (aNewContext != aContext) {
1492       setValue(aNewContext, value());
1493     }
1494     return;
1495   }
1496   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1497   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1498   // iterate the context shape modifications in order to find a feature that is upper in history
1499   // that this one and is really modifies the referenced result to refer to it
1500   ResultPtr aModifierResFound;
1501   TNaming_Iterator aPairIter(aContNS);
1502   if (!aPairIter.More())
1503     return;
1504   TopoDS_Shape aNewCShape = aPairIter.NewShape();
1505   bool anIterate = true;
1506   // trying to update also the sub-shape selected
1507   GeomShapePtr aSubShape = value();
1508   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1509     aSubShape.reset();
1510   TopoDS_Shape aValShape;
1511   if (aSubShape.get()) {
1512     aValShape = aSubShape->impl<TopoDS_Shape>();
1513   }
1514
1515   std::list<ResultPtr> aNewContexts;
1516   TopTools_ListOfShape aValShapes;
1517   if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1518   {
1519     std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1520     TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1521     if (aNewCont == aNewContexts.end()) { // all results were deleted
1522       ResultPtr anEmptyContext;
1523       std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1524       setValue(anEmptyContext, anEmptyShape); // nullify the selection
1525       return;
1526     }
1527
1528     GeomShapePtr aValueShape;
1529     if (!aNewValues.Value().IsNull()) {
1530       aValueShape = std::make_shared<GeomAPI_Shape>();
1531       aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1532     }
1533     setValue(*aNewCont, aValueShape);
1534     // if there are more than one result, put them by "append" into "parent" list
1535     if (myParent) {
1536       for(aNewCont++, aNewValues.Next(); aNewCont != aNewContexts.end();
1537           aNewCont++, aNewValues.Next()) {
1538         GeomShapePtr aValueShape;
1539         if (!aNewValues.Value().IsNull()) {
1540           aValueShape = std::make_shared<GeomAPI_Shape>();
1541           aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1542         }
1543
1544         // Check that list has the same type of shape selection before adding.
1545         GeomAPI_Shape::ShapeType aListShapeType = GeomAPI_Shape::SHAPE;
1546         if (myParent->selectionType() == "VERTEX") aListShapeType = GeomAPI_Shape::VERTEX;
1547         else if (myParent->selectionType() == "EDGE") aListShapeType = GeomAPI_Shape::EDGE;
1548         else if (myParent->selectionType() == "FACE") aListShapeType = GeomAPI_Shape::FACE;
1549
1550         GeomAPI_Shape::ShapeType aShapeShapeType = GeomAPI_Shape::SHAPE;
1551         if (aValueShape.get()) {
1552           aShapeShapeType = aValueShape->shapeType();
1553         } else {
1554           (*aNewCont)->shape()->shapeType();
1555         }
1556
1557         if (aListShapeType != GeomAPI_Shape::SHAPE && aListShapeType != aShapeShapeType) {
1558           continue;
1559         }
1560
1561         myParent->append(*aNewCont, aValueShape);
1562       }
1563     }
1564   }
1565 }
1566
1567 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1568 {
1569   myParent = theParent;
1570 }
1571
1572 std::string Model_AttributeSelection::contextName(const TDF_Label theSelectionLab)
1573 {
1574   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1575     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1576   FeaturePtr aFeatureOwner = aDoc->featureByLab(theSelectionLab);
1577   if (aFeatureOwner.get()) {
1578     // if it is sub-element of the sketch, the context name is the name of the sketch
1579     // searching also for result - real context
1580     ResultPtr aResult;
1581     FeaturePtr aComposite = ModelAPI_Tools::compositeOwner(aFeatureOwner);
1582     if (aComposite.get() && aComposite->results().size() == 1 &&
1583         aComposite->firstResult()->groupName() == ModelAPI_ResultConstruction::group()) {
1584       aFeatureOwner = aComposite;
1585       aResult = aFeatureOwner->firstResult();
1586     } else {
1587       aResult = aDoc->resultByLab(theSelectionLab);
1588     }
1589     if (aResult.get()) {
1590       // this is to avoid duplicated names of results problem
1591       std::string aContextName = aResult->data()->name();
1592       // myLab corresponds to the current time
1593       TDF_Label aCurrentLab = selectionLabel();
1594       while(aCurrentLab.Depth() > 3)
1595         aCurrentLab = aCurrentLab.Father();
1596
1597       int aNumInHistoryNames =
1598         aDoc->numberOfNameInHistory(aResult, aCurrentLab);
1599       while(aNumInHistoryNames > 1) { // add "_" before name the needed number of times
1600         aContextName = "_" + aContextName;
1601         aNumInHistoryNames--;
1602       }
1603       return aContextName;
1604     }
1605   }
1606   return ""; // invalid case
1607 }
1608
1609 /// This method restores by the context and value name the context label and
1610 /// sub-label where the value is. Returns true if it is valid.
1611 bool Model_AttributeSelection::restoreContext(std::string theName,
1612   TDF_Label& theContext, TDF_Label& theValue)
1613 {
1614   static const GeomShapePtr anEmptyShape; // to store context only
1615   std::string aName = theName;
1616   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1617     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1618
1619   // remove the sub-value part if exists
1620   std::string aSubShapeName = aName;
1621   std::string::size_type n = aName.find('/');
1622   if (n != std::string::npos) {
1623     aName = aName.substr(0, n);
1624   }
1625
1626   if (aName.empty()) return false;
1627   bool anUniqueContext = false;
1628   ResultPtr aCont = aDoc->findByName(aName, aSubShapeName, anUniqueContext);
1629   if (!aCont.get() || !aCont->shape().get() || aCont->shape()->isNull())
1630     return false;
1631
1632   // searching the sub-shape
1633   static const ResultPtr anEmpty;
1634   theValue = aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
1635
1636   // sketch sub-component shape and name is located in separated feature label, try the sub-name
1637   if (theValue.IsNull() && aCont->groupName() == ModelAPI_ResultConstruction::group()) {
1638     std::string::size_type aSlash = aSubShapeName.rfind('/');
1639     if (aSlash != std::string::npos) {
1640       std::string aCompName = aSubShapeName.substr(aSlash + 1);
1641       CompositeFeaturePtr aComposite =
1642         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aCont));
1643       if (aComposite.get() && aComposite->numberOfSubs()) {
1644         const int aSubNum = aComposite->numberOfSubs();
1645         for (int a = 0; a < aSubNum && theValue.IsNull(); a++) {
1646           FeaturePtr aSub = aComposite->subFeature(a);
1647           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
1648           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
1649           for (; aRes != aResults.cend() && theValue.IsNull(); aRes++) {
1650             if ((*aRes)->data()->name() == aCompName) {
1651               theValue = std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->shapeLab();
1652               break;
1653             } else if (aCompName.find((*aRes)->data()->name()) != std::string::npos) {// sub-vertex
1654               TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->shapeLab();
1655               TDF_ChildIDIterator aSubNames(aLab, TDataStd_Name::GetID());
1656               for(; aSubNames.More(); aSubNames.Next()) {
1657                 if (Handle(TDataStd_Name)::DownCast(aSubNames.Value())->Get().
1658                   IsEqual(aCompName.c_str())) {
1659                   theValue = aSubNames.Value()->Label();
1660                   break;
1661                 }
1662               }
1663             }
1664           }
1665         }
1666       }
1667     }
1668   }
1669
1670   /* to find the latest lower result that keeps given shape
1671   bool aFindNewContext = true;
1672   while(aFindNewContext && aCont.get()) {
1673     aFindNewContext = false;
1674     // try to find the last context to find the up to date shape
1675     TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
1676     Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
1677     if (!aNS.IsNull()) {
1678       aNS = TNaming_Tool::CurrentNamedShape(aNS);
1679       if (!aNS.IsNull() && isOlderThanMe(aNS->Label())) { // scope check is for 2228
1680         TDF_Label aLab = aNS->Label();
1681         if (aLab.Depth() % 2 == 0)
1682           aLab = aLab.Father();
1683         ObjectPtr anObj = aDoc->objects()->object(aLab);
1684         while (!anObj.get() && aLab.Depth() > 5) {
1685           aLab = aLab.Father().Father();
1686           anObj = aDoc->objects()->object(aLab);
1687         }
1688
1689         if (anObj.get()) {
1690           ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1691           if (aRes) {
1692             aCont = aRes;
1693             aFindNewContext = true;
1694           }
1695         }
1696       }
1697     } else if (aCont->groupName() == ModelAPI_ResultBody::group()) {
1698       // try to search newer context by the concealment references
1699       // take references to all results: root one, any sub
1700       std::list<ResultPtr> allRes;
1701       ResultPtr aCompContext;
1702       if (aCont->groupName() == ModelAPI_ResultBody::group()) {
1703         ResultBodyPtr aCompBody = ModelAPI_Tools::bodyOwner(aCont, true);
1704         if (aCompBody.get()) {
1705           ModelAPI_Tools::allSubs(aCompBody, allRes);
1706           allRes.push_back(aCompBody);
1707           aCompContext = aCompBody;
1708         }
1709       }
1710       if (allRes.empty())
1711         allRes.push_back(aCont);
1712
1713       for(std::list<ResultPtr>::iterator aSub = allRes.begin(); aSub != allRes.end(); aSub++) {
1714         ResultPtr aResCont = *aSub;
1715         ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResCont);
1716         if (aResBody.get() && aResBody->numberOfSubs() > 0 && aResBody != aCompContext)
1717           continue; // only lower and higher level subs are counted
1718         const std::set<AttributePtr>& aRefs = aResCont->data()->refsToMe();
1719         std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1720         for(; !aFindNewContext && aRef != aRefs.end(); aRef++) {
1721           if (!aRef->get() || !(*aRef)->owner().get())
1722             continue;
1723           // concealed attribute only
1724           FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1725           if (!ModelAPI_Session::get()->validators()->isConcealed(
1726             aRefFeat->getKind(), (*aRef)->id()))
1727             continue;
1728           // search the feature result that contains sub-shape selected
1729           std::list<std::shared_ptr<ModelAPI_Result> > aResults;
1730
1731           // take all sub-results or one result
1732           std::list<ResultPtr> aRefFeatResults;
1733           ModelAPI_Tools::allResults(aRefFeat, aRefFeatResults);
1734           std::list<ResultPtr>::iterator aRefResIter = aRefFeatResults.begin();
1735           for(; aRefResIter != aRefFeatResults.end(); aRefResIter++) {
1736             ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRefResIter);
1737             if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1738               aResults.push_back(aBody);
1739           }
1740           std::list<std::shared_ptr<ModelAPI_Result> >::iterator aResIter = aResults.begin();
1741           for(; aResIter != aResults.end(); aResIter++) {
1742             if (!aResIter->get() || !(*aResIter)->data()->isValid() || (*aResIter)->isDisabled())
1743               continue;
1744             GeomShapePtr aShape = (*aResIter)->shape();
1745             GeomShapePtr aSelectedShape =
1746               aShapeToBeSelected.get() ? aShapeToBeSelected : aCont->shape();
1747             if (aShape.get() && aShape->isSubShape(aSelectedShape, false)) {
1748               aCont = *aResIter; // found new context (produced from this) with same subshape
1749               aFindNewContext = true; // continue searching futher
1750               break;
1751             }
1752           }
1753         }
1754       }
1755     }
1756   }
1757   // if compsolid is context, try to take sub-solid as context: like in GUI and scripts
1758   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aCont);
1759   if (aComp && aComp->numberOfSubs()) {
1760     std::list<ResultPtr> allSubs;
1761     ModelAPI_Tools::allSubs(aComp, allSubs);
1762     std::list<ResultPtr>::iterator aS = allSubs.begin();
1763     for (; aS != allSubs.end(); aS++) {
1764       ResultBodyPtr aSub = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aS);
1765       if (aSub && aSub->numberOfSubs() == 0 && aSub->shape().get() &&
1766         aSub->shape()->isSubShape(aShapeToBeSelected)) {
1767         aCont = aSub;
1768         break;
1769       }
1770     }
1771   }
1772   */
1773   if (aCont.get()) {
1774     theContext = std::dynamic_pointer_cast<Model_Data>(aCont->data())->label();
1775   }
1776   return true;
1777 }
1778
1779 bool Model_AttributeSelection::isLater(
1780   const TDF_Label theResult1, const TDF_Label theResult2) const
1781 {
1782   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1783     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1784   FeaturePtr aFeat1 = aDoc->featureByLab(theResult1);
1785   if (!aFeat1.get())
1786     return false;
1787   FeaturePtr aFeat2 = aDoc->featureByLab(theResult2);
1788   if (!aFeat2.get())
1789     return false;
1790   return aDoc->isLaterByDep(aFeat1, aFeat2);
1791 }