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