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