Salome HOME
Remove compilation errors and warnings
[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   // whole infinitive construction
880   if (aCont->groupName() == ModelAPI_ResultConstruction::group()) {
881     ResultConstructionPtr aConstr = std::dynamic_pointer_cast<Model_ResultConstruction>(aCont);
882     if (aConstr->isInfinite()) {
883       return contextName(aCont);
884     } else {
885       // external sketch face
886       Handle(TDataStd_Integer) anIndex;
887       if (aSelLab.FindAttribute(kEXT_SKETCH_FACE, anIndex) ||
888           aSelLab.FindAttribute(kEXT_SKETCH_EDGE, anIndex) ||
889           aSelLab.FindAttribute(kEXT_SKETCH_VERT, anIndex)) {
890         std::shared_ptr<Model_Document> anExtDoc =
891           std::dynamic_pointer_cast<Model_Document>(aCont->document());
892         Selector_Selector aSelector(anExtDoc->extConstructionsLabel());
893         TopoDS_Shape aContShape = aConstr->shape()->impl<TopoDS_Shape>();
894         TopoDS_Shape aValShape = value()->impl<TopoDS_Shape>();
895         aSelector.select(aContShape, aValShape);
896         myRestoreDocument = anExtDoc;
897         std::string aName = anExtDoc->kind() + "/" + aSelector.name(this);
898         myRestoreDocument.reset();
899         return aName;
900       }
901     }
902   }
903
904   Selector_Selector aSelector(aSelLab);
905   std::string aResult;
906   if (aSelector.restore())
907     aResult = aSelector.name(this);
908   /*
909   Model_SelectionNaming aSelNaming(aSelLab);
910   std::string aResult = aSelNaming.namingName(
911     aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
912     */
913   if (aCenterType != NOT_CENTER) {
914     aResult += centersMap()[aCenterType];
915   }
916   return aResult;
917 }
918
919 // returns the center type and modifies the shape name if this name is center-name
920 static ModelAPI_AttributeSelection::CenterType centerTypeByName(std::string& theShapeName)
921 {
922   std::map<ModelAPI_AttributeSelection::CenterType, std::string>::iterator aPrefixIter =
923     centersMap().begin();
924   for(; aPrefixIter != centersMap().end(); aPrefixIter++) {
925     std::size_t aFound = theShapeName.find(aPrefixIter->second);
926     if (aFound != std::string::npos &&
927         aFound == theShapeName.size() - aPrefixIter->second.size()) {
928       theShapeName = theShapeName.substr(0, aFound);
929       return aPrefixIter->first;
930     }
931   }
932   return ModelAPI_AttributeSelection::NOT_CENTER;
933 }
934
935 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
936 void Model_AttributeSelection::selectSubShape(
937   const std::string& theType, const std::string& theSubShapeName)
938 {
939   if(theSubShapeName.empty() || theType.empty()) return;
940
941   std::string aSubShapeName = theSubShapeName;
942   CenterType aCenterType = theType[0] == 'v' || theType[0] == 'V' ? // only for vertex-type
943     centerTypeByName(aSubShapeName) : NOT_CENTER;
944   std::string aType = aCenterType == NOT_CENTER ? theType : "EDGE"; // search for edge now
945   TopAbs_ShapeEnum aShapeType =  TopAbs_ShapeEnum(GeomAPI_Shape::shapeTypeByStr(theType));
946   static const GeomShapePtr anEmptyShape;
947
948   // first iteration is selection by name without center prefix, second - in case of problem,
949   // try with initial name
950   for(int aUseCenter = 1; aUseCenter >= 0; aUseCenter--)  {
951     std::string aSubShapeName = theSubShapeName;
952     if (aUseCenter == 0 && aCenterType != NOT_CENTER) {
953       aCenterType = NOT_CENTER;
954       aType = theType;
955     } else if (aUseCenter != 1) continue;
956
957     std::shared_ptr<Model_Document> aDoc =
958       std::dynamic_pointer_cast<Model_Document>(owner()->document());
959     // check this is Part-name: 2 delimiters in the name
960     std::size_t aPartEnd = aSubShapeName.find('/');
961     if (aPartEnd != std::string::npos) {
962       std::string aPartName = aSubShapeName.substr(0, aPartEnd);
963       DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
964       if (aPartName == aRootDoc->kind()) {
965         aDoc = std::dynamic_pointer_cast<Model_Document>(aRootDoc);
966         aSubShapeName = aSubShapeName.substr(aPartEnd + 1);
967       } else {
968         ObjectPtr aFound =
969           owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
970         if (aFound.get()) { // found such part, so asking it for the name
971           ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
972           aDoc = std::dynamic_pointer_cast<Model_Document>(aPart->partDoc());
973           aSubShapeName = aSubShapeName.substr(aPartEnd +1);
974         }
975       }
976     }
977
978     // check this is a whole feature context
979     if (aSubShapeName.size() > kWHOLE_FEATURE.size() &&
980       aSubShapeName.substr(0, kWHOLE_FEATURE.size()) == kWHOLE_FEATURE) {
981       std::string aFeatureName = aSubShapeName.substr(kWHOLE_FEATURE.size());
982       ObjectPtr anObj = aDoc->objectByName(ModelAPI_Feature::group(), aFeatureName);
983       if (anObj.get()) {
984         setValue(anObj, anEmptyShape);
985         return;
986       }
987     }
988
989     // the whole result selection check
990     if (aSubShapeName.find('/') == std::string::npos) {
991       ObjectPtr aRes = aDoc->objectByName(ModelAPI_ResultConstruction::group(), aSubShapeName);
992       if (!aRes.get())
993         aRes = aDoc->objectByName(ModelAPI_ResultBody::group(), aSubShapeName);
994       if (aRes.get()) {
995         setValue(aRes, anEmptyShape);
996         return;
997       }
998     }
999
1000     Selector_Selector aSelector(aDoc->generalLabel());
1001     myRestoreDocument = aDoc;
1002     TDF_Label aContextLabel = aSelector.restoreByName(aSubShapeName, aShapeType, this);
1003     myRestoreDocument.reset();
1004     if (!aContextLabel.IsNull()) {
1005       ResultPtr aContext = aDoc->resultByLab(aContextLabel); // any label for document access
1006       if (aContext.get() && aContext->shape().get()) {
1007         TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
1008         if (aSelector.solve(aContextShape)) {
1009           GeomShapePtr aShapeToBeSelected(new GeomAPI_Shape);
1010           aShapeToBeSelected->setImpl<TopoDS_Shape>(new TopoDS_Shape(aSelector.value()));
1011           if (aCenterType != NOT_CENTER) {
1012             if (!aShapeToBeSelected->isEdge())
1013               continue;
1014             std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aShapeToBeSelected));
1015             setValueCenter(aContext, aSelectedEdge, aCenterType);
1016           }
1017           else
1018             setValue(aContext, aShapeToBeSelected);
1019           return;
1020         }
1021       }
1022     }
1023     aSubShapeName = theSubShapeName;
1024   }
1025   // invalid
1026   TDF_Label aSelLab = selectionLabel();
1027   setInvalidIfFalse(aSelLab, false);
1028   reset();
1029 }
1030
1031 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1032                                               const GeomPointPtr& thePoint)
1033 {
1034   if (theType.empty() || !thePoint)
1035     return;
1036
1037   // list of parent features
1038   FeaturePtr anOwner = ModelAPI_Feature::feature(owner());
1039   std::set<FeaturePtr> aParents = ModelAPI_Tools::getParents(anOwner);
1040
1041   int aSelectionIndex = 0;
1042   GeomAPI_Shape::ShapeType aType = GeomAPI_Shape::shapeTypeByStr(theType);
1043   if (aType == GeomAPI_Shape::SHAPE) {
1044     // possibly, the string consists of the type and the index,
1045     // thus, try to separate them
1046     size_t aUndersporePos = theType.find_first_of('_');
1047     if (aUndersporePos != std::string::npos)
1048       aType = GeomAPI_Shape::shapeTypeByStr(theType.substr(0, aUndersporePos));
1049
1050     if (aType != GeomAPI_Shape::SHAPE) {
1051       for (std::string::const_iterator aChar = theType.begin() + aUndersporePos + 1;
1052            aChar != theType.end(); ++aChar) {
1053         if (std::isdigit(*aChar))
1054           aSelectionIndex = aSelectionIndex * 10 + (*aChar - '0');
1055         else {
1056           aSelectionIndex = 1;
1057           break;
1058         }
1059       }
1060       aSelectionIndex -= 1;
1061     }
1062   }
1063
1064   std::list<ModelGeomAlgo_Shape::SubshapeOfResult> anAppropriate;
1065
1066   // collect features from PartSet and the current part
1067   SessionPtr aSession = ModelAPI_Session::get();
1068   std::list<FeaturePtr> aFeatures = aSession->moduleDocument()->allFeatures();
1069   if (aSession->moduleDocument() != owner()->document()) {
1070     std::list<FeaturePtr> aPartFeatures = owner()->document()->allFeatures();
1071     aFeatures.insert(aFeatures.end(), aPartFeatures.begin(), aPartFeatures.end());
1072   }
1073   // Process results of all features from the last to the first
1074   // to find appropriate sub-shape
1075   for (std::list<FeaturePtr>::const_reverse_iterator anIt = aFeatures.rbegin();
1076        anIt != aFeatures.rend(); ++anIt) {
1077     // selection cannot be linked to the parent features
1078     if (aParents.find(*anIt) != aParents.end())
1079       continue;
1080     // check the feature is a part of composite feature (like sketch elements),
1081     // then do not process it, it will be processed in scope of composite feature
1082     bool isSubOfComposite = false;
1083     const std::set<AttributePtr>& aRefs = (*anIt)->data()->refsToMe();
1084     for (std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
1085          aRefIt != aRefs.end() && !isSubOfComposite; ++aRefIt) {
1086       FeaturePtr aFeature = ModelAPI_Feature::feature((*aRefIt)->owner());
1087       CompositeFeaturePtr aCompFeature =
1088           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
1089       isSubOfComposite = aCompFeature && aCompFeature->isSub(*anIt);
1090     }
1091     if (isSubOfComposite)
1092       continue;
1093
1094     // process results of the current feature to find appropriate sub-shape
1095     if (ModelGeomAlgo_Shape::findSubshapeByPoint(*anIt, thePoint, aType, anAppropriate)) {
1096       std::list<ModelGeomAlgo_Shape::SubshapeOfResult>::iterator anApIt = anAppropriate.begin();
1097       for (; aSelectionIndex > 0 && anApIt != anAppropriate.end(); --aSelectionIndex)
1098         ++anApIt; // skip this shape, because one of the previous is selected
1099
1100       if (anApIt != anAppropriate.end()) {
1101         if (anApIt->myCenterType == (int)ModelAPI_AttributeSelection::NOT_CENTER)
1102           setValue(anApIt->myResult, anApIt->mySubshape);
1103         else
1104           setValueCenter(anApIt->myResult, anApIt->mySubshape->edge(),
1105                          (ModelAPI_AttributeSelection::CenterType)anApIt->myCenterType);
1106         return;
1107       }
1108     }
1109   }
1110
1111   TDF_Label aSelLab = selectionLabel();
1112   setInvalidIfFalse(aSelLab, false);
1113   reset();
1114 }
1115
1116 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1117   const std::string& theContextName, const int theIndex)
1118 {
1119   // selection of context by name
1120   //std::string aNamingContextName = theContextName + "/";
1121   //selectSubShape(theType, aNamingContextName);
1122   std::shared_ptr<Model_Document> aDoc =
1123     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1124   if (aDoc.get()) {
1125     bool aUnique = true;
1126     std::string aContextName = theContextName;
1127     std::string anEmptySub = "";
1128     ResultPtr aContext = aDoc->findByName(aContextName, anEmptySub, aUnique);
1129     //ResultPtr aContext = context();
1130     if (aContext.get()) {
1131       GeomShapePtr aContShape = aContext->shape();
1132       if (aContShape.get()) {
1133         GeomAlgoAPI_NExplode aNExp(aContShape, GeomAPI_Shape::shapeTypeByStr(theType));
1134         GeomShapePtr aValue = aNExp.shape(theIndex);
1135         if (aValue.get())
1136           setValue(aContext, aValue);
1137       }
1138     }
1139   }
1140 }
1141
1142 int Model_AttributeSelection::Id()
1143 {
1144   int anID = 0;
1145   std::shared_ptr<GeomAPI_Shape> aSelection = value();
1146   ResultPtr aContextRes = context();
1147   // support for compsolids:
1148   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1149     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1150   }
1151   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1152
1153
1154   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1155   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
1156   // searching for the latest main shape
1157   if (aSelection && !aSelection->isNull() && aContext && !aContext->isNull())
1158   {
1159     std::shared_ptr<Model_Document> aDoc =
1160       std::dynamic_pointer_cast<Model_Document>(context()->document());
1161     if (aDoc.get()) {
1162       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1163       if (!aNS.IsNull()) {
1164         aMainShape = TNaming_Tool::CurrentShape(aNS);
1165       }
1166     }
1167
1168     TopTools_IndexedMapOfShape aSubShapesMap;
1169     TopExp::MapShapes(aMainShape, aSubShapesMap);
1170     anID = aSubShapesMap.FindIndex(aSubShape);
1171   }
1172   return anID;
1173 }
1174
1175 void Model_AttributeSelection::setId(int theID)
1176 {
1177   std::shared_ptr<GeomAPI_Shape> aSelection;
1178
1179   ResultPtr aContextRes = context();
1180   // support for compsolids:
1181   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1182     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1183   }
1184   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1185
1186   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1187   // searching for the latest main shape
1188   if (theID > 0 && aContext && !aContext->isNull())
1189   {
1190     std::shared_ptr<Model_Document> aDoc =
1191       std::dynamic_pointer_cast<Model_Document>(aContextRes->document());
1192     if (aDoc.get()) {
1193       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1194       if (!aNS.IsNull()) {
1195         aMainShape = TNaming_Tool::CurrentShape(aNS);
1196       }
1197     }
1198
1199     TopTools_IndexedMapOfShape aSubShapesMap;
1200     TopExp::MapShapes(aMainShape, aSubShapesMap);
1201     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1202
1203     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1204     aResult->setImpl(new TopoDS_Shape(aSelShape));
1205
1206     aSelection = aResult;
1207   }
1208
1209   setValue(aContextRes, aSelection);
1210 }
1211
1212 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1213 {
1214   std::string aResult;
1215   if (owner()->document() != theContext->document()) {
1216     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1217       aResult = theContext->document()->kind() + "/";
1218     } else {
1219       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1220         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1221       if (aDocRes.get()) {
1222         aResult = aDocRes->data()->name() + "/";
1223       }
1224     }
1225   }
1226   aResult += theContext->data()->name();
1227   return aResult;
1228 }
1229
1230 void Model_AttributeSelection::computeValues(
1231   ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
1232   TopTools_ListOfShape& theShapes)
1233 {
1234   bool aWasWholeContext = theValShape.IsNull();
1235   if (aWasWholeContext) {
1236     //theShapes.Append(theValShape);
1237     //return;
1238     theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
1239   }
1240   //TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
1241   TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
1242   //if (anOldContShape.IsSame(theValShape)) { // full context shape substituted by new full context
1243     //theShapes.Append(aNewContShape);
1244     //return;
1245   //}
1246   // if a new value is unchanged in the new context, do nothing: value is correct
1247   TopExp_Explorer aSubExp(aNewContShape, theValShape.ShapeType());
1248   for(; aSubExp.More(); aSubExp.Next()) {
1249     if (aSubExp.Current().IsSame(theValShape)) {
1250       theShapes.Append(theValShape);
1251       return;
1252     }
1253   }
1254   // if new context becomes compsolid, the resulting sub may be in sub-solids
1255   std::list<ResultPtr> aNewToIterate;
1256   aNewToIterate.push_back(theNewContext);
1257   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theNewContext);
1258   if (aComp.get()) {
1259     std::list<ResultPtr> allNewContextSubs;
1260     ModelAPI_Tools::allSubs(aComp, allNewContextSubs);
1261     std::list<ResultPtr>::iterator aSub = allNewContextSubs.begin();
1262     for(; aSub != allNewContextSubs.end(); aSub++) {
1263       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aSub);
1264       if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1265         aNewToIterate.push_back(aBody);
1266     }
1267   }
1268
1269   // first iteration: searching for the whole shape appearance (like face of the box)
1270   // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
1271   int aToFindPart = 0;
1272   TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
1273   TopTools_MapOfShape anOlds; // to know how many olds produced new containers
1274   for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
1275     std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
1276     for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
1277       std::shared_ptr<Model_Data> aNewData =
1278         std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
1279       TDF_Label aNewLab = aNewData->shapeLab();
1280       // searching for produced sub-shape fully on some label
1281       TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID(), Standard_True);
1282       for(; aNSIter.More(); aNSIter.Next()) {
1283         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1284         for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
1285           if (aToFindPart == 0) { // search shape is fully inside
1286             if (aPairIter.OldShape().IsSame(theValShape)) {
1287               if (aPairIter.NewShape().IsNull()) {// value was removed
1288                 theShapes.Clear();
1289                 return;
1290               }
1291               theShapes.Append(aPairIter.NewShape());
1292             }
1293           } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
1294             TopExp_Explorer anExp(aPairIter.OldShape(), theValShape.ShapeType());
1295             for(; anExp.More(); anExp.Next()) {
1296               if (anExp.Current().IsSame(theValShape)) { // found a new container
1297                 if (aPairIter.NewShape().IsNull()) {// value was removed
1298                   theShapes.Clear();
1299                   return;
1300                 }
1301                 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
1302                 anOlds.Add(aPairIter.OldShape());
1303                 break;
1304               }
1305             }
1306           }
1307         }
1308       }
1309     }
1310   }
1311   if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
1312     // map of sub-shapes -> number of occurences of these shapes in containers
1313     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
1314     TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
1315     for(; aContIter.More(); aContIter.Next()) {
1316       TopExp_Explorer aSubExp(aContIter.Key(), theValShape.ShapeType());
1317       for(; aSubExp.More(); aSubExp.Next()) {
1318         if (!aSubs.IsBound(aSubExp.Current())) {
1319           aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
1320         }
1321         // store old to know how many olds produced this shape
1322         aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
1323       }
1324     }
1325     // if sub is appeared same times in containers as the number of old shapes that contain it
1326     int aCountInOld = anOlds.Size();
1327     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
1328       aSubsIter(aSubs);
1329     for(; aSubsIter.More(); aSubsIter.Next()) {
1330       if (aSubsIter.Value().Size() == aCountInOld) {
1331         theShapes.Append(aSubsIter.Key());
1332       }
1333     }
1334   }
1335   if (theShapes.IsEmpty()) { // nothing was changed
1336     theShapes.Append(aWasWholeContext ? TopoDS_Shape() : theValShape);
1337   }
1338 }
1339
1340 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
1341   const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
1342   TDF_Label theAccessLabel,
1343   std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
1344 {
1345   std::set<ResultPtr> aResults; // to avoid duplicates, new context, null if deleted
1346   TopTools_ListOfShape aResContShapes;
1347   // iterate context and shape, but also if it is sub-shape of main shape, check also it
1348   TopTools_ListOfShape aContextList;
1349   aContextList.Append(theContShape);
1350   if (theContext.get()) {
1351     ResultPtr aComposite = ModelAPI_Tools::bodyOwner(theContext);
1352     if (aComposite.get() && aComposite->shape().get() && !aComposite->shape()->isNull())
1353       aContextList.Append(aComposite->shape()->impl<TopoDS_Shape>());
1354   }
1355   for(TopTools_ListOfShape::Iterator aContIter(aContextList); aContIter.More(); aContIter.Next()) {
1356     TNaming_SameShapeIterator aModifIter(aContIter.ChangeValue(), theAccessLabel);
1357     for(; aModifIter.More(); aModifIter.Next()) {
1358       TDF_Label anObjLab = aModifIter.Label().Father();
1359       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1360         (theDoc->objects()->object(anObjLab));
1361       if (!aModifierObj.get()) {
1362         // #2241: shape may be sub-element of new object, not main (shell created from faces)
1363         if (!anObjLab.IsRoot())
1364           aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1365           (theDoc->objects()->object(anObjLab.Father()));
1366         if (!aModifierObj.get())
1367           continue;
1368       }
1369       FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
1370       if (!aModifierFeat.get())
1371         continue;
1372       FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1373       if (aModifierFeat == aThisFeature || !theDoc->isLaterByDep(aThisFeature, aModifierFeat))
1374         continue; // the modifier feature is later than this, so, should not be used
1375       FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
1376       if (aCurrentModifierFeat == aModifierFeat ||
1377         !theDoc->isLaterByDep(aModifierFeat, aCurrentModifierFeat))
1378         continue; // the current modifier is later than the found, so, useless
1379       Handle(TNaming_NamedShape) aNewNS;
1380       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1381       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1382         aResults.insert(aModifierObj);
1383         //TNaming_Iterator aPairIter(aNewNS);
1384         //aResContShapes.Append(aPairIter.NewShape());
1385         aResContShapes.Append(aModifierObj->shape()->impl<TopoDS_Shape>());
1386       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
1387         aResults.insert(ResultPtr());
1388       } else { // not-processed modification => don't support it
1389         continue;
1390       }
1391     }
1392   }
1393   if (aResults.empty())
1394     return false; // no modifications found, must stay the same
1395   // iterate all results to find futher modifications
1396   std::set<ResultPtr>::iterator aResIter = aResults.begin();
1397   for(; aResIter != aResults.end(); aResIter++) {
1398     if (aResIter->get() != NULL) {
1399       // compute new values by two contextes: the old and the new
1400       TopTools_ListOfShape aValShapes;
1401       computeValues(theContext, *aResIter, theValShape, aValShapes);
1402
1403       TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
1404       for(; aNewVal.More(); aNewVal.Next()) {
1405         std::list<ResultPtr> aNewRes;
1406         TopTools_ListOfShape aNewUpdatedVal;
1407         TopoDS_Shape aNewValSh = aNewVal.Value();
1408         TopoDS_Shape aNewContShape = (*aResIter)->shape()->impl<TopoDS_Shape>();
1409         if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
1410           aNewValSh.Nullify();
1411         if (searchNewContext(theDoc, aNewContShape, *aResIter, aNewValSh,
1412                              theAccessLabel, aNewRes, aNewUpdatedVal))
1413         {
1414           // appeand new results instead of the current ones
1415           std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1416           TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1417           for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1418             theResults.push_back(*aNewIter);
1419             theValShapes.Append(aNewUpdVal.Value());
1420           }
1421         } else { // the current result is good
1422           theResults.push_back(*aResIter);
1423           theValShapes.Append(aNewValSh);
1424         }
1425       }
1426     }
1427   }
1428   return true; // theResults must be empty: everything is deleted
1429 }
1430
1431 void Model_AttributeSelection::updateInHistory()
1432 {
1433   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1434   // only bodies and parts may be modified later in the history, don't do anything otherwise
1435   if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
1436       aContext->groupName() != ModelAPI_ResultPart::group()))
1437     return;
1438   std::shared_ptr<Model_Document> aDoc =
1439     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1440   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1441   if (!aContData.get() || !aContData->isValid())
1442     return;
1443   TDF_Label aContLab = aContData->shapeLab(); // named shape where the selected context is located
1444   Handle(TNaming_NamedShape) aContNS;
1445   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
1446     bool aFoundNewContext = true;
1447     ResultPtr aNewContext = aContext;
1448     while(aFoundNewContext) {
1449       aFoundNewContext = false;
1450       // parts have no shape in result, so, trace references using the Part info
1451       if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
1452         ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
1453         if (aPartContext.get()) { // searching for the up to date references to the referenced cont
1454           const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
1455           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1456           for(; aRef != aRefs.end(); aRef++) {
1457             // to avoid detection of part changes by local selection only
1458             AttributeSelectionPtr aSel =
1459               std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1460             if (aSel.get() && !aSel->value()->isSame(aSel->context()->shape()))
1461               continue;
1462
1463             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1464             if (aRefFeat.get() && aRefFeat != owner()) {
1465               FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1466               if (!aDoc->isLaterByDep(aRefFeat, aThisFeature)) { // found better feature
1467                 aFoundNewContext = true;
1468                 aNewContext = aRefFeat->firstResult();
1469               }
1470             }
1471           }
1472         }
1473       }
1474     }
1475     if (aNewContext != aContext) {
1476       setValue(aNewContext, value());
1477     }
1478     return;
1479   }
1480   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1481   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1482   // iterate the context shape modifications in order to find a feature that is upper in history
1483   // that this one and is really modifies the referenced result to refer to it
1484   ResultPtr aModifierResFound;
1485   TNaming_Iterator aPairIter(aContNS);
1486   if (!aPairIter.More())
1487     return;
1488   TopoDS_Shape aNewCShape = aPairIter.NewShape();
1489   bool anIterate = true;
1490   // trying to update also the sub-shape selected
1491   GeomShapePtr aSubShape = value();
1492   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1493     aSubShape.reset();
1494   TopoDS_Shape aValShape;
1495   if (aSubShape.get()) {
1496     aValShape = aSubShape->impl<TopoDS_Shape>();
1497   }
1498
1499   std::list<ResultPtr> aNewContexts;
1500   TopTools_ListOfShape aValShapes;
1501   if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1502   {
1503     std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1504     TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1505     if (aNewCont == aNewContexts.end()) { // all results were deleted
1506       ResultPtr anEmptyContext;
1507       std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1508       setValue(anEmptyContext, anEmptyShape); // nullify the selection
1509       return;
1510     }
1511
1512     GeomShapePtr aValueShape;
1513     if (!aNewValues.Value().IsNull()) {
1514       aValueShape = std::make_shared<GeomAPI_Shape>();
1515       aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1516     }
1517     setValue(*aNewCont, aValueShape);
1518     // if there are more than one result, put them by "append" into "parent" list
1519     if (myParent) {
1520       for(aNewCont++, aNewValues.Next(); aNewCont != aNewContexts.end();
1521           aNewCont++, aNewValues.Next()) {
1522         GeomShapePtr aValueShape;
1523         if (!aNewValues.Value().IsNull()) {
1524           aValueShape = std::make_shared<GeomAPI_Shape>();
1525           aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1526         }
1527
1528         // Check that list has the same type of shape selection before adding.
1529         GeomAPI_Shape::ShapeType aListShapeType = GeomAPI_Shape::SHAPE;
1530         if (myParent->selectionType() == "VERTEX") aListShapeType = GeomAPI_Shape::VERTEX;
1531         else if (myParent->selectionType() == "EDGE") aListShapeType = GeomAPI_Shape::EDGE;
1532         else if (myParent->selectionType() == "FACE") aListShapeType = GeomAPI_Shape::FACE;
1533
1534         GeomAPI_Shape::ShapeType aShapeShapeType = GeomAPI_Shape::SHAPE;
1535         if (aValueShape.get()) {
1536           aShapeShapeType = aValueShape->shapeType();
1537         } else {
1538           (*aNewCont)->shape()->shapeType();
1539         }
1540
1541         if (aListShapeType != GeomAPI_Shape::SHAPE && aListShapeType != aShapeShapeType) {
1542           continue;
1543         }
1544
1545         myParent->append(*aNewCont, aValueShape);
1546       }
1547     }
1548   }
1549 }
1550
1551 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1552 {
1553   myParent = theParent;
1554 }
1555
1556 std::string Model_AttributeSelection::contextName(const TDF_Label theSelectionLab)
1557 {
1558   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1559     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1560   FeaturePtr aFeatureOwner = aDoc->featureByLab(theSelectionLab);
1561   if (aFeatureOwner.get()) {
1562     // if it is sub-element of the sketch, the context name is the name of the sketch
1563     // searching also for result - real context
1564     ResultPtr aResult;
1565     FeaturePtr aComposite = ModelAPI_Tools::compositeOwner(aFeatureOwner);
1566     if (aComposite.get() && aComposite->results().size() == 1 &&
1567         aComposite->firstResult()->groupName() == ModelAPI_ResultConstruction::group()) {
1568       aFeatureOwner = aComposite;
1569       aResult = aFeatureOwner->firstResult();
1570     } else {
1571       aResult = aDoc->resultByLab(theSelectionLab);
1572     }
1573     if (aResult.get()) {
1574       // this is to avoid duplicated names of results problem
1575       std::string aContextName = aResult->data()->name();
1576       // myLab corresponds to the current time
1577       TDF_Label aCurrentLab = selectionLabel();
1578       while(aCurrentLab.Depth() > 3)
1579         aCurrentLab = aCurrentLab.Father();
1580
1581       int aNumInHistoryNames =
1582         aDoc->numberOfNameInHistory(aResult, aCurrentLab);
1583       while(aNumInHistoryNames > 1) { // add "_" before name the needed number of times
1584         aContextName = "_" + aContextName;
1585         aNumInHistoryNames--;
1586       }
1587       return aContextName;
1588     }
1589   }
1590   return ""; // invalid case
1591 }
1592
1593 /// This method restores by the context and value name the context label and
1594 /// sub-label where the value is. Returns true if it is valid.
1595 bool Model_AttributeSelection::restoreContext(std::string theName,
1596   TDF_Label& theContext, TDF_Label& theValue)
1597 {
1598   static const GeomShapePtr anEmptyShape; // to store context only
1599   std::string aName = theName;
1600   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1601     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1602
1603   // remove the sub-value part if exists
1604   std::string aSubShapeName = aName;
1605   std::string::size_type n = aName.find('/');
1606   if (n != std::string::npos) {
1607     aName = aName.substr(0, n);
1608   }
1609
1610   if (aName.empty()) return false;
1611   bool anUniqueContext = false;
1612   ResultPtr aCont = aDoc->findByName(aName, aSubShapeName, anUniqueContext);
1613   if (!aCont.get() || !aCont->shape().get() || aCont->shape()->isNull())
1614     return false;
1615
1616   // searching the sub-shape
1617   static const ResultPtr anEmpty;
1618   theValue = aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
1619
1620   // sketch sub-component shape and name is located in separated feature label, try the sub-name
1621   if (theValue.IsNull() && aCont->groupName() == ModelAPI_ResultConstruction::group()) {
1622     std::string::size_type aSlash = aSubShapeName.rfind('/');
1623     if (aSlash != std::string::npos) {
1624       std::string aCompName = aSubShapeName.substr(aSlash + 1);
1625       CompositeFeaturePtr aComposite =
1626         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aCont));
1627       if (aComposite.get() && aComposite->numberOfSubs()) {
1628         const int aSubNum = aComposite->numberOfSubs();
1629         for (int a = 0; a < aSubNum && theValue.IsNull(); a++) {
1630           FeaturePtr aSub = aComposite->subFeature(a);
1631           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
1632           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
1633           for (; aRes != aResults.cend() && theValue.IsNull(); aRes++) {
1634             if ((*aRes)->data()->name() == aCompName) {
1635               theValue = std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->shapeLab();
1636               break;
1637             } else if (aCompName.find((*aRes)->data()->name()) != std::string::npos) {// sub-vertex
1638               TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->shapeLab();
1639               TDF_ChildIDIterator aSubNames(aLab, TDataStd_Name::GetID());
1640               for(; aSubNames.More(); aSubNames.Next()) {
1641                 if (Handle(TDataStd_Name)::DownCast(aSubNames.Value())->Get().
1642                   IsEqual(aCompName.c_str())) {
1643                   theValue = aSubNames.Value()->Label();
1644                   break;
1645                 }
1646               }
1647             }
1648           }
1649         }
1650       }
1651     }
1652   }
1653
1654   /* to find the latest lower result that keeps given shape
1655   bool aFindNewContext = true;
1656   while(aFindNewContext && aCont.get()) {
1657     aFindNewContext = false;
1658     // try to find the last context to find the up to date shape
1659     TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
1660     Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
1661     if (!aNS.IsNull()) {
1662       aNS = TNaming_Tool::CurrentNamedShape(aNS);
1663       if (!aNS.IsNull() && isOlderThanMe(aNS->Label())) { // scope check is for 2228
1664         TDF_Label aLab = aNS->Label();
1665         if (aLab.Depth() % 2 == 0)
1666           aLab = aLab.Father();
1667         ObjectPtr anObj = aDoc->objects()->object(aLab);
1668         while (!anObj.get() && aLab.Depth() > 5) {
1669           aLab = aLab.Father().Father();
1670           anObj = aDoc->objects()->object(aLab);
1671         }
1672
1673         if (anObj.get()) {
1674           ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
1675           if (aRes) {
1676             aCont = aRes;
1677             aFindNewContext = true;
1678           }
1679         }
1680       }
1681     } else if (aCont->groupName() == ModelAPI_ResultBody::group()) {
1682       // try to search newer context by the concealment references
1683       // take references to all results: root one, any sub
1684       std::list<ResultPtr> allRes;
1685       ResultPtr aCompContext;
1686       if (aCont->groupName() == ModelAPI_ResultBody::group()) {
1687         ResultBodyPtr aCompBody = ModelAPI_Tools::bodyOwner(aCont, true);
1688         if (aCompBody.get()) {
1689           ModelAPI_Tools::allSubs(aCompBody, allRes);
1690           allRes.push_back(aCompBody);
1691           aCompContext = aCompBody;
1692         }
1693       }
1694       if (allRes.empty())
1695         allRes.push_back(aCont);
1696
1697       for(std::list<ResultPtr>::iterator aSub = allRes.begin(); aSub != allRes.end(); aSub++) {
1698         ResultPtr aResCont = *aSub;
1699         ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResCont);
1700         if (aResBody.get() && aResBody->numberOfSubs() > 0 && aResBody != aCompContext)
1701           continue; // only lower and higher level subs are counted
1702         const std::set<AttributePtr>& aRefs = aResCont->data()->refsToMe();
1703         std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1704         for(; !aFindNewContext && aRef != aRefs.end(); aRef++) {
1705           if (!aRef->get() || !(*aRef)->owner().get())
1706             continue;
1707           // concealed attribute only
1708           FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1709           if (!ModelAPI_Session::get()->validators()->isConcealed(
1710             aRefFeat->getKind(), (*aRef)->id()))
1711             continue;
1712           // search the feature result that contains sub-shape selected
1713           std::list<std::shared_ptr<ModelAPI_Result> > aResults;
1714
1715           // take all sub-results or one result
1716           std::list<ResultPtr> aRefFeatResults;
1717           ModelAPI_Tools::allResults(aRefFeat, aRefFeatResults);
1718           std::list<ResultPtr>::iterator aRefResIter = aRefFeatResults.begin();
1719           for(; aRefResIter != aRefFeatResults.end(); aRefResIter++) {
1720             ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRefResIter);
1721             if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1722               aResults.push_back(aBody);
1723           }
1724           std::list<std::shared_ptr<ModelAPI_Result> >::iterator aResIter = aResults.begin();
1725           for(; aResIter != aResults.end(); aResIter++) {
1726             if (!aResIter->get() || !(*aResIter)->data()->isValid() || (*aResIter)->isDisabled())
1727               continue;
1728             GeomShapePtr aShape = (*aResIter)->shape();
1729             GeomShapePtr aSelectedShape =
1730               aShapeToBeSelected.get() ? aShapeToBeSelected : aCont->shape();
1731             if (aShape.get() && aShape->isSubShape(aSelectedShape, false)) {
1732               aCont = *aResIter; // found new context (produced from this) with same subshape
1733               aFindNewContext = true; // continue searching futher
1734               break;
1735             }
1736           }
1737         }
1738       }
1739     }
1740   }
1741   // if compsolid is context, try to take sub-solid as context: like in GUI and scripts
1742   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aCont);
1743   if (aComp && aComp->numberOfSubs()) {
1744     std::list<ResultPtr> allSubs;
1745     ModelAPI_Tools::allSubs(aComp, allSubs);
1746     std::list<ResultPtr>::iterator aS = allSubs.begin();
1747     for (; aS != allSubs.end(); aS++) {
1748       ResultBodyPtr aSub = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aS);
1749       if (aSub && aSub->numberOfSubs() == 0 && aSub->shape().get() &&
1750         aSub->shape()->isSubShape(aShapeToBeSelected)) {
1751         aCont = aSub;
1752         break;
1753       }
1754     }
1755   }
1756   */
1757   if (aCont.get()) {
1758     theContext = std::dynamic_pointer_cast<Model_Data>(aCont->data())->label();
1759   }
1760   return true;
1761 }
1762
1763 bool Model_AttributeSelection::isLater(
1764   const TDF_Label theResult1, const TDF_Label theResult2) const
1765 {
1766   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1767     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1768   FeaturePtr aFeat1 = aDoc->featureByLab(theResult1);
1769   if (!aFeat1.get())
1770     return false;
1771   FeaturePtr aFeat2 = aDoc->featureByLab(theResult2);
1772   if (!aFeat2.get())
1773     return false;
1774   return aDoc->isLaterByDep(aFeat1, aFeat2);
1775 }