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           aRes = aDoc->objectByName(ModelAPI_ResultGroup::group(), aSubShapeName);
903       }
904       if (aRes.get()) {
905         setValue(aRes, anEmptyShape);
906         return;
907       }
908     }
909
910     Selector_Selector aSelector(selectionLabel(), baseDocumentLab());
911     myRestoreDocument = aDoc;
912     TDF_Label aContextLabel = aSelector.restoreByName(
913       aSubShapeName, aShapeType, this, myIsGeometricalSelection);
914     myRestoreDocument.reset();
915     if (!aContextLabel.IsNull()) {
916       ResultPtr aContext = aDoc->resultByLab(aContextLabel); // any label for document access
917       if (aContext.get() && aContext->shape().get()) {
918         TopoDS_Shape aContextShape = aContext->shape()->impl<TopoDS_Shape>();
919         if (aSelector.solve(aContextShape)) {
920           TopoDS_Shape aSelectorShape = aSelector.value();
921           GeomShapePtr aShapeToBeSelected(new GeomAPI_Shape);
922           aShapeToBeSelected->setImpl<TopoDS_Shape>(new TopoDS_Shape(aSelectorShape));
923           // make the context result the latest existing
924           aContext = newestContext(aContext, aShapeToBeSelected);
925           if (myIsGeometricalSelection || aCenterType == NOT_CENTER) {
926             // store the currently generated name
927             selectionLabel().ForgetAllAttributes(true);
928             bool aToUnblock = false;
929             aToUnblock = !owner()->data()->blockSendAttributeUpdated(true);
930             myRef.setValue(aContext);
931             aSelector.store(aContextShape);
932             owner()->data()->sendAttributeUpdated(this);
933             if (aToUnblock)
934               owner()->data()->blockSendAttributeUpdated(false);
935             return;
936           } else { // re-select center of circle/arc by context and value
937             if (!aShapeToBeSelected->isEdge())
938               continue;
939             std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aShapeToBeSelected));
940             setValueCenter(aContext, aSelectedEdge, aCenterType);
941           }
942           return;
943         }
944       }
945     }
946   }
947   // invalid
948   TDF_Label aSelLab = selectionLabel();
949   setInvalidIfFalse(aSelLab, false);
950   reset();
951 }
952
953 void Model_AttributeSelection::selectSubShape(const std::string& theType,
954                                               const GeomPointPtr& thePoint)
955 {
956   if (theType.empty() || !thePoint)
957     return;
958
959   // list of parent features
960   FeaturePtr anOwner = ModelAPI_Feature::feature(owner());
961   std::set<FeaturePtr> aParents = ModelAPI_Tools::getParents(anOwner);
962
963   int aSelectionIndex = 0;
964   GeomAPI_Shape::ShapeType aType = GeomAPI_Shape::shapeTypeByStr(theType);
965   if (aType == GeomAPI_Shape::SHAPE) {
966     // possibly, the string consists of the type and the index,
967     // thus, try to separate them
968     size_t aUndersporePos = theType.find_first_of('_');
969     if (aUndersporePos != std::string::npos)
970       aType = GeomAPI_Shape::shapeTypeByStr(theType.substr(0, aUndersporePos));
971
972     if (aType != GeomAPI_Shape::SHAPE) {
973       for (std::string::const_iterator aChar = theType.begin() + aUndersporePos + 1;
974            aChar != theType.end(); ++aChar) {
975         if (std::isdigit(*aChar))
976           aSelectionIndex = aSelectionIndex * 10 + (*aChar - '0');
977         else {
978           aSelectionIndex = 1;
979           break;
980         }
981       }
982       aSelectionIndex -= 1;
983     }
984   }
985
986   std::list<ModelGeomAlgo_Shape::SubshapeOfResult> anAppropriate;
987
988   // collect features from PartSet and the current part
989   SessionPtr aSession = ModelAPI_Session::get();
990   std::list<FeaturePtr> aFeatures = aSession->moduleDocument()->allFeatures();
991   if (aSession->moduleDocument() != owner()->document()) {
992     std::list<FeaturePtr> aPartFeatures = owner()->document()->allFeatures();
993     aFeatures.insert(aFeatures.end(), aPartFeatures.begin(), aPartFeatures.end());
994   }
995   // Process results of all features from the last to the first
996   // to find appropriate sub-shape
997   for (std::list<FeaturePtr>::const_reverse_iterator anIt = aFeatures.rbegin();
998        anIt != aFeatures.rend(); ++anIt) {
999     // selection cannot be linked to the parent features
1000     if (aParents.find(*anIt) != aParents.end())
1001       continue;
1002     // check the feature is a part of composite feature (like sketch elements),
1003     // then do not process it, it will be processed in scope of composite feature
1004     bool isSubOfComposite = false;
1005     const std::set<AttributePtr>& aRefs = (*anIt)->data()->refsToMe();
1006     for (std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
1007          aRefIt != aRefs.end() && !isSubOfComposite; ++aRefIt) {
1008       FeaturePtr aFeature = ModelAPI_Feature::feature((*aRefIt)->owner());
1009       CompositeFeaturePtr aCompFeature =
1010           std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
1011       isSubOfComposite = aCompFeature && aCompFeature->isSub(*anIt);
1012     }
1013     if (isSubOfComposite)
1014       continue;
1015
1016     // process results of the current feature to find appropriate sub-shape
1017     if (ModelGeomAlgo_Shape::findSubshapeByPoint(*anIt, thePoint, aType, anAppropriate)) {
1018       std::list<ModelGeomAlgo_Shape::SubshapeOfResult>::iterator anApIt = anAppropriate.begin();
1019       for (; aSelectionIndex > 0 && anApIt != anAppropriate.end(); --aSelectionIndex)
1020         ++anApIt; // skip this shape, because one of the previous is selected
1021
1022       if (anApIt != anAppropriate.end()) {
1023         if (anApIt->myCenterType == (int)ModelAPI_AttributeSelection::NOT_CENTER)
1024           setValue(anApIt->myResult, anApIt->mySubshape);
1025         else
1026           setValueCenter(anApIt->myResult, anApIt->mySubshape->edge(),
1027                          (ModelAPI_AttributeSelection::CenterType)anApIt->myCenterType);
1028         return;
1029       }
1030     }
1031   }
1032
1033   TDF_Label aSelLab = selectionLabel();
1034   setInvalidIfFalse(aSelLab, false);
1035   reset();
1036 }
1037
1038 void Model_AttributeSelection::selectSubShape(const std::string& theType,
1039   const std::string& theContextName, const int theIndex)
1040 {
1041   // selection of context by name
1042   selectSubShape(theType, theContextName);
1043   ResultPtr aContext = context();
1044   if (aContext.get()) {
1045     GeomShapePtr aContShape = aContext->shape();
1046     if (aContShape.get()) {
1047       GeomAlgoAPI_NExplode aNExp(aContShape, GeomAPI_Shape::shapeTypeByStr(theType));
1048       GeomShapePtr aValue = aNExp.shape(theIndex);
1049       if (aValue.get())
1050         setValue(aContext, aValue);
1051     }
1052   }
1053 }
1054
1055 void Model_AttributeSelection::setId(int theID)
1056 {
1057   std::shared_ptr<GeomAPI_Shape> aSelection;
1058
1059   ResultPtr aContextRes = context();
1060   // support for compsolids:
1061   while(ModelAPI_Tools::bodyOwner(aContextRes).get()) {
1062     aContextRes = ModelAPI_Tools::bodyOwner(aContextRes);
1063   }
1064   std::shared_ptr<GeomAPI_Shape> aContext = aContextRes->shape();
1065
1066   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
1067   // searching for the latest main shape
1068   if (theID > 0 && aContext && !aContext->isNull())
1069   {
1070     std::shared_ptr<Model_Document> aDoc =
1071       std::dynamic_pointer_cast<Model_Document>(aContextRes->document());
1072     if (aDoc.get()) {
1073       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1074       if (!aNS.IsNull()) {
1075         aMainShape = TNaming_Tool::CurrentShape(aNS);
1076       }
1077     }
1078
1079     TopTools_IndexedMapOfShape aSubShapesMap;
1080     TopExp::MapShapes(aMainShape, aSubShapesMap);
1081     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1082
1083     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1084     aResult->setImpl(new TopoDS_Shape(aSelShape));
1085
1086     aSelection = aResult;
1087   }
1088
1089   setValue(aContextRes, aSelection);
1090 }
1091
1092 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1093 {
1094   std::string aResult;
1095   if (owner()->document() != theContext->document()) {
1096     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1097       aResult = theContext->document()->kind() + "/";
1098     } else {
1099       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1100         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1101       if (aDocRes.get()) {
1102         aResult = aDocRes->data()->name() + "/";
1103       }
1104     }
1105   }
1106   aResult += theContext->data()->name();
1107   return aResult;
1108 }
1109
1110 void Model_AttributeSelection::computeValues(
1111   ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
1112   TopTools_ListOfShape& theShapes)
1113 {
1114   bool aWasWholeContext = theValShape.IsNull();
1115   if (aWasWholeContext) {
1116     theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
1117   }
1118   TopAbs_ShapeEnum aValType = theValShape.ShapeType();
1119   TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
1120   // if a new value is unchanged in the new context, do nothing: value is correct
1121   TopExp_Explorer aSubExp(aNewContShape, aValType);
1122   for(; aSubExp.More(); aSubExp.Next()) {
1123     if (aSubExp.Current().IsSame(theValShape)) {
1124       theShapes.Append(theValShape);
1125       return;
1126     }
1127   }
1128   // if new context becomes compsolid, the resulting sub may be in sub-solids
1129   std::list<ResultPtr> aNewToIterate;
1130   aNewToIterate.push_back(theNewContext);
1131   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theNewContext);
1132   if (aComp.get()) {
1133     std::list<ResultPtr> allNewContextSubs;
1134     ModelAPI_Tools::allSubs(aComp, allNewContextSubs);
1135     std::list<ResultPtr>::iterator aSub = allNewContextSubs.begin();
1136     for(; aSub != allNewContextSubs.end(); aSub++) {
1137       ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aSub);
1138       if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1139         aNewToIterate.push_back(aBody);
1140     }
1141   }
1142
1143   // first iteration: searching for the whole shape appearance (like face of the box)
1144   // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
1145   int aToFindPart = 0;
1146   TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
1147   TopTools_MapOfShape anOlds; // to know how many olds produced new containers
1148   for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
1149     std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
1150     for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
1151       std::shared_ptr<Model_Data> aNewData =
1152         std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
1153       TDF_Label aNewLab = aNewData->shapeLab();
1154       // searching for produced sub-shape fully on some label
1155       TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID());
1156       for(; aNSIter.More(); aNSIter.Next()) {
1157         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1158         for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
1159           if (aToFindPart == 0) { // search shape is fully inside
1160             if (aPairIter.OldShape().IsSame(theValShape)) {
1161               if (aPairIter.NewShape().IsNull()) {// value was removed
1162                 theShapes.Clear();
1163                 return;
1164               }
1165               // don't add edges generated from faces
1166               if (aPairIter.NewShape().ShapeType() <= aValType)
1167                 theShapes.Append(aPairIter.NewShape());
1168             }
1169           } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
1170             TopExp_Explorer anExp(aPairIter.OldShape(), aValType);
1171             for(; anExp.More(); anExp.Next()) {
1172               if (anExp.Current().IsSame(theValShape)) { // found a new container
1173                 if (aPairIter.NewShape().IsNull()) // skip removed high-level shape
1174                   continue;
1175                 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
1176                 anOlds.Add(aPairIter.OldShape());
1177                 break;
1178               }
1179             }
1180           }
1181         }
1182       }
1183     }
1184   }
1185   if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
1186     // also iterate the whole old shape to find not-modified shapes that contain this old
1187     TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
1188     NCollection_Map<TopAbs_ShapeEnum> aNewTypes; // types of shapes to iterate
1189     TopTools_DataMapOfShapeShape::Iterator aNewTypeIter(aNewToOld);
1190     for(; aNewTypeIter.More(); aNewTypeIter.Next()) {
1191       if (aNewTypeIter.Key().ShapeType() != aValType)
1192         aNewTypes.Add(aNewTypeIter.Key().ShapeType());
1193     }
1194     NCollection_Map<TopAbs_ShapeEnum>::Iterator aTypeIter(aNewTypes);
1195     for(; aTypeIter.More(); aTypeIter.Next()) {
1196       for(TopExp_Explorer anExp(anOldContShape, aTypeIter.Value()); anExp.More(); anExp.Next()) {
1197         TopoDS_Shape anOld = anExp.Current();
1198         if (aNewToOld.IsBound(anOld) || anOlds.Contains(anOld)) // this was modified
1199           continue;
1200         TopExp_Explorer aValExp(anOld, aValType);
1201         for(; aValExp.More(); aValExp.Next()) {
1202           const TopoDS_Shape& anUnchanged = aValExp.Current();
1203           if (anUnchanged.IsSame(theValShape)) {
1204             aNewToOld.Bind(anOld, anOld);
1205             anOlds.Add(anOld);
1206             break;
1207           }
1208         }
1209       }
1210     }
1211
1212     // map of sub-shapes -> number of occurrences of these shapes in containers
1213     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
1214     TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
1215     for(; aContIter.More(); aContIter.Next()) {
1216       TopExp_Explorer aSubExp(aContIter.Key(), aValType);
1217       for(; aSubExp.More(); aSubExp.Next()) {
1218         if (!aSubs.IsBound(aSubExp.Current())) {
1219           aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
1220         }
1221         // store old to know how many olds produced this shape
1222         aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
1223       }
1224     }
1225     // if sub is appeared same times in containers as the number of old shapes that contain it
1226     int aCountInOld = anOlds.Size();
1227     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
1228       aSubsIter(aSubs);
1229     for(; aSubsIter.More(); aSubsIter.Next()) {
1230       if (aSubsIter.Value().Size() == aCountInOld) {
1231         TopoDS_Shape anOld = aSubsIter.Key();
1232         // check this exists in the new shape
1233         TopExp_Explorer aNew(aNewContShape, anOld.ShapeType());
1234         for (; aNew.More(); aNew.Next()) {
1235           if (aNew.Current().IsSame(anOld))
1236             break;
1237         }
1238         if (aNew.More())
1239           theShapes.Append(anOld);
1240       }
1241     }
1242   }
1243   if (theShapes.IsEmpty()) { // nothing was changed
1244     if (aWasWholeContext)
1245       theShapes.Append(TopoDS_Shape());
1246     else { // if theValShape exists in new context, add it without changes, otherwise - nothing
1247       for (TopExp_Explorer aNew(aNewContShape, aValType); aNew.More(); aNew.Next()){
1248         if (aNew.Current().IsSame(theValShape)) {
1249           theShapes.Append(theValShape);
1250           break;
1251         }
1252       }
1253     }
1254   } else if (theShapes.Size() > 1) {
1255     // check it is possible to remove extra sub-shapes:
1256     // keep only shapes with the same number of containers if possible
1257     TopAbs_ShapeEnum anAncType = TopAbs_FACE;
1258     if (aValType == TopAbs_VERTEX)
1259       anAncType = TopAbs_EDGE;
1260     TopoDS_Shape anOldContext = theOldContext->shape()->impl<TopoDS_Shape>();
1261     TopTools_IndexedDataMapOfShapeListOfShape anOldMap;
1262     TopExp::MapShapesAndUniqueAncestors(anOldContext, aValType,  anAncType, anOldMap);
1263     if (anOldMap.Contains(theValShape)) {
1264       int aNumInOld = anOldMap.FindFromKey(theValShape).Extent();
1265       TopTools_IndexedDataMapOfShapeListOfShape aNewMap;
1266       TopExp::MapShapesAndUniqueAncestors(aNewContShape, aValType,  anAncType, aNewMap);
1267       TopTools_ListOfShape aNewResults;
1268       for(TopTools_ListOfShape::Iterator aNewSubs(theShapes); aNewSubs.More(); aNewSubs.Next()) {
1269         TopoDS_Shape aCand = aNewSubs.Value();
1270         if (aNewMap.Contains(aCand) && aNewMap.FindFromKey(aCand).Extent() == aNumInOld)
1271           aNewResults.Append(aCand);
1272       }
1273       if (!aNewResults.IsEmpty() && aNewResults.Size() < theShapes.Size())
1274         theShapes = aNewResults;
1275     }
1276   }
1277 }
1278
1279 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
1280   const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
1281   TDF_Label theAccessLabel,
1282   std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
1283 {
1284   std::set<ResultPtr> aResults; // to avoid duplicates, new context, null if deleted
1285   // iterate context and shape, but also if it is sub-shape of main shape, check also it
1286   TopTools_ListOfShape aContextList;
1287   aContextList.Append(theContShape);
1288   if (theContext.get()) {
1289     ResultPtr aComposite = ModelAPI_Tools::bodyOwner(theContext);
1290     if (aComposite.get() && aComposite->shape().get() && !aComposite->shape()->isNull())
1291       aContextList.Append(aComposite->shape()->impl<TopoDS_Shape>());
1292   }
1293   for(TopTools_ListOfShape::Iterator aContIter(aContextList); aContIter.More(); aContIter.Next()) {
1294     TNaming_SameShapeIterator aModifIter(aContIter.ChangeValue(), theAccessLabel);
1295     for(; aModifIter.More(); aModifIter.Next()) {
1296       TDF_Label anObjLab = aModifIter.Label().Father();
1297       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1298         (theDoc->objects()->object(anObjLab));
1299       if (!aModifierObj.get()) {
1300         // #2241: shape may be sub-element of new object, not main (shell created from faces)
1301         if (!anObjLab.IsRoot())
1302           aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1303           (theDoc->objects()->object(anObjLab.Father()));
1304         if (!aModifierObj.get())
1305           continue;
1306       }
1307       FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
1308       if (!aModifierFeat.get())
1309         continue;
1310       FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1311       if (aModifierFeat == aThisFeature || !theDoc->isLaterByDep(aThisFeature, aModifierFeat))
1312         continue; // the modifier feature is later than this, so, should not be used
1313       FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
1314       if (aCurrentModifierFeat == aModifierFeat ||
1315         !theDoc->isLaterByDep(aModifierFeat, aCurrentModifierFeat))
1316         continue; // the current modifier is later than the found, so, useless
1317       Handle(TNaming_NamedShape) aNewNS;
1318       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1319       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1320         aResults.insert(aModifierObj);
1321       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
1322         aResults.insert(ResultPtr());
1323       } else { // not-processed modification => don't support it
1324         continue;
1325       }
1326     }
1327   }
1328   // if there exist context composite and sub-result(s), leave only sub(s)
1329   for(std::set<ResultPtr>::iterator aResIter = aResults.begin(); aResIter != aResults.end();) {
1330     ResultPtr aParent = ModelAPI_Tools::bodyOwner(*aResIter);
1331     for(; aParent.get(); aParent = ModelAPI_Tools::bodyOwner(aParent))
1332       if (aResults.count(aParent))
1333         break;
1334     if (aParent.get()) { // erase from set, so, restart iteration
1335       aResults.erase(aParent);
1336       aResIter = aResults.begin();
1337     } else aResIter++;
1338   }
1339
1340   if (aResults.empty()) {
1341     // check the context become concealed by operation which is earlier than this selection
1342     std::list<ResultPtr> allRes;
1343     ResultPtr aRoot = ModelAPI_Tools::bodyOwner(theContext, true);
1344     if (!aRoot.get())
1345       aRoot = theContext;
1346     ResultBodyPtr aRootBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aRoot);
1347     if (aRootBody.get()) {
1348       ModelAPI_Tools::allSubs(aRootBody, allRes);
1349       allRes.push_back(aRootBody);
1350     } else
1351       allRes.push_back(aRoot);
1352
1353     FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1354     for (std::list<ResultPtr>::iterator aSub = allRes.begin(); aSub != allRes.end(); aSub++) {
1355       ResultPtr aResCont = *aSub;
1356       const std::set<AttributePtr>& aRefs = aResCont->data()->refsToMe();
1357       std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1358       for (; aRef != aRefs.end(); aRef++) {
1359         if (!aRef->get() || !(*aRef)->owner().get())
1360           continue;
1361         // concealed attribute only
1362         FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1363         if (aRefFeat == aThisFeature)
1364           continue;
1365         if (!ModelAPI_Session::get()->validators()->isConcealed(
1366           aRefFeat->getKind(), (*aRef)->id()))
1367           continue;
1368         if (theDoc->isLaterByDep(aThisFeature, aRefFeat)) {
1369           // for extrusion cut in python script the nested sketch reference may be concealed before
1370           // it is nested, so, check this composite feature is valid
1371           static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
1372           // need to be validated to update the "Apply" state if not previewed
1373           if (aFactory->validate(aRefFeat)) {
1374             // there could be a reference to unmodified object, check result contain same shape
1375             std::list<ResultPtr> aRefResults;
1376             ModelAPI_Tools::allResults(aRefFeat, aRefResults);
1377             std::list<ResultPtr>::iterator aRefIter = aRefResults.begin();
1378             for(; aRefIter != aRefResults.end(); aRefIter++) {
1379               ResultBodyPtr aRefBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRefIter);
1380               if (!aRefBody.get() || aRefBody->numberOfSubs() != 0) // iterate only leafs
1381                 continue;
1382               GeomShapePtr aRefShape = aRefBody->shape();
1383               if (!aRefShape.get() || aRefShape->isNull())
1384                 continue;
1385               if (aRefShape->impl<TopoDS_Shape>().IsSame(theContShape)) {
1386                 // add the new context result with the same shape
1387                 aResults.insert(aRefBody);
1388               }
1389             }
1390             if (aResults.empty())
1391               return true; // feature conceals result, return true, so the context will be removed
1392           }
1393         }
1394       }
1395     }
1396     if (aResults.empty())
1397       return false; // no modifications found, must stay the same
1398   }
1399   // iterate all results to find further modifications
1400   std::set<ResultPtr>::iterator aResIter = aResults.begin();
1401   for(; aResIter != aResults.end(); aResIter++) {
1402     if (aResIter->get() != NULL) {
1403       // compute new values by two contexts: the old and the new
1404       TopTools_ListOfShape aValShapes;
1405       computeValues(theContext, *aResIter, theValShape, aValShapes);
1406
1407       TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
1408       for(; aNewVal.More(); aNewVal.Next()) {
1409         std::list<ResultPtr> aNewRes;
1410         TopTools_ListOfShape aNewUpdatedVal;
1411         TopoDS_Shape aNewValSh = aNewVal.Value();
1412         TopoDS_Shape aNewContShape = (*aResIter)->shape()->impl<TopoDS_Shape>();
1413         if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
1414           aNewValSh.Nullify();
1415         if (searchNewContext(theDoc, aNewContShape, *aResIter, aNewValSh,
1416                              theAccessLabel, aNewRes, aNewUpdatedVal))
1417         {
1418           // append new results instead of the current ones
1419           std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1420           TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1421           for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1422             theResults.push_back(*aNewIter);
1423             theValShapes.Append(aNewUpdVal.Value());
1424           }
1425         } else { // the current result is good
1426           theResults.push_back(*aResIter);
1427           theValShapes.Append(aNewValSh);
1428         }
1429       }
1430     }
1431   }
1432   return true; // theResults must be empty: everything is deleted
1433 }
1434
1435 void Model_AttributeSelection::updateInHistory(bool& theRemove)
1436 {
1437   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1438   // only bodies and parts may be modified later in the history, don't do anything otherwise
1439   if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
1440       aContext->groupName() != ModelAPI_ResultPart::group()))
1441     return;
1442   std::shared_ptr<Model_Document> aDoc =
1443     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1444   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1445   if (!aContData.get() || !aContData->isValid())
1446     return;
1447   TDF_Label aContLab = aContData->shapeLab(); // named shape where the selected context is located
1448
1449   // checking this may be just a reference to another context (same shape), so use that label
1450   Handle(TNaming_NamedShape) aContNS;
1451   Handle(TDF_Reference) aRefAttr;
1452   while(!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS) &&
1453         aContLab.FindAttribute(TDF_Reference::GetID(), aRefAttr))
1454     aContLab = aRefAttr->Get();
1455
1456   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
1457     bool aFoundNewContext = true;
1458     ResultPtr aNewContext = aContext;
1459     while(aFoundNewContext) {
1460       aFoundNewContext = false;
1461       // parts have no shape in result, so, trace references using the Part info
1462       if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
1463         ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
1464         if (aPartContext.get()) { // searching for the up to date references to the referenced cont
1465           const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
1466           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1467           for(; aRef != aRefs.end(); aRef++) {
1468             // to avoid detection of part changes by local selection only
1469             AttributeSelectionPtr aSel =
1470               std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1471             if (aSel.get() && aSel->value().get() &&
1472                 !aSel->value()->isSame(aSel->context()->shape()))
1473               continue;
1474
1475             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1476
1477             if (aRefFeat.get() && aRefFeat != owner() && aRefFeat->firstResult().get()) {
1478               // check the reference is concealed: #2900
1479               ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
1480               if (!aValidators->isConcealed(aRefFeat->getKind(), (*aRef)->id()))
1481                 continue;
1482               FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1483               if (!aDoc->isLaterByDep(aRefFeat, aThisFeature)) { // found better feature
1484                 aFoundNewContext = true;
1485                 aNewContext = aRefFeat->firstResult();
1486               }
1487             }
1488           }
1489         }
1490       }
1491     }
1492     if (aNewContext != aContext) {
1493       setValue(aNewContext, value());
1494     }
1495     return;
1496   }
1497   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1498   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1499   // iterate the context shape modifications in order to find a feature that is upper in history
1500   // that this one and is really modifies the referenced result to refer to it
1501   ResultPtr aModifierResFound;
1502   TNaming_Iterator aPairIter(aContNS);
1503   if (!aPairIter.More())
1504     return;
1505   TopoDS_Shape aNewCShape = aPairIter.NewShape();
1506   bool anIterate = true;
1507   // trying to update also the sub-shape selected
1508   GeomShapePtr aSubShape = value();
1509   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1510     aSubShape.reset();
1511   TopoDS_Shape aValShape;
1512   if (aSubShape.get()) {
1513     aValShape = aSubShape->impl<TopoDS_Shape>();
1514   }
1515
1516   std::list<ResultPtr> aNewContexts;
1517   TopTools_ListOfShape aValShapes;
1518   if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1519   {
1520     std::set<ResultPtr> allContexts, aSkippedContext;
1521     std::list<ResultPtr>::iterator aNewContext = aNewContexts.begin();
1522     for(; aNewContext != aNewContexts.end(); aNewContext++)
1523       allContexts.insert(*aNewContext);
1524
1525     // if there exist context composite and sub-result(s), leave only sub(s)
1526     std::set<ResultPtr>::iterator aResIter = allContexts.begin();
1527     for(; aResIter != allContexts.end(); aResIter++) {
1528       ResultPtr aParent = ModelAPI_Tools::bodyOwner(*aResIter);
1529       for(; aParent.get(); aParent = ModelAPI_Tools::bodyOwner(aParent))
1530         if (allContexts.count(aParent))
1531           aSkippedContext.insert(aParent);
1532     }
1533
1534     GeomAPI_Shape::ShapeType aListShapeType = GeomAPI_Shape::SHAPE;
1535     if (myParent) {
1536       if (myParent->selectionType() == "VERTEX" || myParent->selectionType() == "Vertices")
1537         aListShapeType = GeomAPI_Shape::VERTEX;
1538       else if (myParent->selectionType() == "EDGE" || myParent->selectionType() == "Edges")
1539         aListShapeType = GeomAPI_Shape::EDGE;
1540       else if (myParent->selectionType() == "FACE" || myParent->selectionType() == "Faces")
1541         aListShapeType = GeomAPI_Shape::FACE;
1542     }
1543
1544     std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1545     TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1546     bool aFirst = true; // first is set to this, next are appended to parent
1547     for(; aNewCont != aNewContexts.end(); aNewCont++, aNewValues.Next()) {
1548       if (aSkippedContext.count(*aNewCont))
1549         continue;
1550
1551       GeomShapePtr aValueShape;
1552       if (!aNewValues.Value().IsNull()) {
1553         aValueShape = std::make_shared<GeomAPI_Shape>();
1554         aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1555       }
1556       // Check that list has the same type of shape selection before adding.
1557       GeomAPI_Shape::ShapeType aShapeShapeType = GeomAPI_Shape::SHAPE;
1558       if (aValueShape.get()) {
1559         aShapeShapeType = aValueShape->shapeType();
1560       } else {
1561         aShapeShapeType = (*aNewCont)->shape()->shapeType();
1562       }
1563       if (aListShapeType != GeomAPI_Shape::SHAPE && aListShapeType != aShapeShapeType) {
1564         continue;
1565       }
1566
1567       ResultPtr aNewContext = *aNewCont;
1568       if (aValueShape.get()) { // #2892 if context is higher level result, search this sub in lower
1569         ResultBodyPtr aBodyContext = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aNewContext);
1570         if (aBodyContext.get() && aBodyContext->numberOfSubs() != 0) {
1571           std::list<ResultPtr> aLower;
1572           ModelAPI_Tools::allSubs(aBodyContext, aLower, true);
1573           for(std::list<ResultPtr>::iterator aL = aLower.begin(); aL != aLower.end(); aL++) {
1574             GeomShapePtr aLShape = (*aL)->shape();
1575             if (aLShape.get() && !aLShape->isNull()) {
1576               if (aLShape->isSubShape(aValueShape, false)) {
1577                 aNewContext = *aL;
1578                 break;
1579               }
1580             }
1581           }
1582         }
1583       }
1584
1585       if (aFirst) {
1586         if (!myParent || !myParent->isInList(aNewContext, aValueShape)) { // avoid duplicates
1587           setValue(aNewContext, aValueShape);
1588           aFirst = false;
1589         }
1590       } else if (myParent) {
1591         if (!myParent->isInList(aNewContext, aValueShape)) // avoid addition of duplicates
1592           myParent->append(aNewContext, aValueShape);
1593       }
1594     }
1595     if (aFirst) { // nothing was added, all results were deleted
1596       if (myParent) {
1597         theRemove = true;
1598       } else {
1599         ResultPtr anEmptyContext;
1600         std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1601         setValue(anEmptyContext, anEmptyShape); // nullify the selection
1602         return;
1603       }
1604     }
1605   }
1606 }
1607
1608 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1609 {
1610   myParent = theParent;
1611 }
1612
1613 std::string Model_AttributeSelection::contextName(const TDF_Label theSelectionLab)
1614 {
1615   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1616     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1617   FeaturePtr aFeatureOwner = aDoc->featureByLab(theSelectionLab);
1618   bool aBaseDocumnetUsed = false;
1619   if (!aFeatureOwner.get()) { // use module document
1620     aDoc = std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument());
1621     aFeatureOwner = aDoc->featureByLab(theSelectionLab);
1622     aBaseDocumnetUsed = true;
1623   }
1624   if (aFeatureOwner.get()) {
1625     // if it is sub-element of the sketch, the context name is the name of the sketch
1626     // searching also for result - real context
1627     ResultPtr aResult;
1628     FeaturePtr aComposite = ModelAPI_Tools::compositeOwner(aFeatureOwner);
1629     if (aComposite.get() && aComposite->results().size() == 1 &&
1630         aComposite->firstResult()->groupName() == ModelAPI_ResultConstruction::group()) {
1631       aFeatureOwner = aComposite;
1632       aResult = aFeatureOwner->firstResult();
1633     } else {
1634       aResult = aDoc->resultByLab(theSelectionLab);
1635     }
1636     if (aResult.get()) {
1637       // this is to avoid duplicated names of results problem
1638       std::string aContextName = aResult->data()->name();
1639       // myLab corresponds to the current time
1640       TDF_Label aCurrentLab = selectionLabel();
1641       while(aCurrentLab.Depth() > 3)
1642         aCurrentLab = aCurrentLab.Father();
1643
1644       int aNumInHistoryNames =
1645         aDoc->numberOfNameInHistory(aResult, aCurrentLab);
1646       while(aNumInHistoryNames > 1) { // add "_" before name the needed number of times
1647         aContextName = "_" + aContextName;
1648         aNumInHistoryNames--;
1649       }
1650       if (aBaseDocumnetUsed)
1651         aContextName = aDoc->kind() + "/" + aContextName;
1652       return aContextName;
1653     }
1654   }
1655   return ""; // invalid case
1656 }
1657
1658 /// This method restores by the context and value name the context label and
1659 /// sub-label where the value is. Returns true if it is valid.
1660 bool Model_AttributeSelection::restoreContext(std::string theName,
1661   TDF_Label& theContext, TDF_Label& theValue)
1662 {
1663   static const GeomShapePtr anEmptyShape; // to store context only
1664   std::string aName = theName;
1665   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1666     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1667
1668   // remove the sub-value part if exists
1669   std::string aSubShapeName = aName;
1670   std::string::size_type n = aName.find('/');
1671   if (n != std::string::npos) {
1672     aName = aName.substr(0, n);
1673   }
1674
1675   if (aName.empty()) return false;
1676   bool anUniqueContext = false;
1677   ResultPtr aCont = aDoc->findByName(aName, aSubShapeName, anUniqueContext);
1678   if (!aCont.get() || !aCont->shape().get() || aCont->shape()->isNull()) {
1679     // name in PartSet?
1680     aDoc = std::dynamic_pointer_cast<Model_Document>(
1681       ModelAPI_Session::get()->moduleDocument());
1682     if (theName.find(aDoc->kind()) == 0) { // remove the document identifier from name if exists
1683       aSubShapeName = theName.substr(aDoc->kind().size() + 1);
1684       aName = aSubShapeName;
1685       std::string::size_type n = aName.find('/');
1686       if (n != std::string::npos) {
1687         aName = aName.substr(0, n);
1688       }
1689     }
1690     aCont = aDoc->findByName(aName, aSubShapeName, anUniqueContext);
1691     if (!aCont.get() || !aCont->shape().get() || aCont->shape()->isNull())
1692       return false;
1693   }
1694
1695   // searching the sub-shape
1696   static const ResultPtr anEmpty;
1697   theValue = aDoc->findNamingName(aSubShapeName, anUniqueContext ? aCont : anEmpty);
1698
1699   // sketch sub-component shape and name is located in separated feature label, try the sub-name
1700   if (theValue.IsNull() && aCont->groupName() == ModelAPI_ResultConstruction::group()) {
1701     std::string::size_type aSlash = aSubShapeName.rfind('/');
1702     if (aSlash != std::string::npos) {
1703       std::string aCompName = aSubShapeName.substr(aSlash + 1);
1704       CompositeFeaturePtr aComposite =
1705         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aDoc->feature(aCont));
1706       if (aComposite.get() && aComposite->numberOfSubs()) {
1707         const int aSubNum = aComposite->numberOfSubs();
1708         for (int a = 0; a < aSubNum && theValue.IsNull(); a++) {
1709           FeaturePtr aSub = aComposite->subFeature(a);
1710           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aSub->results();
1711           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRes = aResults.cbegin();
1712           for (; aRes != aResults.cend() && theValue.IsNull(); aRes++) {
1713             if ((*aRes)->data()->name() == aCompName) {
1714               theValue = std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->shapeLab();
1715               break;
1716             } else { // any sub-label because the sketch line may be renamed, but not sub-vertices
1717               TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>((*aRes)->data())->shapeLab();
1718               TDF_ChildIDIterator aSubNames(aLab, TDataStd_Name::GetID());
1719               for(; aSubNames.More(); aSubNames.Next()) {
1720                 if (Handle(TDataStd_Name)::DownCast(aSubNames.Value())->Get().
1721                   IsEqual(aCompName.c_str())) {
1722                   theValue = aSubNames.Value()->Label();
1723                   break;
1724                 }
1725               }
1726             }
1727           }
1728         }
1729       }
1730     }
1731   }
1732
1733   if (aCont.get()) {
1734     theContext = std::dynamic_pointer_cast<Model_Data>(aCont->data())->label();
1735   }
1736   return true;
1737 }
1738
1739 bool Model_AttributeSelection::isLater(
1740   const TDF_Label theResult1, const TDF_Label theResult2) const
1741 {
1742   std::shared_ptr<Model_Document> aDoc = myRestoreDocument.get() ? myRestoreDocument :
1743     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1744   FeaturePtr aFeat1 = aDoc->featureByLab(theResult1);
1745   if (!aFeat1.get())
1746     return false;
1747   FeaturePtr aFeat2 = aDoc->featureByLab(theResult2);
1748   if (!aFeat2.get())
1749     return false;
1750   return aDoc->isLaterByDep(aFeat1, aFeat2);
1751 }
1752
1753 ResultPtr Model_AttributeSelection::newestContext(
1754   const ResultPtr theCurrent, const GeomShapePtr theValue)
1755 {
1756   ResultPtr aResult = theCurrent;
1757   GeomShapePtr aSelectedShape = theValue.get() ? theValue : theCurrent->shape();
1758   std::shared_ptr<Model_Document> aDoc =
1759     std::dynamic_pointer_cast<Model_Document>(owner()->document());
1760   bool aFindNewContext = true;
1761   while (aFindNewContext && aResult.get()) {
1762     aFindNewContext = false;
1763     // try to find the last context to find the up to date shape
1764     TopoDS_Shape aConShape = aResult->shape()->impl<TopoDS_Shape>();
1765     if (TNaming_Tool::HasLabel(selectionLabel(), aConShape)) {
1766       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
1767       if (!aNS.IsNull()) {
1768         aNS = TNaming_Tool::CurrentNamedShape(aNS);
1769         if (!aNS.IsNull()
1770             && isLater(selectionLabel(), aNS->Label())
1771             && isLater(aNS->Label(),
1772                        std::dynamic_pointer_cast<Model_Data>(aResult->data())->label()))
1773         {
1774           TDF_Label aLab = aNS->Label();
1775           ResultPtr aRes = aDoc->resultByLab(aLab);
1776           if (aRes.get()) {
1777             if (aRes->shape()->isSubShape(aSelectedShape)) {
1778               aResult = aRes;
1779               aFindNewContext = true;
1780               continue;
1781             }
1782           }
1783         }
1784       }
1785     }
1786
1787     // TestFillWireVertex.py - sketch constructions for wire may participate too
1788     //if (aResult->groupName() == ModelAPI_ResultBody::group()) {
1789       // try to search newer context by the concealment references
1790       // take references to all results: root one, any sub
1791     std::list<ResultPtr> allRes;
1792     ResultPtr aCompContext;
1793     ResultBodyPtr aCompBody = ModelAPI_Tools::bodyOwner(aResult, true);
1794     if (aCompBody.get()) {
1795       ModelAPI_Tools::allSubs(aCompBody, allRes);
1796       allRes.push_back(aCompBody);
1797       aCompContext = aCompBody;
1798     }
1799     if (allRes.empty())
1800       allRes.push_back(aResult);
1801
1802     for (std::list<ResultPtr>::iterator aSub = allRes.begin(); aSub != allRes.end(); aSub++) {
1803       ResultPtr aResCont = *aSub;
1804       ResultBodyPtr aResBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResCont);
1805       if (aResBody.get() && aResBody->numberOfSubs() > 0 && aResBody != aCompContext)
1806         continue; // only lower and higher level subs are counted
1807       const std::set<AttributePtr>& aRefs = aResCont->data()->refsToMe();
1808       std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1809       for (; !aFindNewContext && aRef != aRefs.end(); aRef++) {
1810         if (!aRef->get() || !(*aRef)->owner().get())
1811           continue;
1812         // concealed attribute only
1813         FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1814         if (!ModelAPI_Session::get()->validators()->isConcealed(
1815           aRefFeat->getKind(), (*aRef)->id()))
1816           continue;
1817         // search the feature result that contains sub-shape selected
1818         std::list<std::shared_ptr<ModelAPI_Result> > aResults;
1819
1820         // take all sub-results or one result
1821         std::list<ResultPtr> aRefFeatResults;
1822         ModelAPI_Tools::allResults(aRefFeat, aRefFeatResults);
1823         std::list<ResultPtr>::iterator aRefResIter = aRefFeatResults.begin();
1824         for (; aRefResIter != aRefFeatResults.end(); aRefResIter++) {
1825           ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRefResIter);
1826           if (aBody.get() && aBody->numberOfSubs() == 0) // add only lower level subs
1827             aResults.push_back(aBody);
1828         }
1829         std::list<std::shared_ptr<ModelAPI_Result> >::iterator aResIter = aResults.begin();
1830
1831         // searching by sub-shape
1832         for (; aResIter != aResults.end(); aResIter++) {
1833           if (!aResIter->get() || !(*aResIter)->data()->isValid() || (*aResIter)->isDisabled())
1834             continue;
1835           GeomShapePtr aShape = (*aResIter)->shape();
1836           if (aShape.get() && aShape->isSubShape(aSelectedShape, false)) {
1837             aResult = *aResIter; // found new context (produced from this) with same subshape
1838             aFindNewContext = true; // continue searching further
1839             break;
1840           }
1841         }
1842       }
1843     }
1844   }
1845   // if compsolid is context, try to take sub-solid as context: like in GUI and scripts
1846   ResultBodyPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aResult);
1847   if (aComp && aComp->numberOfSubs()) {
1848     std::list<ResultPtr> allSubs;
1849     ModelAPI_Tools::allSubs(aComp, allSubs);
1850     std::list<ResultPtr>::iterator aS = allSubs.begin();
1851     for (; aS != allSubs.end(); aS++) {
1852       ResultBodyPtr aSub = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aS);
1853       if (aSub && aSub->numberOfSubs() == 0 && aSub->shape().get() &&
1854           aSub->shape()->isSubShape(aSelectedShape)) {
1855         aResult = aSub;
1856         break;
1857       }
1858     }
1859   }
1860   // in case sketch line was selected for wire, but wire was concealed and not such line anymore,
1861   // so, actually, the sketch element was selected (which is never concealed)
1862   if (aResult != theCurrent && aResult->isConcealed())
1863     aResult = theCurrent;
1864   return aResult;
1865 }
1866
1867 void Model_AttributeSelection::combineGeometrical()
1868 {
1869   if (myTmpContext.get() || myTmpSubShape.get())
1870     return;
1871   TDF_Label aSelLab = selectionLabel();
1872   if (aSelLab.IsAttribute(kINVALID_SELECTION) || !myRef.isInitialized())
1873     return;
1874
1875   if (aSelLab.IsAttribute(kCIRCLE_CENTER) || aSelLab.IsAttribute(kELLIPSE_CENTER1) ||
1876       aSelLab.IsAttribute(kELLIPSE_CENTER2) || aSelLab.IsAttribute(kSIMPLE_REF_ID))
1877     return;
1878
1879   if (aSelLab.IsAttribute(kPART_REF_ID)) {
1880     ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
1881     if (!aPart.get() || !aPart->isActivated())
1882       return; // postponed naming needed
1883     Handle(TDataStd_Integer) anIndex;
1884     if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
1885       if (anIndex->Get()) { // special selection attribute was created, use it
1886         std::string aNewName;
1887         aPart->combineGeometrical(anIndex->Get(), aNewName);
1888         TDataStd_Name::Set(aSelLab, aNewName.c_str());
1889       }
1890     }
1891     return;
1892   }
1893
1894   std::shared_ptr<Model_ResultConstruction> aConstr =
1895     std::dynamic_pointer_cast<Model_ResultConstruction>(context());
1896   if (aConstr.get())
1897     return;
1898   FeaturePtr aFeature = contextFeature();
1899   if (aFeature.get())
1900     return;
1901
1902   Selector_Selector aSelector(aSelLab, baseDocumentLab());
1903   TopoDS_Shape aContextShape = context()->shape()->impl<TopoDS_Shape>();
1904   if (aSelector.restore(aContextShape)) {
1905     aSelector.combineGeometrical(aContextShape);
1906   }
1907 }
1908
1909 TDF_Label Model_AttributeSelection::baseDocumentLab()
1910 {
1911   if (ModelAPI_Session::get()->moduleDocument() != owner()->document())
1912     return std::dynamic_pointer_cast<Model_Document>
1913       (ModelAPI_Session::get()->moduleDocument())->extConstructionsLabel();
1914   static TDF_Label anEmpty;
1915   return anEmpty;
1916 }