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