Salome HOME
Fix for the issue #2450 : consequent creation of fillet requires extra click
[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_SelectionNaming.h"
27 #include <Model_Objects.h>
28 #include <Model_AttributeSelectionList.h>
29 #include <Model_ResultConstruction.h>
30 #include <ModelAPI_Feature.h>
31 #include <ModelAPI_ResultBody.h>
32 #include <ModelAPI_ResultCompSolid.h>
33 #include <ModelAPI_ResultConstruction.h>
34 #include <ModelAPI_ResultPart.h>
35 #include <ModelAPI_CompositeFeature.h>
36 #include <ModelAPI_Tools.h>
37 #include <ModelAPI_Session.h>
38 #include <ModelAPI_Validator.h>
39 #include <Events_InfoMessage.h>
40 #include <GeomAPI_Edge.h>
41 #include <GeomAPI_Vertex.h>
42
43 #include <TNaming_Selector.hxx>
44 #include <TNaming_NamedShape.hxx>
45 #include <TNaming_Tool.hxx>
46 #include <TNaming_Builder.hxx>
47 #include <TNaming_SameShapeIterator.hxx>
48 #include <TNaming_Iterator.hxx>
49 #include <TDataStd_Integer.hxx>
50 #include <TDataStd_UAttribute.hxx>
51 #include <TDataStd_Name.hxx>
52 #include <TopTools_ListOfShape.hxx>
53 #include <TopTools_DataMapOfShapeShape.hxx>
54 #include <TopTools_MapOfShape.hxx>
55 #include <TopExp_Explorer.hxx>
56 #include <BRep_Tool.hxx>
57 #include <TopoDS.hxx>
58 #include <TopExp.hxx>
59 #include <TDF_ChildIterator.hxx>
60 #include <TDF_ChildIDIterator.hxx>
61 #include <TopoDS_Iterator.hxx>
62 #include <TDF_ChildIDIterator.hxx>
63 #include <Geom_Circle.hxx>
64 #include <Geom_Ellipse.hxx>
65 #include <BRep_Builder.hxx>
66
67 //#define DEB_NAMING 1
68 #ifdef DEB_NAMING
69 #include <BRepTools.hxx>
70 #endif
71 /// added to the index in the packed map to signalize that the vertex of edge is selected
72 /// (multiplied by the index of the edge)
73 static const int kSTART_VERTEX_DELTA = 1000000;
74 // identifier that there is simple reference: selection equals to context
75 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
76 // reference to Part sub-object
77 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
78 // selection is invalid after recomputation
79 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
80
81 // identifier of the selection of the center of circle on edge
82 Standard_GUID kCIRCLE_CENTER("d0d0e0f1-217a-4b95-8fbb-0c4132f23718");
83 // identifier of the selection of the first focus point of ellipse on edge
84 Standard_GUID kELLIPSE_CENTER1("f70df04c-3168-4dc9-87a4-f1f840c1275d");
85 // identifier of the selection of the second focus point of ellipse on edge
86 Standard_GUID kELLIPSE_CENTER2("1395ae73-8e02-4cf8-b204-06ff35873a32");
87
88 // on this label is stored:
89 // TNaming_NamedShape - selected shape
90 // TNaming_Naming - topological selection information (for the body)
91 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
92 // TDataStd_Integer - type of the selected shape (for construction)
93 // TDF_Reference - from ReferenceAttribute, the context
94 bool Model_AttributeSelection::setValue(const ResultPtr& theContext,
95   const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
96 {
97   if (theTemporarily) { // just keep the stored without DF update
98     myTmpContext = theContext;
99     myTmpSubShape = theSubShape;
100     owner()->data()->sendAttributeUpdated(this);
101     return true;
102   } else {
103     myTmpContext.reset();
104     myTmpSubShape.reset();
105     myTmpCenterType = NOT_CENTER;
106   }
107
108   CenterType aType;
109   const std::shared_ptr<GeomAPI_Shape>& anOldShape = internalValue(aType);
110   bool isOldContext = theContext == myRef.value();
111   bool isOldShape = isOldContext &&
112     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
113   if (isOldShape) return false; // shape is the same, so context is also unchanged
114   // update the referenced object if needed
115   if (!isOldContext) {
116       myRef.setValue(theContext);
117   }
118
119   // do noth use naming if selected shape is result shape itself, but not sub-shape
120   TDF_Label aSelLab = selectionLabel();
121   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
122   aSelLab.ForgetAttribute(kINVALID_SELECTION);
123   aSelLab.ForgetAttribute(kCIRCLE_CENTER);
124   aSelLab.ForgetAttribute(kELLIPSE_CENTER1);
125   aSelLab.ForgetAttribute(kELLIPSE_CENTER2);
126
127   bool isDegeneratedEdge = false;
128   // do not use the degenerated edge as a shape, a null context and shape is used in the case
129   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
130     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
131     if (aSubShape.ShapeType() == TopAbs_EDGE)
132       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
133   }
134   if (!theContext.get() || isDegeneratedEdge) {
135     // to keep the reference attribute label
136     TDF_Label aRefLab = myRef.myRef->Label();
137     aSelLab.ForgetAllAttributes(true);
138     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
139     return false;
140   }
141   if (theContext->groupName() == ModelAPI_ResultBody::group()) {
142     // do not select the whole shape for body:it is already must be in the data framework
143     // equal and null selected objects mean the same: object is equal to context,
144     if (theContext->shape().get() &&
145         (theContext->shape()->isEqual(theSubShape) || !theSubShape.get())) {
146       aSelLab.ForgetAllAttributes(true);
147       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
148     } else {
149       selectBody(theContext, theSubShape);
150     }
151   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
152     aSelLab.ForgetAllAttributes(true); // to remove old selection data
153     std::shared_ptr<Model_ResultConstruction> aConstruction =
154       std::dynamic_pointer_cast<Model_ResultConstruction>(theContext);
155     std::shared_ptr<GeomAPI_Shape> aSubShape;
156     if (theSubShape.get() && !theContext->shape()->isEqual(theSubShape))
157       aSubShape = theSubShape; // the whole context
158     if (aConstruction->isInfinite()) {
159       // For correct naming selection, put the shape into the naming structure.
160       // It seems sub-shapes are not needed: only this shape is (and can be ) selected.
161       TNaming_Builder aBuilder(aSelLab);
162       aBuilder.Generated(theContext->shape()->impl<TopoDS_Shape>());
163     }
164     int anIndex = aConstruction->select(theSubShape, owner()->document());
165     TDataStd_Integer::Set(aSelLab, anIndex);
166   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
167     aSelLab.ForgetAllAttributes(true);
168     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
169     selectPart(theContext, theSubShape);
170   }
171
172   owner()->data()->sendAttributeUpdated(this);
173   return true;
174 }
175
176 void Model_AttributeSelection::setValueCenter(
177     const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Edge>& theEdge,
178     const CenterType theCenterType, const bool theTemporarily)
179 {
180   bool anUpdated = setValue(theContext, theEdge, theTemporarily);
181   if (theTemporarily) {
182     myTmpCenterType = theCenterType;
183   } else { // store in the data structure
184     TDF_Label aSelLab = selectionLabel();
185     switch(theCenterType) {
186     case CIRCLE_CENTER:
187       if (!anUpdated)
188         anUpdated = !aSelLab.IsAttribute(kCIRCLE_CENTER);
189       TDataStd_UAttribute::Set(aSelLab, kCIRCLE_CENTER);
190       break;
191     case ELLIPSE_FIRST_FOCUS:
192       if (!anUpdated)
193         anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER1);
194       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER1);
195       break;
196     case ELLIPSE_SECOND_FOCUS:
197       if (!anUpdated)
198         anUpdated = !aSelLab.IsAttribute(kELLIPSE_CENTER2);
199       TDataStd_UAttribute::Set(aSelLab, kELLIPSE_CENTER2);
200       break;
201     }
202     if (anUpdated)
203       owner()->data()->sendAttributeUpdated(this);
204   }
205 }
206
207 void Model_AttributeSelection::selectValue(
208     const std::shared_ptr<ModelAPI_AttributeSelection>& theSource)
209 {
210   CenterType aType;
211   std::shared_ptr<GeomAPI_Shape> aValue =
212     std::dynamic_pointer_cast<Model_AttributeSelection>(theSource)->internalValue(aType);
213   if (!aValue.get() || aType == NOT_CENTER) {
214     setValue(theSource->context(), aValue);
215   } else {
216     std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge);
217     anEdge->setImpl(new TopoDS_Shape(aValue->impl<TopoDS_Shape>()));
218     setValueCenter(theSource->context(), anEdge, aType);
219   }
220 }
221
222 void Model_AttributeSelection::removeTemporaryValues()
223 {
224   if (myTmpContext.get() || myTmpSubShape.get()) {
225     myTmpContext.reset();
226     myTmpSubShape.reset();
227   }
228 }
229
230 // returns the center of the edge: circular or elliptical
231 GeomShapePtr centerByEdge(GeomShapePtr theEdge, ModelAPI_AttributeSelection::CenterType theType)
232 {
233   if (theType != ModelAPI_AttributeSelection::NOT_CENTER && theEdge.get() != NULL) {
234     TopoDS_Shape aShape = theEdge->impl<TopoDS_Shape>();
235     if (!aShape.IsNull() && aShape.ShapeType() == TopAbs_EDGE) {
236       TopoDS_Edge anEdge = TopoDS::Edge(aShape);
237       double aFirst, aLast;
238       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
239       if (!aCurve.IsNull()) {
240         TopoDS_Vertex aVertex;
241         BRep_Builder aBuilder;
242         if (theType == ModelAPI_AttributeSelection::CIRCLE_CENTER) {
243           Handle(Geom_Circle) aCirc = Handle(Geom_Circle)::DownCast(aCurve);
244           if (!aCirc.IsNull()) {
245             aBuilder.MakeVertex(aVertex, aCirc->Location(), Precision::Confusion());
246           }
247         } else { // ellipse
248           Handle(Geom_Ellipse) anEll = Handle(Geom_Ellipse)::DownCast(aCurve);
249           if (!anEll.IsNull()) {
250             aBuilder.MakeVertex(aVertex,
251               theType == ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS ?
252               anEll->Focus1() : anEll->Focus2(), Precision::Confusion());
253           }
254         }
255         if (!aVertex.IsNull()) {
256           std::shared_ptr<GeomAPI_Vertex> aResult(new GeomAPI_Vertex);
257           aResult->setImpl(new TopoDS_Vertex(aVertex));
258           return aResult;
259         }
260       }
261     }
262   }
263   return theEdge; // no vertex, so, return the initial edge
264 }
265
266 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
267 {
268   CenterType aType = NOT_CENTER;
269   std::shared_ptr<GeomAPI_Shape> aResult = internalValue(aType);
270   return centerByEdge(aResult, aType);
271 }
272
273 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::internalValue(CenterType& theType)
274 {
275   theType = NOT_CENTER;
276   GeomShapePtr aResult;
277   if (myTmpContext.get() || myTmpSubShape.get()) {
278     theType = myTmpCenterType;
279     ResultConstructionPtr aResulConstruction =
280       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myTmpContext);
281     if(aResulConstruction.get()) {
282       // it is just reference to construction.
283       return myTmpSubShape;
284     }
285     return myTmpSubShape.get() ? myTmpSubShape : myTmpContext->shape();
286   }
287
288   TDF_Label aSelLab = selectionLabel();
289   if (aSelLab.IsAttribute(kINVALID_SELECTION))
290     return aResult;
291
292   if (aSelLab.IsAttribute(kCIRCLE_CENTER))
293     theType = CIRCLE_CENTER;
294   else if (aSelLab.IsAttribute(kELLIPSE_CENTER1))
295     theType = ELLIPSE_FIRST_FOCUS;
296   else if (aSelLab.IsAttribute(kELLIPSE_CENTER2))
297     theType = ELLIPSE_SECOND_FOCUS;
298
299
300   if (myRef.isInitialized()) {
301     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
302       ResultPtr aContext = context();
303       if (!aContext.get())
304         return aResult; // empty result
305       return aContext->shape();
306     }
307     if (aSelLab.IsAttribute(kPART_REF_ID)) {
308       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
309       if (!aPart.get() || !aPart->isActivated())
310         return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
311       Handle(TDataStd_Integer) anIndex;
312       if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
313         if (anIndex->Get()) { // special selection attribute was created, use it
314           return aPart->selectionValue(anIndex->Get());
315         } else { // face with name is already in the data model, so try to take it by name
316           Handle(TDataStd_Name) aName;
317           if (aSelLab.FindAttribute(TDataStd_Name::GetID(), aName)) {
318             std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
319             std::size_t aPartEnd = aSubShapeName.find('/');
320             if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
321               std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
322               int anIndex;
323               std::string aType; // to reuse already existing selection the type is not needed
324               return aPart->shapeInPart(aNameInPart, aType, anIndex);
325             }
326           }
327         }
328       }
329     }
330
331     std::shared_ptr<Model_ResultConstruction> aConstr =
332       std::dynamic_pointer_cast<Model_ResultConstruction>(context());
333     if (aConstr) {
334       if (aConstr->isInfinite())
335         return aResult; // empty result
336     }
337     Handle(TNaming_NamedShape) aSelection;
338     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
339       TopoDS_Shape aSelShape = aSelection->Get();
340       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
341       aResult->setImpl(new TopoDS_Shape(aSelShape));
342     } else if (aConstr) { // simple construction element: just shape of this construction element
343       Handle(TDataStd_Integer) anIndex;
344       if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
345         if (anIndex->Get() == 0) // it is just reference to construction, nothing is in value
346           return aResult;
347         return aConstr->shape(anIndex->Get(), owner()->document());
348       }
349     }
350   }
351   return aResult;
352 }
353
354 bool Model_AttributeSelection::isInvalid()
355 {
356   return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
357 }
358
359 bool Model_AttributeSelection::isInitialized()
360 {
361   if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
362     std::shared_ptr<GeomAPI_Shape> aResult;
363     if (myRef.isInitialized()) {
364       TDF_Label aSelLab = selectionLabel();
365       if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
366         ResultPtr aContext = context();
367         return aContext.get() != NULL;
368       }
369       Handle(TNaming_NamedShape) aSelection;
370       if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
371         return !aSelection->Get().IsNull();
372       } else { // for simple construction element: just shape of this construction element
373         std::shared_ptr<Model_ResultConstruction> aConstr =
374           std::dynamic_pointer_cast<Model_ResultConstruction>(context());
375         if (aConstr.get()) {
376           Handle(TDataStd_Integer) anIndex;
377           if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
378             // for the whole shape it may return null, so, if index exists, returns true
379             return true;
380           }
381         }
382       }
383     }
384   }
385   return false;
386 }
387
388 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
389   : myRef(theLabel)
390 {
391   myIsInitialized = myRef.isInitialized();
392   myParent = NULL;
393 }
394
395 void Model_AttributeSelection::setID(const std::string theID)
396 {
397   myRef.setID(theID);
398   ModelAPI_AttributeSelection::setID(theID);
399 }
400
401 ResultPtr Model_AttributeSelection::context() {
402   if (myTmpContext.get() || myTmpSubShape.get()) {
403     return myTmpContext;
404   }
405
406   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
407   // for parts there could be same-data result, so take the last enabled
408   if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
409     int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
410     for(int a = aSize - 1; a >= 0; a--) {
411       ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
412       if (aPart.get() && aPart->data() == aResult->data()) {
413         ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
414         FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
415         // check that this result is not this-feature result (it is forbidden t oselect itself)
416         if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
417           return aPartResult;
418         }
419       }
420     }
421   }
422   return aResult;
423 }
424
425
426 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
427 {
428   ModelAPI_AttributeSelection::setObject(theObject);
429   myRef.setObject(theObject);
430 }
431
432 TDF_LabelMap& Model_AttributeSelection::scope()
433 {
434   if (myScope.IsEmpty()) { // create a new scope if not yet done
435     // gets all features with named shapes that are before this feature label (before in history)
436     DocumentPtr aMyDoc = owner()->document();
437     std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
438     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
439     bool aMePassed = false;
440     CompositeFeaturePtr aComposite =
441       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
442     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
443     CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
444     if (aFeature.get()) {
445       aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
446       if (aCompositeOwner.get()) {
447          aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
448       }
449     }
450     // for group Scope is not limitet: this is always up to date objects
451     bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
452     for(; aFIter != allFeatures.end(); aFIter++) {
453       if (*aFIter == owner()) {  // the left features are created later (except subs of composite)
454         aMePassed = true;
455         continue;
456       }
457       if (isGroup) aMePassed = false;
458       bool isInScope = !aMePassed;
459       if (!isInScope && aComposite.get()) {
460         // try to add sub-elements of composite if this is composite
461         if (aComposite->isSub(*aFIter))
462           isInScope = true;
463       }
464       // remove the composite-owner of this feature (sketch in extrusion-cut)
465       if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
466         isInScope = false;
467
468       if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
469         TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
470           (*aFIter)->data())->label().Father();
471         TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), true);
472         for(; aNSIter.More(); aNSIter.Next()) {
473           Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
474           if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
475             myScope.Add(aNS->Label());
476           }
477         }
478       }
479     }
480     // also add all naming labels created for external constructions
481     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(aMyDoc);
482     TDF_Label anExtDocLab = aDoc->extConstructionsLabel();
483     TDF_ChildIDIterator aNSIter(anExtDocLab, TNaming_NamedShape::GetID(), true);
484     for(; aNSIter.More(); aNSIter.Next()) {
485       Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
486       if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
487         myScope.Add(aNS->Label());
488       }
489     }
490   }
491   return myScope;
492 }
493
494 /// Sets the invalid flag if flag is false, or removes it if "true"
495 /// Returns theFlag
496 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
497   if (theFlag) {
498     theLab.ForgetAttribute(kINVALID_SELECTION);
499   } else {
500     TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
501   }
502   return theFlag;
503 }
504
505 void Model_AttributeSelection::split(
506   ResultPtr theContext, TopoDS_Shape theNewShape, TopAbs_ShapeEnum theType)
507 {
508   TopTools_ListOfShape aSubs;
509   for(TopoDS_Iterator anExplorer(theNewShape); anExplorer.More(); anExplorer.Next()) {
510     if (!anExplorer.Value().IsNull() &&
511       anExplorer.Value().ShapeType() == theType) {
512         aSubs.Append(anExplorer.Value());
513     } else { // invalid case; bad result shape, so, impossible to split easily
514       aSubs.Clear();
515       break;
516     }
517   }
518   if (aSubs.Extent() > 1) { // ok to split
519     TopTools_ListIteratorOfListOfShape aSub(aSubs);
520     GeomShapePtr aSubSh(new GeomAPI_Shape);
521     aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
522     setValue(theContext, aSubSh);
523     for(aSub.Next(); aSub.More(); aSub.Next()) {
524       GeomShapePtr aSubSh(new GeomAPI_Shape);
525       aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
526       myParent->append(theContext, aSubSh);
527     }
528   }
529 }
530
531 bool Model_AttributeSelection::update()
532 {
533   TDF_Label aSelLab = selectionLabel();
534   ResultPtr aContext = context();
535   if (!aContext.get())
536     return setInvalidIfFalse(aSelLab, false);
537   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
538     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
539   }
540
541   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
542     std::shared_ptr<GeomAPI_Shape> aNoSelection;
543     bool aResult = selectPart(aContext, aNoSelection, true);
544     aResult = setInvalidIfFalse(aSelLab, aResult);
545     if (aResult) {
546       owner()->data()->sendAttributeUpdated(this);
547     }
548     return aResult;
549   }
550
551   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
552     // body: just a named shape, use selection mechanism from OCCT
553     TNaming_Selector aSelector(aSelLab);
554     TopoDS_Shape anOldShape;
555     if (!aSelector.NamedShape().IsNull()) {
556       anOldShape = aSelector.NamedShape()->Get();
557     }
558     bool aResult = aSelector.Solve(scope()) == Standard_True;
559     // must be before sending of updated attribute (1556)
560     aResult = setInvalidIfFalse(aSelLab, aResult);
561     TopoDS_Shape aNewShape;
562     if (!aSelector.NamedShape().IsNull()) {
563       aNewShape = aSelector.NamedShape()->Get();
564     }
565     if (anOldShape.IsNull() || aNewShape.IsNull() ||
566         !anOldShape.IsEqual(aSelector.NamedShape()->Get())) {
567       // shape type shoud not not changed: if shape becomes compound of such shapes, then split
568       if (myParent && !anOldShape.IsNull() && !aNewShape.IsNull() &&
569           anOldShape.ShapeType() != aNewShape.ShapeType() &&
570           (aNewShape.ShapeType() == TopAbs_COMPOUND || aNewShape.ShapeType() == TopAbs_COMPSOLID))
571       {
572         split(aContext, aNewShape, anOldShape.ShapeType());
573       }
574       owner()->data()->sendAttributeUpdated(this);  // send updated if shape is changed
575     }
576     return aResult;
577   }
578
579   if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
580     Handle(TDataStd_Integer) anIndex;
581     if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
582       std::shared_ptr<Model_ResultConstruction> aConstructionContext =
583         std::dynamic_pointer_cast<Model_ResultConstruction>(aContext);
584       bool aModified = true;
585       bool aValid = aConstructionContext->update(anIndex->Get(), owner()->document(), aModified);
586       setInvalidIfFalse(aSelLab, aValid);
587       if (aConstructionContext->isInfinite()) {
588         // Update the selected shape.
589         TNaming_Builder aBuilder(aSelLab);
590         aBuilder.Generated(aConstructionContext->shape()->impl<TopoDS_Shape>());
591       }
592       if (aModified)
593         owner()->data()->sendAttributeUpdated(this);
594       return aValid;
595     }
596   }
597   return setInvalidIfFalse(aSelLab, false); // unknown case
598 }
599
600 void Model_AttributeSelection::selectBody(
601   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
602 {
603   // perform the selection
604   TNaming_Selector aSel(selectionLabel());
605   TopoDS_Shape aContext;
606
607   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theContext);//myRef.value()
608   if (aBody) {
609     aContext = aBody->shape()->impl<TopoDS_Shape>();
610   } else {
611     ResultPtr aResult =
612       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
613     if (aResult) {
614       aContext = aResult->shape()->impl<TopoDS_Shape>();
615     } else {
616       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
617       return;
618     }
619   }
620
621   // with "recover" feature the selected context may be not up to date (issue 1710)
622   Handle(TNaming_NamedShape) aResult;
623   TDF_Label aSelLab = selectionLabel();
624   TopoDS_Shape aNewContext = aContext;
625   bool isUpdated = true;
626   while(!aNewContext.IsNull() && isUpdated) {
627     // searching for the very last shape that was produced from this one
628     isUpdated = false;
629     if (!TNaming_Tool::HasLabel(aSelLab, aNewContext))
630       // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
631       break;
632     for(TNaming_SameShapeIterator anIter(aNewContext, aSelLab); anIter.More(); anIter.Next()) {
633       TDF_Label aNSLab = anIter.Label();
634       if (!scope().Contains(aNSLab))
635         continue;
636       Handle(TNaming_NamedShape) aNS;
637       if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
638         for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
639           if (aShapesIter.Evolution() == TNaming_SELECTED)
640             continue; // don't use the selection evolution
641           if (!aShapesIter.OldShape().IsNull() && aShapesIter.OldShape().IsSame(aNewContext)) {
642              // found the original shape
643             aNewContext = aShapesIter.NewShape(); // go to the newer shape
644             isUpdated = true;
645             break;
646           }
647         }
648       }
649     }
650   }
651   if (aNewContext.IsNull()) { // a context is already deleted
652     setInvalidIfFalse(aSelLab, false);
653     Events_InfoMessage("Model_AttributeSelection", "Failed to select shape already deleted").send();
654     return;
655   }
656
657   TopoDS_Shape aNewSub = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
658   if (!aNewSub.IsEqual(aContext)) { // searching for subshape in the new context
659     bool isFound = false;
660     TopExp_Explorer anExp(aNewContext, aNewSub.ShapeType());
661     for(; anExp.More(); anExp.Next()) {
662       if (anExp.Current().IsSame(aNewSub)) {
663         isFound = true;
664         break;
665       }
666     }
667     if (!isFound) { // sub-shape is not found in the up-to-date instance of the context shape
668       // if context is sub-result of compound/compsolid, selection of sub-shape better propagate to
669       // the main result (which is may be modified), case is in 1799
670       ResultCompSolidPtr aMain = ModelAPI_Tools::compSolidOwner(theContext);
671       if (aMain.get()) {
672         selectBody(aMain, theSubShape);
673         return;
674       }
675       setInvalidIfFalse(aSelLab, false);
676       Events_InfoMessage("Model_AttributeSelection",
677         "Failed to select sub-shape already modified").send();
678       return;
679     }
680   }
681
682   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
683   if (!aContext.IsNull()) {
684     FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
685     bool aEraseResults = false;
686     if (aFeatureOwner.get()) {
687       aEraseResults = !aFeatureOwner->results().empty();
688       if (aEraseResults) // erase results without flash deleted and redisplay: do it after Select
689         aFeatureOwner->removeResults(0, false, false);
690     }
691     aSel.Select(aNewSub, aNewContext);
692
693     if (aEraseResults) { // flash after Select : in Groups it makes selection with shift working
694       static Events_Loop* aLoop = Events_Loop::loop();
695       static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
696       aLoop->flush(kDeletedEvent);
697     }
698   }
699 }
700
701 bool Model_AttributeSelection::selectPart(
702   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
703   const bool theUpdate)
704 {
705   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
706   if (!aPart.get() || !aPart->isActivated())
707     return true; // postponed naming
708   if (theUpdate) {
709     Handle(TDataStd_Integer) anIndex;
710     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
711       // by internal selection
712       if (anIndex->Get() > 0) {
713         // update the selection by index
714         return aPart->updateInPart(anIndex->Get());
715       } else {
716         return true; // nothing to do, referencing just by name
717       }
718     }
719     return true; // nothing to do, referencing just by name
720   }
721   // store the shape (in case part is not loaded it should be useful
722   TopoDS_Shape aShape;
723   std::string aName = theContext->data()->name();
724   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
725     aShape = theContext->shape()->impl<TopoDS_Shape>();
726   } else {
727     aShape = theSubShape->impl<TopoDS_Shape>();
728     int anIndex;
729     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
730     TDataStd_Integer::Set(selectionLabel(), anIndex);
731   }
732   TNaming_Builder aBuilder(selectionLabel());
733   aBuilder.Select(aShape, aShape);
734   // identify by name in the part
735   TDataStd_Name::Set(selectionLabel(), aName.c_str());
736   return !aName.empty();
737 }
738
739 TDF_Label Model_AttributeSelection::selectionLabel()
740 {
741   return myRef.myRef->Label().FindChild(1);
742 }
743
744 /// prefixes of the shape names with centers defined
745 static std::map<ModelAPI_AttributeSelection::CenterType, std::string> kCENTERS_PREFIX;
746
747 /// returns the map that contains all possible prefixes of the center-names
748 static std::map<ModelAPI_AttributeSelection::CenterType, std::string>& centersMap()
749 {
750   if (kCENTERS_PREFIX.empty()) { // fill map by initial values
751     kCENTERS_PREFIX[ModelAPI_AttributeSelection::CIRCLE_CENTER] = "__cc";
752     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_FIRST_FOCUS] = "__eff";
753     kCENTERS_PREFIX[ModelAPI_AttributeSelection::ELLIPSE_SECOND_FOCUS] = "__esf";
754   }
755   return kCENTERS_PREFIX;
756 }
757
758 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
759 {
760   std::string aName("");
761   if(!this->isInitialized())
762     return !theDefaultName.empty() ? theDefaultName : aName;
763
764   CenterType aCenterType = NOT_CENTER;
765   std::shared_ptr<GeomAPI_Shape> aSubSh = internalValue(aCenterType);
766   ResultPtr aCont = context();
767
768   if (!aCont.get()) // in case of selection of removed result
769     return "";
770
771   Model_SelectionNaming aSelNaming(selectionLabel());
772   std::string aResult = aSelNaming.namingName(
773     aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
774   if (aCenterType != NOT_CENTER) {
775     aResult += centersMap()[aCenterType];
776   }
777   return aResult;
778 }
779
780 // returns the center type and modifies the shape name if this name is center-name
781 static ModelAPI_AttributeSelection::CenterType centerTypeByName(std::string& theShapeName)
782 {
783   std::map<ModelAPI_AttributeSelection::CenterType, std::string>::iterator aPrefixIter =
784     centersMap().begin();
785   for(; aPrefixIter != centersMap().end(); aPrefixIter++) {
786     std::size_t aFound = theShapeName.find(aPrefixIter->second);
787     if (aFound != std::string::npos &&
788         aFound == theShapeName.size() - aPrefixIter->second.size()) {
789       theShapeName = theShapeName.substr(0, aFound);
790       return aPrefixIter->first;
791     }
792   }
793   return ModelAPI_AttributeSelection::NOT_CENTER;
794 }
795
796 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
797 void Model_AttributeSelection::selectSubShape(
798   const std::string& theType, const std::string& theSubShapeName)
799 {
800   if(theSubShapeName.empty() || theType.empty()) return;
801
802   std::string aSubShapeName = theSubShapeName;
803   CenterType aCenterType = theType[0] == 'v' || theType[0] == 'V' ? // only for vertex-type
804     centerTypeByName(aSubShapeName) : NOT_CENTER;
805   std::string aType = aCenterType == NOT_CENTER ? theType : "EDGE"; // search for edge now
806
807   // first iteration is selection by name without center prefix, second - in case of problem,
808   // try with initial name
809   for(int aUseCenter = 1; aUseCenter >= 0; aUseCenter--) {
810     if (aUseCenter == 0 && aCenterType != NOT_CENTER) {
811       aSubShapeName = theSubShapeName;
812       aCenterType = NOT_CENTER;
813       aType = theType;
814     } else if (aUseCenter != 1) continue;
815
816     // check this is Part-name: 2 delimiters in the name
817     std::size_t aPartEnd = aSubShapeName.find('/');
818     if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
819       std::string aPartName = aSubShapeName.substr(0, aPartEnd);
820       ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
821       if (aFound.get()) { // found such part, so asking it for the name
822         ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
823         std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
824         int anIndex;
825         std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, aType, anIndex);
826         if (aSelected.get()) {
827           if (aCenterType != NOT_CENTER) {
828             if (!aSelected->isEdge())
829               continue;
830             std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aSelected));
831             setValueCenter(aPart, aSelectedEdge, aCenterType);
832           } else
833             setValue(aPart, aSelected);
834           TDataStd_Integer::Set(selectionLabel(), anIndex);
835           return;
836         }
837       }
838     }
839
840     Model_SelectionNaming aSelNaming(selectionLabel());
841     std::shared_ptr<Model_Document> aDoc =
842       std::dynamic_pointer_cast<Model_Document>(owner()->document());
843     std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
844     ResultPtr aCont;
845     if (aSelNaming.selectSubShape(aType, aSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
846       // try to find the last context to find the up to date shape
847       if (aCont->shape().get() && !aCont->shape()->isNull() &&
848         aCont->groupName() == ModelAPI_ResultBody::group() && aDoc == owner()->document()) {
849         const TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
850         if (!aConShape.IsNull()) {
851           Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
852           if (!aNS.IsNull()) {
853             aNS = TNaming_Tool::CurrentNamedShape(aNS);
854             if (!aNS.IsNull() && scope().Contains(aNS->Label())) { // scope check is for 2228
855               TDF_Label aLab = aNS->Label();
856               while(aLab.Depth() != 7 && aLab.Depth() > 5)
857                 aLab = aLab.Father();
858               ObjectPtr anObj = aDoc->objects()->object(aLab);
859               if (anObj.get()) {
860                 ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
861                 if (aRes)
862                   aCont = aRes;
863               }
864             }
865           }
866         }
867       }
868       // if compsolid is context, try to take sub-solid as context: like in GUI and scripts
869       if (aCont.get() && aShapeToBeSelected.get()) {
870         ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aCont);
871         if (aComp && aComp->numberOfSubs()) {
872           for(int aSubNum = 0; aSubNum < aComp->numberOfSubs(); aSubNum++) {
873             ResultPtr aSub = aComp->subResult(aSubNum);
874             if (aSub && aSub->shape().get() && aSub->shape()->isSubShape(aShapeToBeSelected)) {
875               aCont = aSub;
876               break;
877             }
878           }
879         }
880       }
881       // try to find the latest active result that must be used instead of the selected
882       // to set the active context (like in GUI selection), not concealed one
883       bool aFindNewContext = true;
884       while(aFindNewContext && aCont.get()) {
885         aFindNewContext = false;
886         // take references to all results: root one, any sub
887         ResultCompSolidPtr aCompContext = ModelAPI_Tools::compSolidOwner(aCont);
888         int aSubsSize = (aCompContext.get() ? aCompContext->numberOfSubs() : 0) + 1;
889         for(int aResultNum = 0; aResultNum < aSubsSize; aResultNum++) {
890           ResultPtr aResCont = aCont;
891           if (aCompContext.get())
892             if (aResultNum == aSubsSize - 1)
893               aResCont = aCompContext;
894             else aResCont = aCompContext->subResult(aResultNum);
895           const std::set<AttributePtr>& aRefs = aResCont->data()->refsToMe();
896           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
897           for(; !aFindNewContext && aRef != aRefs.end(); aRef++) {
898             if (!aRef->get() || !(*aRef)->owner().get())
899               continue;
900             // concealed attribute only
901             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
902             if (!ModelAPI_Session::get()->validators()->isConcealed(
903               aRefFeat->getKind(), (*aRef)->id()))
904               continue;
905             // search the feature result that contains sub-shape selected
906             std::list<std::shared_ptr<ModelAPI_Result> > aResults;
907
908             // take all sub-results or one result
909             const std::list<std::shared_ptr<ModelAPI_Result> >& aFResults = aRefFeat->results();
910             std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aFResults.begin();
911             for (; aRIter != aFResults.cend(); aRIter++) {
912               // iterate sub-bodies of compsolid
913               ResultCompSolidPtr aComp =
914                 std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRIter);
915               if (aComp.get() && aComp->numberOfSubs() > 0) {
916                 int aNumSub = aComp->numberOfSubs();
917                 for(int a = 0; a < aNumSub; a++) {
918                   aResults.push_back(aComp->subResult(a));
919                 }
920               } else {
921                 aResults.push_back(*aRIter);
922               }
923             }
924             std::list<std::shared_ptr<ModelAPI_Result> >::iterator aResIter = aResults.begin();
925             for(; aResIter != aResults.end(); aResIter++) {
926               if (!aResIter->get() || !(*aResIter)->data()->isValid() || (*aResIter)->isDisabled())
927                 continue;
928               GeomShapePtr aShape = (*aResIter)->shape();
929               GeomShapePtr aSelectedShape =
930                 aShapeToBeSelected.get() ? aShapeToBeSelected : aCont->shape();
931               if (aShape.get() && aShape->isSubShape(aSelectedShape, false)) {
932                 aCont = *aResIter; // found new context (produced from this) with same subshape
933                 //if (!aShape->isSubShape(aShapeToBeSelected, true)) // take context orientation
934                 //  aShapeToBeSelected->setOrientation();
935                 aFindNewContext = true; // continue searching futher
936                 break;
937               }
938             }
939           }
940         }
941       }
942
943       if (aCenterType != NOT_CENTER) {
944         if (!aShapeToBeSelected->isEdge())
945           continue;
946         std::shared_ptr<GeomAPI_Edge> aSelectedEdge(new GeomAPI_Edge(aShapeToBeSelected));
947         setValueCenter(aCont, aSelectedEdge, aCenterType);
948       } else
949         setValue(aCont, aShapeToBeSelected);
950       return;
951     }
952   }
953
954   TDF_Label aSelLab = selectionLabel();
955   setInvalidIfFalse(aSelLab, false);
956   reset();
957 }
958
959 int Model_AttributeSelection::Id()
960 {
961   int anID = 0;
962   std::shared_ptr<GeomAPI_Shape> aSelection = value();
963   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
964   // support for compsolids:
965   if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
966     aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
967
968
969   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
970   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
971   // searching for the latest main shape
972   if (aSelection && !aSelection->isNull() &&
973     aContext   && !aContext->isNull())
974   {
975     std::shared_ptr<Model_Document> aDoc =
976       std::dynamic_pointer_cast<Model_Document>(context()->document());
977     if (aDoc.get()) {
978       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
979       if (!aNS.IsNull()) {
980         aMainShape = TNaming_Tool::CurrentShape(aNS);
981       }
982     }
983
984     TopTools_IndexedMapOfShape aSubShapesMap;
985     TopExp::MapShapes(aMainShape, aSubShapesMap);
986     anID = aSubShapesMap.FindIndex(aSubShape);
987   }
988   return anID;
989 }
990
991 void Model_AttributeSelection::setId(int theID)
992 {
993   const ResultPtr& aContext = context();
994   std::shared_ptr<GeomAPI_Shape> aSelection;
995
996   std::shared_ptr<GeomAPI_Shape> aContextShape = aContext->shape();
997   // support for compsolids:
998   if (aContext.get() && ModelAPI_Tools::compSolidOwner(aContext).get())
999     aContextShape = ModelAPI_Tools::compSolidOwner(aContext)->shape();
1000
1001   TopoDS_Shape aMainShape = aContextShape->impl<TopoDS_Shape>();
1002   // searching for the latest main shape
1003   if (theID > 0 &&
1004       aContextShape && !aContextShape->isNull())
1005   {
1006     std::shared_ptr<Model_Document> aDoc =
1007       std::dynamic_pointer_cast<Model_Document>(aContext->document());
1008     if (aDoc.get()) {
1009       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
1010       if (!aNS.IsNull()) {
1011         aMainShape = TNaming_Tool::CurrentShape(aNS);
1012       }
1013     }
1014
1015     TopTools_IndexedMapOfShape aSubShapesMap;
1016     TopExp::MapShapes(aMainShape, aSubShapesMap);
1017     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
1018
1019     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
1020     aResult->setImpl(new TopoDS_Shape(aSelShape));
1021
1022     aSelection = aResult;
1023   }
1024
1025   setValue(aContext, aSelection);
1026 }
1027
1028 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
1029 {
1030   std::string aResult;
1031   if (owner()->document() != theContext->document()) {
1032     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
1033       aResult = theContext->document()->kind() + "/";
1034     } else {
1035       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
1036         ModelAPI_Session::get()->moduleDocument(), theContext->document());
1037       if (aDocRes.get()) {
1038         aResult = aDocRes->data()->name() + "/";
1039       }
1040     }
1041   }
1042   aResult += theContext->data()->name();
1043   return aResult;
1044 }
1045
1046 void Model_AttributeSelection::computeValues(
1047   ResultPtr theOldContext, ResultPtr theNewContext, TopoDS_Shape theValShape,
1048   TopTools_ListOfShape& theShapes)
1049 {
1050   bool aWasWholeContext = theValShape.IsNull();
1051   if (aWasWholeContext) {
1052     //theShapes.Append(theValShape);
1053     //return;
1054     theValShape = theOldContext->shape()->impl<TopoDS_Shape>();
1055   }
1056   //TopoDS_Shape anOldContShape = theOldContext->shape()->impl<TopoDS_Shape>();
1057   TopoDS_Shape aNewContShape = theNewContext->shape()->impl<TopoDS_Shape>();
1058   //if (anOldContShape.IsSame(theValShape)) { // full context shape substituted by new full context
1059     //theShapes.Append(aNewContShape);
1060     //return;
1061   //}
1062   // if a new value is unchanged in the new context, do nothing: value is correct
1063   TopExp_Explorer aSubExp(aNewContShape, theValShape.ShapeType());
1064   for(; aSubExp.More(); aSubExp.Next()) {
1065     if (aSubExp.Current().IsSame(theValShape)) {
1066       theShapes.Append(theValShape);
1067       return;
1068     }
1069   }
1070   // if new context becomes compsolid, the resulting sub may be in sub-solids
1071   std::list<ResultPtr> aNewToIterate;
1072   aNewToIterate.push_back(theNewContext);
1073   ResultCompSolidPtr aComp = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theNewContext);
1074   if (aComp.get()) {
1075     for(int a = 0; a < aComp->numberOfSubs(); a++)
1076       aNewToIterate.push_back(aComp->subResult(a, false));
1077   }
1078
1079   // first iteration: searching for the whole shape appearance (like face of the box)
1080   // second iteration: searching for sub-shapes that contain the sub (like vertex on faces)
1081   int aToFindPart = 0;
1082   TopTools_DataMapOfShapeShape aNewToOld; // map from new containers to old containers (with val)
1083   TopTools_MapOfShape anOlds; // to know how many olds produced new containers
1084   for(; aToFindPart != 2 && theShapes.IsEmpty(); aToFindPart++) {
1085     std::list<ResultPtr>::iterator aNewContIter = aNewToIterate.begin();
1086     for(; aNewContIter != aNewToIterate.end(); aNewContIter++) {
1087       std::shared_ptr<Model_Data> aNewData =
1088         std::dynamic_pointer_cast<Model_Data>((*aNewContIter)->data());
1089       TDF_Label aNewLab = aNewData->label();
1090       // searching for produced sub-shape fully on some label
1091       TDF_ChildIDIterator aNSIter(aNewLab, TNaming_NamedShape::GetID(), Standard_True);
1092       for(; aNSIter.More(); aNSIter.Next()) {
1093         Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
1094         for(TNaming_Iterator aPairIter(aNS); aPairIter.More(); aPairIter.Next()) {
1095           if (aToFindPart == 0) { // search shape is fully inside
1096             if (aPairIter.OldShape().IsSame(theValShape)) {
1097               if (aPairIter.NewShape().IsNull()) {// value was removed
1098                 theShapes.Clear();
1099                 return;
1100               }
1101               theShapes.Append(aPairIter.NewShape());
1102             }
1103           } else if (!aPairIter.OldShape().IsNull()) { // search shape that contains this sub
1104             TopExp_Explorer anExp(aPairIter.OldShape(), theValShape.ShapeType());
1105             for(; anExp.More(); anExp.Next()) {
1106               if (anExp.Current().IsSame(theValShape)) { // found a new container
1107                 if (aPairIter.NewShape().IsNull()) {// value was removed
1108                   theShapes.Clear();
1109                   return;
1110                 }
1111                 aNewToOld.Bind(aPairIter.NewShape(), aPairIter.OldShape());
1112                 anOlds.Add(aPairIter.OldShape());
1113                 break;
1114               }
1115             }
1116           }
1117         }
1118       }
1119     }
1120   }
1121   if (aToFindPart == 2 && !aNewToOld.IsEmpty()) {
1122     // map of sub-shapes -> number of occurences of these shapes in containers
1123     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher> aSubs;
1124     TopTools_DataMapOfShapeShape::Iterator aContIter(aNewToOld);
1125     for(; aContIter.More(); aContIter.Next()) {
1126       TopExp_Explorer aSubExp(aContIter.Key(), theValShape.ShapeType());
1127       for(; aSubExp.More(); aSubExp.Next()) {
1128         if (!aSubs.IsBound(aSubExp.Current())) {
1129           aSubs.Bind(aSubExp.Current(), TopTools_MapOfShape());
1130         }
1131         // store old to know how many olds produced this shape
1132         aSubs.ChangeFind(aSubExp.Current()).Add(aContIter.Value());
1133       }
1134     }
1135     // if sub is appeared same times in containers as the number of old shapes that contain it
1136     int aCountInOld = anOlds.Size();
1137     NCollection_DataMap<TopoDS_Shape, TopTools_MapOfShape, TopTools_ShapeMapHasher>::Iterator
1138       aSubsIter(aSubs);
1139     for(; aSubsIter.More(); aSubsIter.Next()) {
1140       if (aSubsIter.Value().Size() == aCountInOld) {
1141         theShapes.Append(aSubsIter.Key());
1142       }
1143     }
1144   }
1145   if (theShapes.IsEmpty()) { // nothing was changed
1146     theShapes.Append(aWasWholeContext ? TopoDS_Shape() : theValShape);
1147   }
1148 }
1149
1150 bool Model_AttributeSelection::searchNewContext(std::shared_ptr<Model_Document> theDoc,
1151   const TopoDS_Shape theContShape, ResultPtr theContext, TopoDS_Shape theValShape,
1152   TDF_Label theAccessLabel,
1153   std::list<ResultPtr>& theResults, TopTools_ListOfShape& theValShapes)
1154 {
1155   std::set<ResultPtr> aResults; // to avoid duplicates, new context, null if deleted
1156   TopTools_ListOfShape aResContShapes;
1157   // iterate context and shape, but also if it is sub-shape of main shape, check also it
1158   TopTools_ListOfShape aContextList;
1159   aContextList.Append(theContShape);
1160   if (theContext.get()) {
1161     ResultPtr aComposite = ModelAPI_Tools::compSolidOwner(theContext);
1162     if (aComposite.get() && aComposite->shape().get() && !aComposite->shape()->isNull())
1163       aContextList.Append(aComposite->shape()->impl<TopoDS_Shape>());
1164   }
1165   for(TopTools_ListOfShape::Iterator aContIter(aContextList); aContIter.More(); aContIter.Next()) {
1166     TNaming_SameShapeIterator aModifIter(aContIter.ChangeValue(), theAccessLabel);
1167     for(; aModifIter.More(); aModifIter.Next()) {
1168       TDF_Label anObjLab = aModifIter.Label().Father();
1169       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1170         (theDoc->objects()->object(anObjLab));
1171       if (!aModifierObj.get()) {
1172         // #2241: shape may be sub-element of new object, not main (shell created from faces)
1173         if (!anObjLab.IsRoot())
1174           aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
1175           (theDoc->objects()->object(anObjLab.Father()));
1176         if (!aModifierObj.get())
1177           continue;
1178       }
1179       FeaturePtr aModifierFeat = theDoc->feature(aModifierObj);
1180       if (!aModifierFeat.get())
1181         continue;
1182       FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1183       if (aModifierFeat == aThisFeature || theDoc->objects()->isLater(aModifierFeat, aThisFeature))
1184         continue; // the modifier feature is later than this, so, should not be used
1185       FeaturePtr aCurrentModifierFeat = theDoc->feature(theContext);
1186       if (aCurrentModifierFeat == aModifierFeat ||
1187         theDoc->objects()->isLater(aCurrentModifierFeat, aModifierFeat))
1188         continue; // the current modifier is later than the found, so, useless
1189       Handle(TNaming_NamedShape) aNewNS;
1190       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
1191       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
1192         aResults.insert(aModifierObj);
1193         //TNaming_Iterator aPairIter(aNewNS);
1194         //aResContShapes.Append(aPairIter.NewShape());
1195         aResContShapes.Append(aModifierObj->shape()->impl<TopoDS_Shape>());
1196       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is empty
1197         aResults.insert(ResultPtr());
1198       } else { // not-precessed modification => don't support it
1199         continue;
1200       }
1201     }
1202   }
1203   if (aResults.empty())
1204     return false; // no modifications found, must stay the same
1205   // iterate all results to find futher modifications
1206   std::set<ResultPtr>::iterator aResIter = aResults.begin();
1207   for(; aResIter != aResults.end(); aResIter++) {
1208     if (aResIter->get() != NULL) {
1209       // compute new values by two contextes: the old and the new
1210       TopTools_ListOfShape aValShapes;
1211       computeValues(theContext, *aResIter, theValShape, aValShapes);
1212
1213       TopTools_ListIteratorOfListOfShape aNewVal(aValShapes);
1214       for(; aNewVal.More(); aNewVal.Next()) {
1215         std::list<ResultPtr> aNewRes;
1216         TopTools_ListOfShape aNewUpdatedVal;
1217         TopoDS_Shape aNewValSh = aNewVal.Value();
1218         TopoDS_Shape aNewContShape = (*aResIter)->shape()->impl<TopoDS_Shape>();
1219         if (theValShape.IsNull() && aNewContShape.IsSame(aNewValSh))
1220           aNewValSh.Nullify();
1221         if (searchNewContext(theDoc, aNewContShape, *aResIter, aNewValSh,
1222                              theAccessLabel, aNewRes, aNewUpdatedVal))
1223         {
1224           // appeand new results instead of the current ones
1225           std::list<ResultPtr>::iterator aNewIter = aNewRes.begin();
1226           TopTools_ListIteratorOfListOfShape aNewUpdVal(aNewUpdatedVal);
1227           for(; aNewIter != aNewRes.end(); aNewIter++, aNewUpdVal.Next()) {
1228             theResults.push_back(*aNewIter);
1229             theValShapes.Append(aNewUpdVal.Value());
1230           }
1231         } else { // the current result is good
1232           theResults.push_back(*aResIter);
1233           theValShapes.Append(aNewValSh);
1234         }
1235       }
1236     }
1237   }
1238   return true; // theResults must be empty: everything is deleted
1239 }
1240
1241 void Model_AttributeSelection::updateInHistory()
1242 {
1243   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
1244   // only bodies and parts may be modified later in the history, don't do anything otherwise
1245   if (!aContext.get() || (aContext->groupName() != ModelAPI_ResultBody::group() &&
1246       aContext->groupName() != ModelAPI_ResultPart::group()))
1247     return;
1248   std::shared_ptr<Model_Document> aDoc =
1249     std::dynamic_pointer_cast<Model_Document>(aContext->document());
1250   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
1251   if (!aContData.get() || !aContData->isValid())
1252     return;
1253   TDF_Label aContLab = aContData->label(); // named shape where the selected context is located
1254   Handle(TNaming_NamedShape) aContNS;
1255   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS)) {
1256     bool aFoundNewContext = true;
1257     ResultPtr aNewContext = aContext;
1258     while(aFoundNewContext) {
1259       aFoundNewContext = false;
1260       // parts have no shape in result, so, trace references using the Part info
1261       if (aNewContext->groupName() == ModelAPI_ResultPart::group()) {
1262         ResultPartPtr aPartContext = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aNewContext);
1263         if (aPartContext.get()) { // searching for the up to date references to the referenced cont
1264           const std::set<AttributePtr>& aRefs = aPartContext->data()->refsToMe();
1265           std::set<AttributePtr>::const_iterator aRef = aRefs.begin();
1266           for(; aRef != aRefs.end(); aRef++) {
1267             // to avoid detection of part changes by local selection only
1268             AttributeSelectionPtr aSel =
1269               std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(*aRef);
1270             if (aSel.get() && !aSel->value()->isSame(aSel->context()->shape()))
1271               continue;
1272
1273             FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRef)->owner());
1274             if (aRefFeat.get() && aRefFeat != owner()) {
1275               FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1276               if (aDoc->objects()->isLater(aThisFeature, aRefFeat)) { // found better feature
1277                 aFoundNewContext = true;
1278                 aNewContext = aRefFeat->firstResult();
1279               }
1280             }
1281           }
1282         }
1283       }
1284     }
1285     if (aNewContext != aContext) {
1286       setValue(aNewContext, value());
1287     }
1288     return;
1289   }
1290   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
1291   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
1292   // iterate the context shape modifications in order to find a feature that is upper in history
1293   // that this one and is really modifies the referenced result to refer to it
1294   ResultPtr aModifierResFound;
1295   TNaming_Iterator aPairIter(aContNS);
1296   if (!aPairIter.More())
1297     return;
1298   TopoDS_Shape aNewCShape = aPairIter.NewShape();
1299   bool anIterate = true;
1300   // trying to update also the sub-shape selected
1301   GeomShapePtr aSubShape = value();
1302   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
1303     aSubShape.reset();
1304   TopoDS_Shape aValShape;
1305   if (aSubShape.get()) {
1306     aValShape = aSubShape->impl<TopoDS_Shape>();
1307   }
1308
1309   std::list<ResultPtr> aNewContexts;
1310   TopTools_ListOfShape aValShapes;
1311   if (searchNewContext(aDoc, aNewCShape, aContext, aValShape, aContLab, aNewContexts, aValShapes))
1312   {
1313     // update scope to reset to a new one
1314     myScope.Clear();
1315
1316     std::list<ResultPtr>::iterator aNewCont = aNewContexts.begin();
1317     TopTools_ListIteratorOfListOfShape aNewValues(aValShapes);
1318     if (aNewCont == aNewContexts.end()) { // all results were deleted
1319       ResultPtr anEmptyContext;
1320       std::shared_ptr<GeomAPI_Shape> anEmptyShape;
1321       setValue(anEmptyContext, anEmptyShape); // nullify the selection
1322       return;
1323     }
1324
1325     GeomShapePtr aValueShape;
1326     if (!aNewValues.Value().IsNull()) {
1327       aValueShape = std::make_shared<GeomAPI_Shape>();
1328       aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1329     }
1330     setValue(*aNewCont, aValueShape);
1331     // if there are more than one result, put them by "append" into "parent" list
1332     if (myParent) {
1333       for(aNewCont++, aNewValues.Next(); aNewCont != aNewContexts.end();
1334           aNewCont++, aNewValues.Next()) {
1335         GeomShapePtr aValueShape;
1336         if (!aNewValues.Value().IsNull()) {
1337           aValueShape = std::make_shared<GeomAPI_Shape>();
1338           aValueShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aNewValues.Value()));
1339         }
1340         myParent->append(*aNewCont, aValueShape);
1341       }
1342     }
1343   }
1344 }
1345
1346 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
1347 {
1348   myParent = theParent;
1349 }