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