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