]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_AttributeSelection.cpp
Salome HOME
Merge branch 'master' into cgt/devCEA
[modules/shaper.git] / src / Model / Model_AttributeSelection.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_AttributeSelection.cpp
4 // Created:     2 Oct 2014
5 // Author:      Mikhail PONIKAROV
6
7 #include "Model_AttributeSelection.h"
8 #include "Model_Application.h"
9 #include "Model_Events.h"
10 #include "Model_Data.h"
11 #include "Model_Document.h"
12 #include "Model_SelectionNaming.h"
13 #include <Model_Objects.h>
14 #include <Model_AttributeSelectionList.h>
15 #include <Model_ResultConstruction.h>
16 #include <ModelAPI_Feature.h>
17 #include <ModelAPI_ResultBody.h>
18 #include <ModelAPI_ResultConstruction.h>
19 #include <ModelAPI_ResultPart.h>
20 #include <ModelAPI_CompositeFeature.h>
21 #include <ModelAPI_Tools.h>
22 #include <ModelAPI_Session.h>
23 #include <Events_InfoMessage.h>
24
25 #include <TNaming_Selector.hxx>
26 #include <TNaming_NamedShape.hxx>
27 #include <TNaming_Tool.hxx>
28 #include <TNaming_Builder.hxx>
29 #include <TNaming_SameShapeIterator.hxx>
30 #include <TNaming_Iterator.hxx>
31 #include <TDataStd_Integer.hxx>
32 #include <TDataStd_UAttribute.hxx>
33 #include <TDataStd_Name.hxx>
34 #include <TopTools_ListOfShape.hxx>
35 #include <TopExp_Explorer.hxx>
36 #include <BRep_Tool.hxx>
37 #include <TopoDS.hxx>
38 #include <TopExp.hxx>
39 #include <TDF_ChildIterator.hxx>
40 #include <TDF_ChildIDIterator.hxx>
41 #include <TopoDS_Iterator.hxx>
42
43 //#define DEB_NAMING 1
44 #ifdef DEB_NAMING
45 #include <BRepTools.hxx>
46 #endif
47 /// added to the index in the packed map to signalize that the vertex of edge is selected
48 /// (multiplied by the index of the edge)
49 static const int kSTART_VERTEX_DELTA = 1000000;
50 // identifier that there is simple reference: selection equals to context
51 Standard_GUID kSIMPLE_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb29");
52 // reference to Part sub-object
53 Standard_GUID kPART_REF_ID("635eacb2-a1d6-4dec-8348-471fae17cb27");
54 // selection is invalid after recomputation
55 Standard_GUID kINVALID_SELECTION("bce47fd7-80fa-4462-9d63-2f58acddd49d");
56
57 // on this label is stored:
58 // TNaming_NamedShape - selected shape
59 // TNaming_Naming - topological selection information (for the body)
60 // TDataStd_IntPackedMap - indexes of edges in composite element (for construction)
61 // TDataStd_Integer - type of the selected shape (for construction)
62 // TDF_Reference - from ReferenceAttribute, the context
63 void Model_AttributeSelection::setValue(const ResultPtr& theContext,
64   const std::shared_ptr<GeomAPI_Shape>& theSubShape, const bool theTemporarily)
65 {
66   if (theTemporarily) { // just keep the stored without DF update
67     myTmpContext = theContext;
68     myTmpSubShape = theSubShape;
69     owner()->data()->sendAttributeUpdated(this);
70     return;
71   } else {
72     myTmpContext.reset();
73     myTmpSubShape.reset();
74   }
75
76   const std::shared_ptr<GeomAPI_Shape>& anOldShape = value();
77   bool isOldContext = theContext == myRef.value();
78   bool isOldShape = isOldContext &&
79     (theSubShape == anOldShape || (theSubShape && anOldShape && theSubShape->isEqual(anOldShape)));
80   if (isOldShape) return; // shape is the same, so context is also unchanged
81   // update the referenced object if needed
82   if (!isOldContext) {
83       myRef.setValue(theContext);
84   }
85
86   // do noth use naming if selected shape is result shape itself, but not sub-shape
87   TDF_Label aSelLab = selectionLabel();
88   aSelLab.ForgetAttribute(kSIMPLE_REF_ID);
89   aSelLab.ForgetAttribute(kINVALID_SELECTION);
90
91   bool isDegeneratedEdge = false;
92   // do not use the degenerated edge as a shape, a null context and shape is used in the case
93   if (theSubShape.get() && !theSubShape->isNull() && theSubShape->isEdge()) {
94     const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
95     if (aSubShape.ShapeType() == TopAbs_EDGE)
96       isDegeneratedEdge = BRep_Tool::Degenerated(TopoDS::Edge(aSubShape)) == Standard_True;
97   }
98   if (!theContext.get() || isDegeneratedEdge) {
99     // to keep the reference attribute label
100     TDF_Label aRefLab = myRef.myRef->Label();
101     aSelLab.ForgetAllAttributes(true);
102     myRef.myRef = TDF_Reference::Set(aSelLab.Father(), aSelLab.Father());
103     return;
104   }
105   if (theContext->groupName() == ModelAPI_ResultBody::group()) {
106     // do not select the whole shape for body:it is already must be in the data framework
107     // equal and null selected objects mean the same: object is equal to context,
108     if (theContext->shape().get() &&
109         (theContext->shape()->isEqual(theSubShape) || !theSubShape.get())) {
110       aSelLab.ForgetAllAttributes(true);
111       TDataStd_UAttribute::Set(aSelLab, kSIMPLE_REF_ID);
112     } else {
113       selectBody(theContext, theSubShape);
114     }
115   } else if (theContext->groupName() == ModelAPI_ResultConstruction::group()) {
116     aSelLab.ForgetAllAttributes(true); // to remove old selection data
117     std::shared_ptr<Model_ResultConstruction> aConstruction =
118       std::dynamic_pointer_cast<Model_ResultConstruction>(theContext);
119     std::shared_ptr<GeomAPI_Shape> aSubShape;
120     if (theSubShape.get() && !theContext->shape()->isEqual(theSubShape))
121       aSubShape = theSubShape; // the whole context
122     int anIndex = aConstruction->select(theSubShape, owner()->document());
123     TDataStd_Integer::Set(aSelLab, anIndex);
124   } else if (theContext->groupName() == ModelAPI_ResultPart::group()) {
125     aSelLab.ForgetAllAttributes(true);
126     TDataStd_UAttribute::Set(aSelLab, kPART_REF_ID);
127     selectPart(theContext, theSubShape);
128   }
129
130   owner()->data()->sendAttributeUpdated(this);
131 }
132
133 void Model_AttributeSelection::removeTemporaryValues()
134 {
135   if (myTmpContext.get() || myTmpSubShape.get()) {
136     myTmpContext.reset();
137     myTmpSubShape.reset();
138   }
139 }
140
141 std::shared_ptr<GeomAPI_Shape> Model_AttributeSelection::value()
142 {
143   GeomShapePtr aResult;
144   if (myTmpContext.get() || myTmpSubShape.get()) {
145     ResultConstructionPtr aResulConstruction =
146       std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(myTmpContext);
147     if(aResulConstruction.get()) {
148       // it is just reference to construction.
149       return myTmpSubShape;
150     }
151     return myTmpSubShape.get() ? myTmpSubShape : myTmpContext->shape();
152   }
153
154   TDF_Label aSelLab = selectionLabel();
155   if (aSelLab.IsAttribute(kINVALID_SELECTION))
156     return aResult;
157
158   if (myRef.isInitialized()) {
159     if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
160       ResultPtr aContext = context();
161       if (!aContext.get())
162         return aResult; // empty result
163       return aContext->shape();
164     }
165     if (aSelLab.IsAttribute(kPART_REF_ID)) {
166       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(context());
167       if (!aPart.get() || !aPart->isActivated())
168         return std::shared_ptr<GeomAPI_Shape>(); // postponed naming needed
169       Handle(TDataStd_Integer) anIndex;
170       if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
171         if (anIndex->Get()) { // special selection attribute was created, use it
172           return aPart->selectionValue(anIndex->Get());
173         } else { // face with name is already in the data model, so try to take it by name
174           Handle(TDataStd_Name) aName;
175           if (aSelLab.FindAttribute(TDataStd_Name::GetID(), aName)) {
176             std::string aSubShapeName(TCollection_AsciiString(aName->Get()).ToCString());
177             std::size_t aPartEnd = aSubShapeName.find('/');
178             if (aPartEnd != std::string::npos && aPartEnd != aSubShapeName.rfind('/')) {
179               std::string aNameInPart = aSubShapeName.substr(aPartEnd + 1);
180               int anIndex;
181               std::string aType; // to reuse already existing selection the type is not needed
182               return aPart->shapeInPart(aNameInPart, aType, anIndex);
183             }
184           }
185         }
186       }
187     }
188
189     Handle(TNaming_NamedShape) aSelection;
190     if (aSelLab.FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
191       TopoDS_Shape aSelShape = aSelection->Get();
192       aResult = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
193       aResult->setImpl(new TopoDS_Shape(aSelShape));
194     } else { // for simple construction element: just shape of this construction element
195       std::shared_ptr<Model_ResultConstruction> aConstr =
196         std::dynamic_pointer_cast<Model_ResultConstruction>(context());
197       if (aConstr) {
198         Handle(TDataStd_Integer) anIndex;
199         if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
200           if (anIndex->Get() == 0) // it is just reference to construction, nothing is in value
201             return aResult;
202           return aConstr->shape(anIndex->Get(), owner()->document());
203         }
204       }
205     }
206   }
207   return aResult;
208 }
209
210 bool Model_AttributeSelection::isInvalid()
211 {
212   return selectionLabel().IsAttribute(kINVALID_SELECTION) == Standard_True;
213 }
214
215 bool Model_AttributeSelection::isInitialized()
216 {
217   if (ModelAPI_AttributeSelection::isInitialized()) { // additional checks if it is initialized
218     std::shared_ptr<GeomAPI_Shape> aResult;
219     if (myRef.isInitialized()) {
220       TDF_Label aSelLab = selectionLabel();
221       if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
222         ResultPtr aContext = context();
223         return aContext.get() != NULL;
224       }
225       Handle(TNaming_NamedShape) aSelection;
226       if (selectionLabel().FindAttribute(TNaming_NamedShape::GetID(), aSelection)) {
227         return !aSelection->Get().IsNull();
228       } else { // for simple construction element: just shape of this construction element
229         std::shared_ptr<Model_ResultConstruction> aConstr =
230           std::dynamic_pointer_cast<Model_ResultConstruction>(context());
231         if (aConstr.get()) {
232           Handle(TDataStd_Integer) anIndex;
233           if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
234             if (anIndex->Get() == 0) // it is just reference to construction, nothing is in value
235               return true;
236             return aConstr->shape(anIndex->Get(), owner()->document()).get() != NULL;
237           }
238         }
239       }
240     }
241   }
242   return false;
243 }
244
245 Model_AttributeSelection::Model_AttributeSelection(TDF_Label& theLabel)
246   : myRef(theLabel)
247 {
248   myIsInitialized = myRef.isInitialized();
249   myParent = NULL;
250 }
251
252 void Model_AttributeSelection::setID(const std::string theID)
253 {
254   myRef.setID(theID);
255   ModelAPI_AttributeSelection::setID(theID);
256 }
257
258 ResultPtr Model_AttributeSelection::context() {
259   if (myTmpContext.get() || myTmpSubShape.get()) {
260     return myTmpContext;
261   }
262
263   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
264   // for parts there could be same-data result, so take the last enabled
265   if (aResult.get() && aResult->groupName() == ModelAPI_ResultPart::group()) {
266     int aSize = aResult->document()->size(ModelAPI_ResultPart::group());
267     for(int a = aSize - 1; a >= 0; a--) {
268       ObjectPtr aPart = aResult->document()->object(ModelAPI_ResultPart::group(), a);
269       if (aPart.get() && aPart->data() == aResult->data()) {
270         ResultPtr aPartResult = std::dynamic_pointer_cast<ModelAPI_Result>(aPart);
271         FeaturePtr anOwnerFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
272         // check that this result is not this-feature result (it is forbidden t oselect itself)
273         if (anOwnerFeature.get() && anOwnerFeature->firstResult() != aPartResult) {
274           return aPartResult;
275         }
276       }
277     }
278   }
279   return aResult;
280 }
281
282
283 void Model_AttributeSelection::setObject(const std::shared_ptr<ModelAPI_Object>& theObject)
284 {
285   ModelAPI_AttributeSelection::setObject(theObject);
286   myRef.setObject(theObject);
287 }
288
289 TDF_LabelMap& Model_AttributeSelection::scope()
290 {
291   if (myScope.IsEmpty()) { // create a new scope if not yet done
292     // gets all features with named shapes that are before this feature label (before in history)
293     DocumentPtr aMyDoc = owner()->document();
294     std::list<std::shared_ptr<ModelAPI_Feature> > allFeatures = aMyDoc->allFeatures();
295     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator aFIter = allFeatures.begin();
296     bool aMePassed = false;
297     CompositeFeaturePtr aComposite =
298       std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(owner());
299     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
300     CompositeFeaturePtr aCompositeOwner, aCompositeOwnerOwner;
301     if (aFeature.get()) {
302       aCompositeOwner = ModelAPI_Tools::compositeOwner(aFeature);
303       if (aCompositeOwner.get()) {
304          aCompositeOwnerOwner = ModelAPI_Tools::compositeOwner(aCompositeOwner);
305       }
306     }
307     // for group Scope is not limitet: this is always up to date objects
308     bool isGroup = aFeature.get() && aFeature->getKind() == "Group";
309     for(; aFIter != allFeatures.end(); aFIter++) {
310       if (*aFIter == owner()) {  // the left features are created later (except subs of composite)
311         aMePassed = true;
312         continue;
313       }
314       if (isGroup) aMePassed = false;
315       bool isInScope = !aMePassed;
316       if (!isInScope && aComposite.get()) {
317         // try to add sub-elements of composite if this is composite
318         if (aComposite->isSub(*aFIter))
319           isInScope = true;
320       }
321       // remove the composite-owner of this feature (sketch in extrusion-cut)
322       if (isInScope && (aCompositeOwner == *aFIter || aCompositeOwnerOwner == *aFIter))
323         isInScope = false;
324
325       if (isInScope && aFIter->get() && (*aFIter)->data()->isValid()) {
326         TDF_Label aFeatureLab = std::dynamic_pointer_cast<Model_Data>(
327           (*aFIter)->data())->label().Father();
328         TDF_ChildIDIterator aNSIter(aFeatureLab, TNaming_NamedShape::GetID(), true);
329         for(; aNSIter.More(); aNSIter.Next()) {
330           Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
331           if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
332             myScope.Add(aNS->Label());
333           }
334         }
335       }
336     }
337     // also add all naming labels created for external constructions
338     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(aMyDoc);
339     TDF_Label anExtDocLab = aDoc->extConstructionsLabel();
340     TDF_ChildIDIterator aNSIter(anExtDocLab, TNaming_NamedShape::GetID(), true);
341     for(; aNSIter.More(); aNSIter.Next()) {
342       Handle(TNaming_NamedShape) aNS = Handle(TNaming_NamedShape)::DownCast(aNSIter.Value());
343       if (!aNS.IsNull() && aNS->Evolution() != TNaming_SELECTED) {
344         myScope.Add(aNS->Label());
345       }
346     }
347   }
348   return myScope;
349 }
350
351 /// Sets the invalid flag if flag is false, or removes it if "true"
352 /// Returns theFlag
353 static bool setInvalidIfFalse(TDF_Label& theLab, const bool theFlag) {
354   if (theFlag) {
355     theLab.ForgetAttribute(kINVALID_SELECTION);
356   } else {
357     TDataStd_UAttribute::Set(theLab, kINVALID_SELECTION);
358   }
359   return theFlag;
360 }
361
362 void Model_AttributeSelection::split(
363   ResultPtr theContext, TopoDS_Shape theNewShape, TopAbs_ShapeEnum theType)
364 {
365   TopTools_ListOfShape aSubs;
366   for(TopoDS_Iterator anExplorer(theNewShape); anExplorer.More(); anExplorer.Next()) {
367     if (!anExplorer.Value().IsNull() &&
368       anExplorer.Value().ShapeType() == theType) {
369         aSubs.Append(anExplorer.Value());
370     } else { // invalid case; bad result shape, so, impossible to split easily
371       aSubs.Clear();
372       break;
373     }
374   }
375   if (aSubs.Extent() > 1) { // ok to split
376     TopTools_ListIteratorOfListOfShape aSub(aSubs);
377     GeomShapePtr aSubSh(new GeomAPI_Shape);
378     aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
379     setValue(theContext, aSubSh);
380     for(aSub.Next(); aSub.More(); aSub.Next()) {
381       GeomShapePtr aSubSh(new GeomAPI_Shape);
382       aSubSh->setImpl(new TopoDS_Shape(aSub.Value()));
383       myParent->append(theContext, aSubSh);
384     }
385   }
386 }
387
388 bool Model_AttributeSelection::update()
389 {
390   TDF_Label aSelLab = selectionLabel();
391   ResultPtr aContext = context();
392   if (!aContext.get())
393     return setInvalidIfFalse(aSelLab, false);
394   if (aSelLab.IsAttribute(kSIMPLE_REF_ID)) { // it is just reference to shape, not sub-shape
395     return setInvalidIfFalse(aSelLab, aContext->shape() && !aContext->shape()->isNull());
396   }
397
398   if (aSelLab.IsAttribute(kPART_REF_ID)) { // it is reference to the part object
399     std::shared_ptr<GeomAPI_Shape> aNoSelection;
400     bool aResult = selectPart(aContext, aNoSelection, true);
401     aResult = setInvalidIfFalse(aSelLab, aResult);
402     if (aResult) {
403       owner()->data()->sendAttributeUpdated(this);
404     }
405     return aResult;
406   }
407
408   if (aContext->groupName() == ModelAPI_ResultBody::group()) {
409     // body: just a named shape, use selection mechanism from OCCT
410     TNaming_Selector aSelector(aSelLab);
411     TopoDS_Shape anOldShape;
412     if (!aSelector.NamedShape().IsNull()) {
413       anOldShape = aSelector.NamedShape()->Get();
414     }
415     bool aResult = aSelector.Solve(scope()) == Standard_True;
416     // must be before sending of updated attribute (1556)
417     aResult = setInvalidIfFalse(aSelLab, aResult);
418     TopoDS_Shape aNewShape;
419     if (!aSelector.NamedShape().IsNull()) {
420       aNewShape = aSelector.NamedShape()->Get();
421     }
422     if (anOldShape.IsNull() || aNewShape.IsNull() ||
423         !anOldShape.IsEqual(aSelector.NamedShape()->Get())) {
424       // shape type shoud not not changed: if shape becomes compound of such shapes, then split
425       if (myParent && !anOldShape.IsNull() && !aNewShape.IsNull() &&
426           anOldShape.ShapeType() != aNewShape.ShapeType() &&
427           (aNewShape.ShapeType() == TopAbs_COMPOUND || aNewShape.ShapeType() == TopAbs_COMPSOLID))
428       {
429         split(aContext, aNewShape, anOldShape.ShapeType());
430       }
431       owner()->data()->sendAttributeUpdated(this);  // send updated if shape is changed
432     }
433     return aResult;
434   }
435
436   if (aContext->groupName() == ModelAPI_ResultConstruction::group()) {
437     Handle(TDataStd_Integer) anIndex;
438     if (aSelLab.FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
439       std::shared_ptr<Model_ResultConstruction> aConstructionContext =
440         std::dynamic_pointer_cast<Model_ResultConstruction>(aContext);
441       bool aModified = true;
442       bool aValid = aConstructionContext->update(anIndex->Get(), owner()->document(), aModified);
443       setInvalidIfFalse(aSelLab, aValid);
444       if (aModified)
445         owner()->data()->sendAttributeUpdated(this);
446       return aValid;
447     }
448   }
449   return setInvalidIfFalse(aSelLab, false); // unknown case
450 }
451
452 void Model_AttributeSelection::selectBody(
453   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape)
454 {
455   // perform the selection
456   TNaming_Selector aSel(selectionLabel());
457   TopoDS_Shape aContext;
458
459   ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theContext);//myRef.value()
460   if (aBody) {
461     aContext = aBody->shape()->impl<TopoDS_Shape>();
462   } else {
463     ResultPtr aResult =
464       std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
465     if (aResult) {
466       aContext = aResult->shape()->impl<TopoDS_Shape>();
467     } else {
468       Events_InfoMessage("Model_AttributeSelection", "A result with shape is expected").send();
469       return;
470     }
471   }
472
473   // with "recover" feature the selected context may be not up to date (issue 1710)
474   Handle(TNaming_NamedShape) aResult;
475   TDF_Label aSelLab = selectionLabel();
476   TopoDS_Shape aNewContext = aContext;
477   bool isUpdated = true;
478   while(!aNewContext.IsNull() && isUpdated) {
479     // searching for the very last shape that was produced from this one
480     isUpdated = false;
481     if (!TNaming_Tool::HasLabel(aSelLab, aNewContext))
482       // to avoid crash of TNaming_SameShapeIterator if pure shape does not exists
483       break;
484     for(TNaming_SameShapeIterator anIter(aNewContext, aSelLab); anIter.More(); anIter.Next()) {
485       TDF_Label aNSLab = anIter.Label();
486       if (!scope().Contains(aNSLab))
487         continue;
488       Handle(TNaming_NamedShape) aNS;
489       if (aNSLab.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
490         for(TNaming_Iterator aShapesIter(aNS); aShapesIter.More(); aShapesIter.Next()) {
491           if (aShapesIter.Evolution() == TNaming_SELECTED)
492             continue; // don't use the selection evolution
493           if (!aShapesIter.OldShape().IsNull() && aShapesIter.OldShape().IsSame(aNewContext)) {
494              // found the original shape
495             aNewContext = aShapesIter.NewShape(); // go to the newer shape
496             isUpdated = true;
497             break;
498           }
499         }
500       }
501     }
502   }
503   if (aNewContext.IsNull()) { // a context is already deleted
504     setInvalidIfFalse(aSelLab, false);
505     Events_InfoMessage("Model_AttributeSelection", "Failed to select shape already deleted").send();
506     return;
507   }
508
509   TopoDS_Shape aNewSub = theSubShape ? theSubShape->impl<TopoDS_Shape>() : aContext;
510   if (!aNewSub.IsEqual(aContext)) { // searching for subshape in the new context
511     bool isFound = false;
512     TopExp_Explorer anExp(aNewContext, aNewSub.ShapeType());
513     for(; anExp.More(); anExp.Next()) {
514       if (anExp.Current().IsEqual(aNewSub)) {
515         isFound = true;
516         break;
517       }
518     }
519     if (!isFound) { // sub-shape is not found in the up-to-date instance of the context shape
520       // if context is sub-result of compound/compsolid, selection of sub-shape better propagate to
521       // the main result (which is may be modified), case is in 1799
522       ResultCompSolidPtr aMain = ModelAPI_Tools::compSolidOwner(theContext);
523       if (aMain.get()) {
524         selectBody(aMain, theSubShape);
525         return;
526       }
527       setInvalidIfFalse(aSelLab, false);
528       Events_InfoMessage("Model_AttributeSelection",
529         "Failed to select sub-shape already modified").send();
530       return;
531     }
532   }
533
534   /// fix for issue 411: result modified shapes must not participate in this selection mechanism
535   if (!aContext.IsNull()) {
536     FeaturePtr aFeatureOwner = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
537     bool aEraseResults = false;
538     if (aFeatureOwner.get()) {
539       aEraseResults = !aFeatureOwner->results().empty();
540       if (aEraseResults) // erase results without flash deleted and redisplay: do it after Select
541         aFeatureOwner->removeResults(0, false);
542     }
543     aSel.Select(aNewSub, aNewContext);
544
545     if (aEraseResults) { // flash after Select : in Groups it makes selection with shift working
546       static Events_Loop* aLoop = Events_Loop::loop();
547       static const Events_ID kDeletedEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
548       aLoop->flush(kDeletedEvent);
549     }
550   }
551 }
552
553 bool Model_AttributeSelection::selectPart(
554   const ResultPtr& theContext, const std::shared_ptr<GeomAPI_Shape>& theSubShape,
555   const bool theUpdate)
556 {
557   ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(theContext);
558   if (!aPart.get() || !aPart->isActivated())
559     return true; // postponed naming
560   if (theUpdate) {
561     Handle(TDataStd_Integer) anIndex;
562     if (selectionLabel().FindAttribute(TDataStd_Integer::GetID(), anIndex)) {
563       // by internal selection
564       if (anIndex->Get() > 0) {
565         // update the selection by index
566         return aPart->updateInPart(anIndex->Get());
567       } else {
568         return true; // nothing to do, referencing just by name
569       }
570     }
571     return true; // nothing to do, referencing just by name
572   }
573   // store the shape (in case part is not loaded it should be useful
574   TopoDS_Shape aShape;
575   std::string aName = theContext->data()->name();
576   if (!theSubShape.get() || theSubShape->isNull()) {// the whole part shape is selected
577     aShape = theContext->shape()->impl<TopoDS_Shape>();
578   } else {
579     aShape = theSubShape->impl<TopoDS_Shape>();
580     int anIndex;
581     aName += "/" + aPart->nameInPart(theSubShape, anIndex);
582     TDataStd_Integer::Set(selectionLabel(), anIndex);
583   }
584   TNaming_Builder aBuilder(selectionLabel());
585   aBuilder.Select(aShape, aShape);
586   // identify by name in the part
587   TDataStd_Name::Set(selectionLabel(), aName.c_str());
588   return !aName.empty();
589 }
590
591 TDF_Label Model_AttributeSelection::selectionLabel()
592 {
593   return myRef.myRef->Label().FindChild(1);
594 }
595
596 std::string Model_AttributeSelection::namingName(const std::string& theDefaultName)
597 {
598   std::string aName("");
599   if(!this->isInitialized())
600     return !theDefaultName.empty() ? theDefaultName : aName;
601
602   std::shared_ptr<GeomAPI_Shape> aSubSh = value();
603   ResultPtr aCont = context();
604
605   if (!aCont.get()) // in case of selection of removed result
606     return "";
607
608   Model_SelectionNaming aSelNaming(selectionLabel());
609   return aSelNaming.namingName(
610     aCont, aSubSh, theDefaultName, owner()->document() != aCont->document());
611 }
612
613 // type ::= COMP | COMS | SOLD | SHEL | FACE | WIRE | EDGE | VERT
614 void Model_AttributeSelection::selectSubShape(
615   const std::string& theType, const std::string& theSubShapeName)
616 {
617   if(theSubShapeName.empty() || theType.empty()) return;
618
619   // check this is Part-name: 2 delimiters in the name
620   std::size_t aPartEnd = theSubShapeName.find('/');
621   if (aPartEnd != std::string::npos && aPartEnd != theSubShapeName.rfind('/')) {
622     std::string aPartName = theSubShapeName.substr(0, aPartEnd);
623     ObjectPtr aFound = owner()->document()->objectByName(ModelAPI_ResultPart::group(), aPartName);
624     if (aFound.get()) { // found such part, so asking it for the name
625       ResultPartPtr aPart = std::dynamic_pointer_cast<ModelAPI_ResultPart>(aFound);
626       std::string aNameInPart = theSubShapeName.substr(aPartEnd + 1);
627       int anIndex;
628       std::shared_ptr<GeomAPI_Shape> aSelected = aPart->shapeInPart(aNameInPart, theType, anIndex);
629       if (aSelected.get()) {
630         setValue(aPart, aSelected);
631         TDataStd_Integer::Set(selectionLabel(), anIndex);
632         return;
633       }
634     }
635   }
636
637   Model_SelectionNaming aSelNaming(selectionLabel());
638   std::shared_ptr<Model_Document> aDoc =
639     std::dynamic_pointer_cast<Model_Document>(owner()->document());
640   std::shared_ptr<GeomAPI_Shape> aShapeToBeSelected;
641   ResultPtr aCont;
642   if (aSelNaming.selectSubShape(theType, theSubShapeName, aDoc, aShapeToBeSelected, aCont)) {
643     // try to find the last context to find the up to date shape
644     if (aCont->shape().get() && !aCont->shape()->isNull() &&
645       aCont->groupName() == ModelAPI_ResultBody::group() && aDoc == owner()->document()) {
646       const TopoDS_Shape aConShape = aCont->shape()->impl<TopoDS_Shape>();
647       if (!aConShape.IsNull()) {
648         Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aConShape, selectionLabel());
649         if (!aNS.IsNull()) {
650           aNS = TNaming_Tool::CurrentNamedShape(aNS);
651           if (!aNS.IsNull()) {
652             TDF_Label aLab = aNS->Label();
653             while(aLab.Depth() != 7 && aLab.Depth() > 5)
654               aLab = aLab.Father();
655             ObjectPtr anObj = aDoc->objects()->object(aLab);
656             if (anObj.get()) {
657               ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(anObj);
658               if (aRes)
659                 aCont = aRes;
660             }
661           }
662         }
663       }
664     }
665     setValue(aCont, aShapeToBeSelected);
666   }
667 }
668
669 int Model_AttributeSelection::Id()
670 {
671   int anID = 0;
672   std::shared_ptr<GeomAPI_Shape> aSelection = value();
673   std::shared_ptr<GeomAPI_Shape> aContext = context()->shape();
674   // support for compsolids:
675   if (context().get() && ModelAPI_Tools::compSolidOwner(context()).get())
676     aContext = ModelAPI_Tools::compSolidOwner(context())->shape();
677
678
679   TopoDS_Shape aMainShape = aContext->impl<TopoDS_Shape>();
680   const TopoDS_Shape& aSubShape = aSelection->impl<TopoDS_Shape>();
681   // searching for the latest main shape
682   if (aSelection && !aSelection->isNull() &&
683     aContext   && !aContext->isNull())
684   {
685     std::shared_ptr<Model_Document> aDoc =
686       std::dynamic_pointer_cast<Model_Document>(context()->document());
687     if (aDoc.get()) {
688       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
689       if (!aNS.IsNull()) {
690         aMainShape = TNaming_Tool::CurrentShape(aNS);
691       }
692     }
693
694     TopTools_IndexedMapOfShape aSubShapesMap;
695     TopExp::MapShapes(aMainShape, aSubShapesMap);
696     anID = aSubShapesMap.FindIndex(aSubShape);
697   }
698   return anID;
699 }
700
701 void Model_AttributeSelection::setId(int theID)
702 {
703   const ResultPtr& aContext = context();
704   std::shared_ptr<GeomAPI_Shape> aSelection;
705
706   std::shared_ptr<GeomAPI_Shape> aContextShape = aContext->shape();
707   // support for compsolids:
708   if (aContext.get() && ModelAPI_Tools::compSolidOwner(aContext).get())
709     aContextShape = ModelAPI_Tools::compSolidOwner(aContext)->shape();
710
711   TopoDS_Shape aMainShape = aContextShape->impl<TopoDS_Shape>();
712   // searching for the latest main shape
713   if (theID > 0 &&
714       aContextShape && !aContextShape->isNull())
715   {
716     std::shared_ptr<Model_Document> aDoc =
717       std::dynamic_pointer_cast<Model_Document>(aContext->document());
718     if (aDoc.get()) {
719       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aMainShape, aDoc->generalLabel());
720       if (!aNS.IsNull()) {
721         aMainShape = TNaming_Tool::CurrentShape(aNS);
722       }
723     }
724
725     TopTools_IndexedMapOfShape aSubShapesMap;
726     TopExp::MapShapes(aMainShape, aSubShapesMap);
727     const TopoDS_Shape& aSelShape = aSubShapesMap.FindKey(theID);
728
729     std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
730     aResult->setImpl(new TopoDS_Shape(aSelShape));
731
732     aSelection = aResult;
733   }
734
735   setValue(aContext, aSelection);
736 }
737
738 std::string Model_AttributeSelection::contextName(const ResultPtr& theContext) const
739 {
740   std::string aResult;
741   if (owner()->document() != theContext->document()) {
742     if (theContext->document() == ModelAPI_Session::get()->moduleDocument()) {
743       aResult = theContext->document()->kind() + "/";
744     } else {
745       ResultPtr aDocRes = ModelAPI_Tools::findPartResult(
746         ModelAPI_Session::get()->moduleDocument(), theContext->document());
747       if (aDocRes.get()) {
748         aResult = aDocRes->data()->name() + "/";
749       }
750     }
751   }
752   aResult += theContext->data()->name();
753   return aResult;
754 }
755
756 void Model_AttributeSelection::updateInHistory()
757 {
758   ResultPtr aContext = std::dynamic_pointer_cast<ModelAPI_Result>(myRef.value());
759   // only bodies may be modified later in the history, don't do anything otherwise
760   if (!aContext.get() || aContext->groupName() != ModelAPI_ResultBody::group())
761     return;
762   std::shared_ptr<Model_Data> aContData = std::dynamic_pointer_cast<Model_Data>(aContext->data());
763   if (!aContData.get() || !aContData->isValid())
764     return;
765   TDF_Label aContLab = aContData->label(); // named shape where the selected context is located
766   Handle(TNaming_NamedShape) aContNS;
767   if (!aContLab.FindAttribute(TNaming_NamedShape::GetID(), aContNS))
768     return;
769   std::shared_ptr<Model_Document> aDoc =
770     std::dynamic_pointer_cast<Model_Document>(aContext->document());
771   FeaturePtr aThisFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(owner());
772   FeaturePtr aCurrentModifierFeat = aDoc->feature(aContext);
773   // iterate the context shape modifications in order to find a feature that is upper in history
774   // that this one and is really modifies the referenced result to refer to it
775   ResultPtr aModifierResFound;
776   TNaming_Iterator aPairIter(aContNS);
777   if (!aPairIter.More())
778     return;
779   TopoDS_Shape aNewShape = aPairIter.NewShape();
780   bool anIterate = true;
781   // trying to update also the sub-shape selected
782   GeomShapePtr aSubShape = value();
783   if (aSubShape.get() && aSubShape->isEqual(aContext->shape()))
784     aSubShape.reset();
785
786   while(anIterate) {
787     anIterate = false;
788     TNaming_SameShapeIterator aModifIter(aNewShape, aContLab);
789     for(; aModifIter.More(); aModifIter.Next()) {
790       ResultPtr aModifierObj = std::dynamic_pointer_cast<ModelAPI_Result>
791         (aDoc->objects()->object(aModifIter.Label().Father()));
792       if (!aModifierObj.get())
793         break;
794       FeaturePtr aModifierFeat = aDoc->feature(aModifierObj);
795       if (!aModifierFeat.get())
796         break;
797       if (aModifierFeat == aThisFeature || aDoc->objects()->isLater(aModifierFeat, aThisFeature))
798         continue; // the modifier feature is later than this, so, should not be used
799       if (aCurrentModifierFeat == aModifierFeat ||
800         aDoc->objects()->isLater(aCurrentModifierFeat, aModifierFeat))
801         continue; // the current modifier is later than the found, so, useless
802       Handle(TNaming_NamedShape) aNewNS;
803       aModifIter.Label().FindAttribute(TNaming_NamedShape::GetID(), aNewNS);
804       if (aNewNS->Evolution() == TNaming_MODIFY || aNewNS->Evolution() == TNaming_GENERATED) {
805         aModifierResFound = aModifierObj;
806         aCurrentModifierFeat = aModifierFeat;
807         TNaming_Iterator aPairIter(aNewNS);
808         aNewShape = aPairIter.NewShape();
809         anIterate = true;
810         break;
811       } else if (aNewNS->Evolution() == TNaming_DELETE) { // a shape was deleted => result is null
812         ResultPtr anEmptyContext;
813         std::shared_ptr<GeomAPI_Shape> anEmptyShape;
814         setValue(anEmptyContext, anEmptyShape); // nullify the selection
815         return;
816       } else { // not-precessed modification => don't support it
817         continue;
818       }
819     }
820   }
821   if (aModifierResFound.get()) {
822     // update scope to reset to a new one
823     myScope.Clear();
824     myRef.setValue(aModifierResFound);
825     // if context shape type is changed to more complicated and this context is selected, split
826     if (myParent &&!aSubShape.get() && aModifierResFound->shape().get() && aContext->shape().get())
827     {
828       TopoDS_Shape anOldShape = aContext->shape()->impl<TopoDS_Shape>();
829       TopoDS_Shape aNewShape = aModifierResFound->shape()->impl<TopoDS_Shape>();
830       if (!anOldShape.IsNull() && !aNewShape.IsNull() &&
831         anOldShape.ShapeType() != aNewShape.ShapeType() &&
832         (aNewShape.ShapeType() == TopAbs_COMPOUND || aNewShape.ShapeType() == TopAbs_COMPSOLID)) {
833         // prepare for split in "update"
834         TDF_Label aSelLab = selectionLabel();
835         split(aContext, aNewShape, anOldShape.ShapeType());
836       }
837     }
838     update(); // it must recompute a new sub-shape automatically
839   }
840 }
841
842 void Model_AttributeSelection::setParent(Model_AttributeSelectionList* theParent)
843 {
844   myParent = theParent;
845 }