Salome HOME
e2c7460f6749ec23856c2614078ee7a50f662097
[modules/shaper.git] / src / XGUI / XGUI_Displayer.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
2
3 // File:        XGUI_Displayer.cpp
4 // Created:     20 Apr 2014
5 // Author:      Natalia ERMOLAEVA
6
7 #include "XGUI_Displayer.h"
8 #include "XGUI_Workshop.h"
9 #include "XGUI_ViewerProxy.h"
10 #include "XGUI_SelectionMgr.h"
11 #include "XGUI_Selection.h"
12 #include "XGUI_CustomPrs.h"
13
14 #ifndef HAVE_SALOME
15 #include <AppElements_Viewer.h>
16 #endif
17
18 #include <ModelAPI_Document.h>
19 #include <ModelAPI_Data.h>
20 #include <ModelAPI_Object.h>
21 #include <ModelAPI_Tools.h>
22 #include <ModelAPI_AttributeIntArray.h>
23 #include <ModelAPI_ResultCompSolid.h>
24
25 #include <ModuleBase_ResultPrs.h>
26 #include <ModuleBase_Tools.h>
27 #include <ModuleBase_IModule.h>
28 #include <ModuleBase_ViewerPrs.h>
29 #include <ModuleBase_Preferences.h>
30
31 #include <GeomAPI_Shape.h>
32 #include <GeomAPI_IPresentable.h>
33 #include <GeomAPI_ICustomPrs.h>
34
35 #include <SUIT_ResourceMgr.h>
36
37 #include <AIS_InteractiveContext.hxx>
38 #include <AIS_LocalContext.hxx>
39 #include <AIS_ListOfInteractive.hxx>
40 #include <AIS_ListIteratorOfListOfInteractive.hxx>
41 #include <AIS_DimensionSelectionMode.hxx>
42 #include <AIS_Shape.hxx>
43 #include <AIS_Dimension.hxx>
44 #include <AIS_Trihedron.hxx>
45 #include <AIS_Axis.hxx>
46 #include <AIS_Plane.hxx>
47 #include <AIS_Point.hxx>
48 #include <AIS_Selection.hxx>
49 #include <TColStd_ListIteratorOfListOfInteger.hxx>
50 #include <SelectMgr_ListOfFilter.hxx>
51 #include <SelectMgr_ListIteratorOfListOfFilter.hxx>
52 #include <Prs3d_Drawer.hxx>
53 #include <Prs3d_IsoAspect.hxx>
54 #include <SelectMgr_SelectionManager.hxx>
55
56 #include <StdSelect_ViewerSelector3d.hxx>
57
58 #include <TColStd_MapOfTransient.hxx>
59 #include <TColStd_MapIteratorOfMapOfTransient.hxx>
60
61 #include <Events_Loop.h>
62 #include <ModelAPI_Events.h>
63
64 #include <set>
65
66 const int MOUSE_SENSITIVITY_IN_PIXEL = 10;  ///< defines the local context mouse selection sensitivity
67
68 //#define DEBUG_ACTIVATE_OBJECTS
69 //#define DEBUG_DEACTIVATE
70 //#define DEBUG_ACTIVATE_AIS
71 //#define DEBUG_DEACTIVATE_AIS
72
73 //#define DEBUG_DISPLAY
74 //#define DEBUG_FEATURE_REDISPLAY
75 //#define DEBUG_SELECTION_FILTERS
76
77 //#define DEBUG_COMPOSILID_DISPLAY
78 // Workaround for bug #25637
79
80 //#define DEBUG_OCCT_SHAPE_SELECTION
81
82 //#define WORKAROUND_UNTIL_27523_IS_FIXED
83
84 void displayedObjects(const Handle(AIS_InteractiveContext)& theAIS, AIS_ListOfInteractive& theList)
85 {
86   // Get from null point
87   theAIS->DisplayedObjects(theList, true);
88   if (theAIS->HasOpenedContext()) {
89     // get from local context
90     const Handle(AIS_LocalContext)& aLC = theAIS->LocalContext();
91     TColStd_MapOfTransient aMap;
92     int NbDisp = aLC->DisplayedObjects(aMap);
93     TColStd_MapIteratorOfMapOfTransient aIt(aMap);
94
95     Handle(AIS_InteractiveObject) curIO;
96     Handle(Standard_Transient) Tr;
97     for(; aIt.More(); aIt.Next()){
98       Tr = aIt.Key();
99       curIO = *((Handle(AIS_InteractiveObject)*) &Tr);
100       theList.Append(curIO);
101     }
102   }
103 }
104
105 QString qIntListInfo(const QIntList& theValues, const QString& theSeparator = QString(", "))
106 {
107   QStringList anInfo;
108   QIntList::const_iterator anIt = theValues.begin(), aLast = theValues.end();
109   for (; anIt != aLast; anIt++) {
110     anInfo.append(QString::number(*anIt));
111   }
112   return anInfo.join(theSeparator);
113 }
114
115 XGUI_Displayer::XGUI_Displayer(XGUI_Workshop* theWorkshop)
116   : myWorkshop(theWorkshop), myNeedUpdate(false),
117   myIsTrihedronActive(true), myViewerBlockedRecursiveCount(0)
118 {
119   myCustomPrs = std::shared_ptr<GeomAPI_ICustomPrs>(new XGUI_CustomPrs(theWorkshop));
120 }
121
122 XGUI_Displayer::~XGUI_Displayer()
123 {
124 }
125
126 bool XGUI_Displayer::isVisible(ObjectPtr theObject) const
127 {
128   return myResult2AISObjectMap.contains(theObject);
129 }
130
131 bool XGUI_Displayer::display(ObjectPtr theObject, bool theUpdateViewer)
132 {
133   bool aDisplayed = false;
134   if (isVisible(theObject)) {
135 #ifdef DEBUG_COMPOSILID_DISPLAY
136     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
137     if (aCompsolidResult.get()) {
138       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
139         ResultPtr aSubResult = aCompsolidResult->subResult(i);
140         if (aSubResult.get())
141           redisplay(aSubResult, false);
142       }
143       if (theUpdateViewer)
144         updateViewer();
145     }
146     else
147 #endif
148     aDisplayed = redisplay(theObject, theUpdateViewer);
149   } else {
150     AISObjectPtr anAIS;
151     GeomPresentablePtr aPrs = std::dynamic_pointer_cast<GeomAPI_IPresentable>(theObject);
152     bool isShading = false;
153     if (aPrs.get() != NULL) {
154       anAIS = aPrs->getAISObject(anAIS);
155       if (anAIS.get()) {
156         // correct deviation coefficient for 
157         Handle(AIS_InteractiveObject) anAISPrs = anAIS->impl<Handle(AIS_InteractiveObject)>();
158         if (!anAISPrs.IsNull()) {
159           Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(anAISPrs);
160           if (!aShapePrs.IsNull()) {
161             TopoDS_Shape aShape = aShapePrs->Shape();
162             if (!aShape.IsNull())
163               ModuleBase_Tools::setDefaultDeviationCoefficient(aShape, anAISPrs->Attributes());
164           }
165         }
166       }
167     } else {
168       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
169       if (aResult.get() != NULL) {
170 #ifdef DEBUG_COMPOSILID_DISPLAY
171         ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
172         if (aCompsolidResult.get()) {
173           for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
174             ResultPtr aSubResult = aCompsolidResult->subResult(i);
175             if (aSubResult.get())
176               display(aSubResult, false);
177           }
178           if (theUpdateViewer)
179             updateViewer();
180         }
181         else {
182 #endif
183         std::shared_ptr<GeomAPI_Shape> aShapePtr = ModelAPI_Tools::shape(aResult);
184         if (aShapePtr.get() != NULL) {
185           anAIS = AISObjectPtr(new GeomAPI_AISObject());
186           Handle(AIS_InteractiveObject) anAISPrs = myWorkshop->module()->createPresentation(aResult);
187           if (anAISPrs.IsNull())
188             anAISPrs = new ModuleBase_ResultPrs(aResult);
189           else {
190             Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(anAISPrs);
191             if (!aShapePrs.IsNull())
192               ModuleBase_Tools::setPointBallHighlighting((AIS_Shape*) aShapePrs.Access());
193           }
194           anAIS->setImpl(new Handle(AIS_InteractiveObject)(anAISPrs));
195           //anAIS->createShape(aShapePtr);
196           isShading = true;
197         }
198 #ifdef DEBUG_COMPOSILID_DISPLAY
199         } // close else
200 #endif
201       }
202     }
203     if (anAIS)
204       aDisplayed = display(theObject, anAIS, isShading, theUpdateViewer);
205   }
206   return aDisplayed;
207 }
208
209 bool canBeShaded(Handle(AIS_InteractiveObject) theAIS, ModuleBase_IModule* theModule)
210 {
211   Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(theAIS);
212   if (!aShapePrs.IsNull()) {
213     TopoDS_Shape aShape = aShapePrs->Shape();
214     if (aShape.IsNull())
215       return false;
216     TopAbs_ShapeEnum aType = aShape.ShapeType();
217     if ((aType == TopAbs_VERTEX) || (aType == TopAbs_EDGE) || (aType == TopAbs_WIRE))
218       return false;
219     else {
220       // Check that the presentation is not a sketch
221       return theModule->canBeShaded(theAIS);
222     }
223   }
224   return false;
225 }
226
227 bool XGUI_Displayer::display(ObjectPtr theObject, AISObjectPtr theAIS, 
228                              bool isShading, bool theUpdateViewer)
229 {
230   bool aDisplayed = false;
231
232   Handle(AIS_InteractiveContext) aContext = AISContext();
233   if (aContext.IsNull())
234     return aDisplayed;
235
236   Handle(AIS_InteractiveObject) anAISIO = theAIS->impl<Handle(AIS_InteractiveObject)>();
237   if (!anAISIO.IsNull()) {
238     appendResultObject(theObject, theAIS);
239
240     bool isCustomized = customizeObject(theObject);
241
242     int aDispMode = isShading? Shading : Wireframe;
243     if (isShading)
244       anAISIO->Attributes()->SetFaceBoundaryDraw( Standard_True );
245     anAISIO->SetDisplayMode(aDispMode);
246     aContext->Display(anAISIO, aDispMode, 0, false, true, AIS_DS_Displayed); 
247     aDisplayed = true;
248
249     emit objectDisplayed(theObject, theAIS);
250     activate(anAISIO, myActiveSelectionModes, theUpdateViewer);
251   } 
252   if (theUpdateViewer)
253     updateViewer();
254
255   return aDisplayed;
256 }
257
258 bool XGUI_Displayer::erase(ObjectPtr theObject, const bool theUpdateViewer)
259 {
260   bool aErased = false;
261   if (!isVisible(theObject))
262     return aErased;
263
264   Handle(AIS_InteractiveContext) aContext = AISContext();
265   if (aContext.IsNull())
266     return aErased;
267
268   AISObjectPtr anObject = myResult2AISObjectMap[theObject];
269   if (anObject) {
270     Handle(AIS_InteractiveObject) anAIS = anObject->impl<Handle(AIS_InteractiveObject)>();
271     if (!anAIS.IsNull()) {
272       emit beforeObjectErase(theObject, anObject);
273       aContext->Remove(anAIS, false/*update viewer*/);
274       ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::erase -- Remove");
275       aErased = true;
276     }
277   }
278   myResult2AISObjectMap.remove(theObject);
279
280 #ifdef DEBUG_DISPLAY
281   std::ostringstream aPtrStr;
282   aPtrStr << theObject.get();
283   qDebug(QString("erase object: %1").arg(aPtrStr.str().c_str()).toStdString().c_str());
284   qDebug(getResult2AISObjectMapInfo().c_str());
285 #endif
286
287   if (theUpdateViewer)
288     updateViewer();
289
290   return aErased;
291 }
292
293 bool XGUI_Displayer::redisplay(ObjectPtr theObject, bool theUpdateViewer)
294 {
295   bool aRedisplayed = false;
296   if (!isVisible(theObject))
297     return aRedisplayed;
298
299   AISObjectPtr aAISObj = getAISObject(theObject);
300   Handle(AIS_InteractiveObject) aAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
301
302   GeomPresentablePtr aPrs = std::dynamic_pointer_cast<GeomAPI_IPresentable>(theObject);
303   if (aPrs) {
304     AISObjectPtr aAIS_Obj = aPrs->getAISObject(aAISObj);
305     if (!aAIS_Obj) {
306       aRedisplayed = erase(theObject, theUpdateViewer);
307       return aRedisplayed;
308     }
309     if (aAIS_Obj != aAISObj) {
310       appendResultObject(theObject, aAIS_Obj);
311     }
312     aAISIO = aAIS_Obj->impl<Handle(AIS_InteractiveObject)>();
313   }
314
315   Handle(AIS_InteractiveContext) aContext = AISContext();
316   if (!aContext.IsNull() && !aAISIO.IsNull()) {
317     // Check that the visualized shape is the same and the redisplay is not necessary
318     // Redisplay of AIS object leads to this object selection compute and the selection 
319     // in the browser is lost
320     // this check is not necessary anymore because the selection store/restore is realized
321     // before and after the values modification.
322     // Moreother, this check avoids customize and redisplay presentation if the presentable
323     // parameter is changed.
324     bool isEqualShapes = false;
325     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
326     if (aResult.get() != NULL) {
327       Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(aAISIO);
328       if (!aShapePrs.IsNull()) {
329         std::shared_ptr<GeomAPI_Shape> aShapePtr = ModelAPI_Tools::shape(aResult);
330         if (aShapePtr.get()) {
331           const TopoDS_Shape& aOldShape = aShapePrs->Shape();
332           if (!aOldShape.IsNull())
333             isEqualShapes = aOldShape.IsEqual(aShapePtr->impl<TopoDS_Shape>());
334         }
335       }
336     }
337     // Customization of presentation
338     bool isCustomized = customizeObject(theObject);
339     #ifdef DEBUG_FEATURE_REDISPLAY
340       qDebug(QString("Redisplay: %1, isEqualShapes=%2, isCustomized=%3").
341         arg(!isEqualShapes || isCustomized).arg(isEqualShapes).arg(isCustomized).toStdString().c_str());
342     #endif
343     if (!isEqualShapes || isCustomized) {
344       /// if shapes are equal and presentation are customized, selection should be restored
345       bool aNeedToRestoreSelection = isEqualShapes && isCustomized;
346       if (aNeedToRestoreSelection)
347         myWorkshop->module()->storeSelection();
348
349 #ifdef WORKAROUND_UNTIL_27523_IS_FIXED
350       if (!myActiveSelectionModes.contains(0))
351         aContext->Activate(aAISIO, 0);
352 #endif
353
354       aContext->Redisplay(aAISIO, false);
355
356 #ifdef WORKAROUND_UNTIL_27523_IS_FIXED
357       if (!myActiveSelectionModes.contains(0))
358         aContext->Deactivate(aAISIO, 0);
359 #endif
360
361       ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::redisplay -- Redisplay");
362
363       if (aNeedToRestoreSelection)
364         myWorkshop->module()->restoreSelection();
365
366       aRedisplayed = true;
367       #ifdef DEBUG_FEATURE_REDISPLAY
368         qDebug("  Redisplay happens");
369       #endif
370       if (theUpdateViewer)
371         updateViewer();
372     }
373   }
374   return aRedisplayed;
375 }
376
377 void XGUI_Displayer::redisplayObjects()
378 {
379   // redisplay objects visualized in the viewer
380   static Events_ID EVENT_DISP = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
381   static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
382   QObjectPtrList aDisplayed = myWorkshop->displayer()->displayedObjects();
383   QObjectPtrList::const_iterator anIt = aDisplayed.begin(), aLast = aDisplayed.end();
384   for (; anIt != aLast; anIt++) {
385     aECreator->sendUpdated(*anIt, EVENT_DISP);
386   }
387   Events_Loop::loop()->flush(EVENT_DISP);
388 }
389
390 void XGUI_Displayer::deactivate(ObjectPtr theObject, const bool theUpdateViewer)
391 {
392 #ifdef DEBUG_DEACTIVATE
393   QString anInfoStr = ModuleBase_Tools::objectInfo(theObject);
394   qDebug(QString("deactivate: myActiveSelectionModes[%1]: %2, objects = ").
395     arg(myActiveSelectionModes.size()).arg(qIntListInfo(myActiveSelectionModes)).
396     arg(anInfoStr).
397     toStdString().c_str());
398 #endif
399   Handle(AIS_InteractiveContext) aContext = AISContext();
400   if (!aContext.IsNull() && isVisible(theObject)) {
401     AISObjectPtr anObj = myResult2AISObjectMap[theObject];
402     Handle(AIS_InteractiveObject) anAIS = anObj->impl<Handle(AIS_InteractiveObject)>();
403
404     deactivateAIS(anAIS);
405     // the selection from the previous activation modes should be cleared manually (#26172)
406     aContext->LocalContext()->ClearOutdatedSelection(anAIS, true);
407     ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::deactivate -- ClearOutdatedSelection");
408     if (theUpdateViewer)
409       updateViewer();
410   }
411 }
412
413 void XGUI_Displayer::deactivateObjects(const QObjectPtrList& theObjList,
414                                        const bool theUpdateViewer)
415 {
416   //Handle(AIS_InteractiveObject) aTrihedron = getTrihedron();
417   //if (!aTrihedron.IsNull())
418   //  deactivateAIS(aTrihedron);
419
420   QObjectPtrList::const_iterator anIt = theObjList.begin(), aLast = theObjList.end();
421   for (; anIt != aLast; anIt++) {
422     deactivate(*anIt, false);
423   }
424   //VSV It seems that there is no necessity to update viewer on deactivation
425   //if (theUpdateViewer)
426   //  updateViewer();
427 }
428
429 void XGUI_Displayer::getModesOfActivation(ObjectPtr theObject, QIntList& theModes)
430 {
431   Handle(AIS_InteractiveContext) aContext = AISContext();
432   if (aContext.IsNull() || !isVisible(theObject))
433     return;
434
435   AISObjectPtr aAISObj = getAISObject(theObject);
436
437   if (aAISObj.get() != NULL) {
438     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
439     TColStd_ListOfInteger aTColModes;
440     aContext->ActivatedModes(anAISIO, aTColModes);
441     TColStd_ListIteratorOfListOfInteger itr( aTColModes );
442     for (; itr.More(); itr.Next() ) {
443       theModes.append(itr.Value());
444     }
445   }
446 }
447
448 int XGUI_Displayer::getSelectionMode(int theShapeType)
449 {
450   return (theShapeType > TopAbs_SHAPE) ? theShapeType : 
451                                          AIS_Shape::SelectionMode((TopAbs_ShapeEnum)theShapeType);
452 }
453
454 bool XGUI_Displayer::isVisible(XGUI_Displayer* theDisplayer, const ObjectPtr& theObject)
455 {
456   bool aVisible = false;
457   GeomPresentablePtr aPrs = std::dynamic_pointer_cast<GeomAPI_IPresentable>(theObject);
458   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
459   if (aPrs.get() || aResult.get()) {
460     aVisible = theDisplayer->isVisible(theObject);
461     // compsolid is not visualized in the viewer, but should have presentation when all sub solids are
462     // visible. It is useful for highlight presentation where compsolid shape is selectable
463     if (!aVisible && aResult.get() && aResult->groupName() == ModelAPI_ResultCompSolid::group()) {
464       ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(aResult);
465       if (aCompsolidResult.get() != NULL) { // change colors for all sub-solids
466         bool anAllSubsVisible = aCompsolidResult->numberOfSubs() > 0;
467         for(int i = 0; i < aCompsolidResult->numberOfSubs() && anAllSubsVisible; i++) {
468           anAllSubsVisible = theDisplayer->isVisible(aCompsolidResult->subResult(i));
469         }
470         aVisible = anAllSubsVisible;
471       }
472     }
473   }
474   // it is possible that feature is presentable and has results, so we should check visibility
475   // of results if presentation is not shown (e.g. Sketch Circle/Arc features)
476   if (!aVisible) {
477     // check if all results of the feature are visible
478     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
479     std::list<ResultPtr> aResults;
480     ModelAPI_Tools::allResults(aFeature, aResults);
481     std::list<ResultPtr>::const_iterator aIt;
482     aVisible = !aResults.empty();
483     for (aIt = aResults.begin(); aIt != aResults.end(); ++aIt) {
484       aVisible = aVisible && theDisplayer->isVisible(*aIt);
485     }
486   }
487   return aVisible;
488 }
489
490 #ifdef DEBUG_ACTIVATE_OBJECTS
491 QString getModeInfo(const int theMode)
492 {
493   QString anInfo = "Undefined";
494   switch(theMode) {
495     case 0: anInfo = "SHAPE(0)"; break;
496     case 1: anInfo = "VERTEX(1)"; break;
497     case 2: anInfo = "EDGE(2)"; break;
498     case 3: anInfo = "WIRE(3)"; break;
499     case 4: anInfo = "FACE(4)"; break;
500     case 5: anInfo = "SHELL(5)"; break;
501     case 6: anInfo = "SOLID(6)"; break;
502     case 7: anInfo = "COMPSOLID(7)"; break;
503     case 8: anInfo = "COMPOUND(8)"; break;
504     case 100: anInfo = "Sel_Mode_First(100)"; break; //SketcherPrs_Tools
505     case 101: anInfo = "Sel_Constraint(101)"; break;
506     case 102: anInfo = "Sel_Dimension_All(102)"; break;
507     case 103: anInfo = "Sel_Dimension_Line(103)"; break;
508     case 104: anInfo = "Sel_Dimension_Text(104)"; break;
509     default: break;
510   }
511   return anInfo;
512 }
513
514 QString getModesInfo(const QIntList& theModes)
515 {
516   QStringList aModesInfo;
517   for (int i = 0, aSize = theModes.size(); i < aSize; i++)
518     aModesInfo.append(getModeInfo(theModes[i]));
519   return QString("[%1] = %2").arg(aModesInfo.size()).arg(aModesInfo.join(", "));
520 }
521 #endif
522
523 void XGUI_Displayer::activateObjects(const QIntList& theModes, const QObjectPtrList& theObjList,
524                                      const bool theUpdateViewer)
525 {
526   // Convert shape types to selection types
527   QIntList aModes;
528   foreach(int aType, theModes) {
529     aModes.append(getSelectionMode(aType));
530   }
531
532 #ifdef DEBUG_ACTIVATE_OBJECTS
533   QStringList anInfo;
534   QObjectPtrList::const_iterator anIt = theObjList.begin(), aLast = theObjList.end();
535   for (; anIt != aLast; ++anIt) {
536     anInfo.append(ModuleBase_Tools::objectInfo((*anIt)));
537   }
538   QString anInfoStr = anInfo.join(", ");
539
540   qDebug(QString("activateObjects: new modes%1, active modes%2, objects[%3] = %4").
541     arg(getModesInfo(aModes)).
542     arg(getModesInfo(myActiveSelectionModes)).
543     arg(theObjList.size()).
544     arg(anInfoStr).
545     toStdString().c_str());
546 #endif
547   // In order to avoid doblications of selection modes
548   QIntList aNewModes;
549   foreach (int aMode, aModes) {
550     if (!aNewModes.contains(aMode))
551       aNewModes.append(aMode);
552   }
553   myActiveSelectionModes = aNewModes;
554   Handle(AIS_InteractiveContext) aContext = AISContext();
555   // Open local context if there is no one
556   if (aContext.IsNull() || !aContext->HasOpenedContext()) 
557     return;
558
559   //aContext->UseDisplayedObjects();
560   //myUseExternalObjects = true;
561
562   Handle(AIS_InteractiveObject) anAISIO;
563   AIS_ListOfInteractive aPrsList;
564   //if (aObjList.isEmpty())
565   //  return;
566   //else {
567   foreach(ObjectPtr aObj, theObjList) {
568     if (myResult2AISObjectMap.contains(aObj))
569       aPrsList.Append(myResult2AISObjectMap[aObj]->impl<Handle(AIS_InteractiveObject)>());
570   }
571   //}
572
573   // Add trihedron because it has to partisipate in selection
574   Handle(AIS_InteractiveObject) aTrihedron;
575   if (isTrihedronActive()) {
576     aTrihedron = getTrihedron();
577     if (!aTrihedron.IsNull() && aContext->IsDisplayed(aTrihedron))
578       aPrsList.Append(aTrihedron);
579   }
580   if (aPrsList.Extent() == 0)
581     return;
582
583   AIS_ListIteratorOfListOfInteractive aLIt(aPrsList);
584   bool isActivationChanged = false;
585   for(aLIt.Initialize(aPrsList); aLIt.More(); aLIt.Next()){
586     anAISIO = aLIt.Value();
587     if (activate(anAISIO, myActiveSelectionModes, false))
588       isActivationChanged = true;
589   }
590 }
591
592 bool XGUI_Displayer::isActive(ObjectPtr theObject) const
593 {
594   Handle(AIS_InteractiveContext) aContext = AISContext();
595   if (aContext.IsNull() || !isVisible(theObject))
596     return false;
597     
598   AISObjectPtr anObj = myResult2AISObjectMap[theObject];
599   Handle(AIS_InteractiveObject) anAIS = anObj->impl<Handle(AIS_InteractiveObject)>();
600
601   TColStd_ListOfInteger aModes;
602   aContext->ActivatedModes(anAIS, aModes);
603   return aModes.Extent() > 0;
604 }
605
606
607 void XGUI_Displayer::setSelected(const  QList<ModuleBase_ViewerPrsPtr>& theValues, bool theUpdateViewer)
608 {
609   Handle(AIS_InteractiveContext) aContext = AISContext();
610   if (aContext.IsNull())
611     return;
612   if (aContext->HasOpenedContext()) {
613     aContext->UnhilightSelected(false);
614     aContext->ClearSelected(false);
615     NCollection_DataMap<TopoDS_Shape, NCollection_Map<Handle(AIS_InteractiveObject)>> aShapesToBeSelected;
616
617     foreach (ModuleBase_ViewerPrsPtr aPrs, theValues) {
618       const GeomShapePtr& aGeomShape = aPrs->shape();
619       if (aGeomShape.get() && !aGeomShape->isNull()) {
620         const TopoDS_Shape& aShape = aGeomShape->impl<TopoDS_Shape>();
621 #ifdef DEBUG_OCCT_SHAPE_SELECTION
622         // problem 1: performance
623         // problem 2: IO is not specified, so the first found owner is selected, as a result
624         // it might belong to another result
625         aContext->AddOrRemoveSelected(aShape, false);
626 #else
627         NCollection_Map<Handle(AIS_InteractiveObject)> aPresentations;
628         if (aShapesToBeSelected.IsBound(aShape))
629           aPresentations = aShapesToBeSelected.Find(aShape);
630         ObjectPtr anObject = aPrs->object();
631         getPresentations(anObject, aPresentations);
632
633         aShapesToBeSelected.Bind(aShape, aPresentations);
634 #endif
635       } else {
636         ObjectPtr anObject = aPrs->object();
637         ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
638         if (aResult.get() && isVisible(aResult)) {
639           AISObjectPtr anObj = myResult2AISObjectMap[aResult];
640           Handle(AIS_InteractiveObject) anAIS = anObj->impl<Handle(AIS_InteractiveObject)>();
641           if (!anAIS.IsNull()) {
642             // The methods are replaced in order to provide multi-selection, e.g. restore selection
643             // by activating multi selector widget. It also gives an advantage that the multi
644             // selection in OB gives multi-selection in the viewer
645             //aContext->SetSelected(anAIS, false);
646             // The selection in the context was cleared, so the method sets the objects are selected
647             aContext->AddOrRemoveSelected(anAIS, false);
648           }
649         }
650       }
651     }
652     if (!aShapesToBeSelected.IsEmpty())
653       XGUI_Displayer::AddOrRemoveSelectedShapes(aContext, aShapesToBeSelected);
654   } else { // it seems the next code is obsolete as the context is always opened in SHAPER
655     aContext->UnhilightCurrents(false);
656     aContext->ClearCurrents(false);
657     foreach (ModuleBase_ViewerPrsPtr aPrs, theValues) {
658       ObjectPtr anObject = aPrs->object();
659       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
660       if (aResult.get() && isVisible(aResult)) {
661         AISObjectPtr anObj = myResult2AISObjectMap[aResult];
662         Handle(AIS_InteractiveObject) anAIS = anObj->impl<Handle(AIS_InteractiveObject)>();
663         if (!anAIS.IsNull())
664           aContext->SetCurrentObject(anAIS, false);
665       }
666     }
667   }
668   ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::setSelected -- AddOrRemoveSelected/UnhilightCurrents(no local context)");
669   if (theUpdateViewer)
670     updateViewer();
671 }
672
673 void XGUI_Displayer::clearSelected()
674 {
675   Handle(AIS_InteractiveContext) aContext = AISContext();
676   if (!aContext.IsNull()) {
677     aContext->UnhilightCurrents(false);
678     aContext->ClearSelected();
679   }
680 }
681
682 bool XGUI_Displayer::eraseAll(const bool theUpdateViewer)
683 {
684   bool aErased = false;
685   Handle(AIS_InteractiveContext) aContext = AISContext();
686   if (!aContext.IsNull()) {
687     foreach (ObjectPtr aObj, myResult2AISObjectMap.keys()) {
688       AISObjectPtr aAISObj = myResult2AISObjectMap[aObj];
689       // erase an object
690       Handle(AIS_InteractiveObject) anIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
691       if (!anIO.IsNull()) {
692         emit beforeObjectErase(aObj, aAISObj);
693         aContext->Remove(anIO, false/*update viewer*/);
694         aErased = true;
695       }
696     }
697     if (theUpdateViewer)
698       updateViewer();
699   }
700   ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::eraseAll -- Remove");
701   myResult2AISObjectMap.clear();
702 #ifdef DEBUG_DISPLAY
703   qDebug("eraseAll");
704   qDebug(getResult2AISObjectMapInfo().c_str());
705 #endif
706   return aErased;
707 }
708
709 void deactivateObject(Handle(AIS_InteractiveContext) theContext,
710                       Handle(AIS_InteractiveObject) theObject,
711                       const bool theClear = true)
712 {
713   if (!theObject.IsNull()) {
714     theContext->Deactivate(theObject);
715     ModuleBase_Tools::selectionInfo(theContext, "XGUI_Displayer::deactivateObject -- Deactivate");
716     //if (theClear) {
717       //theObject->ClearSelected();
718       //  theContext->LocalContext()->ClearOutdatedSelection(theObject, true);
719     //}
720   }
721 }
722
723 void XGUI_Displayer::deactivateTrihedron(const bool theUpdateViewer) const
724 {
725   Handle(AIS_InteractiveObject) aTrihedron = getTrihedron();
726   Handle(AIS_InteractiveContext) aContext = AISContext();
727   if (!aTrihedron.IsNull() && aContext->IsDisplayed(aTrihedron)) {
728     Handle(AIS_Trihedron) aTrie = Handle(AIS_Trihedron)::DownCast(aTrihedron);
729     deactivateObject(aContext, aTrie);
730
731     /// #1136 hidden axis are selected in sketch
732     /// workaround for Cascade: there is a crash in AIS_LocalContext::ClearOutdatedSelection
733     /// for Position AIS object in SelectionModes.
734     deactivateObject(aContext, aTrie->XAxis());
735     deactivateObject(aContext, aTrie->YAxis());
736     deactivateObject(aContext, aTrie->Axis());
737     deactivateObject(aContext, aTrie->Position());
738
739     deactivateObject(aContext, aTrie->XYPlane());
740     deactivateObject(aContext, aTrie->XZPlane());
741     deactivateObject(aContext, aTrie->YZPlane());
742
743     if (theUpdateViewer)
744       updateViewer();
745   }
746 }
747
748 Handle(AIS_InteractiveObject) XGUI_Displayer::getTrihedron() const
749 {
750   return myWorkshop->viewer()->trihedron();
751 }
752
753 void XGUI_Displayer::openLocalContext()
754 {
755   Handle(AIS_InteractiveContext) aContext = AISContext();
756   // Open local context if there is no one
757   if (!aContext.IsNull() && !aContext->HasOpenedContext()) {
758     // Preserve selected objects
759     //AIS_ListOfInteractive aAisList;
760     //for (aContext->InitCurrent(); aContext->MoreCurrent(); aContext->NextCurrent())
761     //  aAisList.Append(aContext->Current());
762
763     // get the filters from the global context and append them to the local context
764     // a list of filters in the global context is not cleared and should be cleared here
765     SelectMgr_ListOfFilter aFilters;
766     aFilters.Assign(aContext->Filters());
767     // it is important to remove the filters in the global context, because there is a code
768     // in the closeLocalContex, which restore the global context filters
769     aContext->RemoveFilters();
770
771     //aContext->ClearCurrents();
772     aContext->OpenLocalContext();
773     //deactivateTrihedron();
774     //aContext->NotUseDisplayedObjects();
775
776     //myUseExternalObjects = false;
777
778     SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
779     for (;aIt.More(); aIt.Next()) {
780       aContext->AddFilter(aIt.Value());
781     }
782     // Restore selection
783     //AIS_ListIteratorOfListOfInteractive aIt2(aAisList);
784     //for(; aIt2.More(); aIt2.Next()) {
785     //  aContext->SetSelected(aIt2.Value(), false);
786     //}
787   }
788 }
789
790 void XGUI_Displayer::closeLocalContexts(const bool theUpdateViewer)
791 {
792   Handle(AIS_InteractiveContext) aContext = AISContext();
793   if (!aContext.IsNull() && aContext->HasOpenedContext()) {
794     // Preserve selected objects
795     //AIS_ListOfInteractive aAisList;
796     //for (aContext->InitSelected(); aContext->MoreSelected(); aContext->NextSelected())
797     //  aAisList.Append(aContext->SelectedInteractive());
798
799     // get the filters from the local context and append them to the global context
800     // a list of filters in the local context is cleared
801     SelectMgr_ListOfFilter aFilters;
802     aFilters.Assign(aContext->Filters());
803
804     //aContext->ClearSelected();
805     aContext->CloseAllContexts(false);
806
807     // From the moment when the AIS_DS_Displayed flag is used in the Display of AIS object,
808     // this code is obsolete. It is temporaty commented and should be removed after
809     // the test campaign.
810     // Redisplay all object if they were displayed in localContext
811     /*Handle(AIS_InteractiveObject) aAISIO;
812     foreach (AISObjectPtr aAIS, myResult2AISObjectMap) {
813       aAISIO = aAIS->impl<Handle(AIS_InteractiveObject)>();
814       if (aContext->DisplayStatus(aAISIO) != AIS_DS_Displayed) {
815         aContext->Display(aAISIO, false);
816         aContext->SetDisplayMode(aAISIO, Shading, false);
817       }
818     }*/
819
820     // Append the filters from the local selection in the global selection context
821     SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
822     for (;aIt.More(); aIt.Next()) {
823       Handle(SelectMgr_Filter) aFilter = aIt.Value();
824       aContext->AddFilter(aFilter);
825     }
826
827     if (theUpdateViewer)
828       updateViewer();
829     //myUseExternalObjects = false;
830
831     // Restore selection
832     //AIS_ListIteratorOfListOfInteractive aIt2(aAisList);
833     //for(; aIt2.More(); aIt2.Next()) {
834     //  if (aContext->IsDisplayed(aIt2.Value()))
835     //    aContext->SetCurrentObject(aIt2.Value(), false);
836     //}
837   }
838 }
839
840 AISObjectPtr XGUI_Displayer::getAISObject(ObjectPtr theObject) const
841 {
842   AISObjectPtr anIO;
843   if (myResult2AISObjectMap.contains(theObject))
844     anIO = myResult2AISObjectMap[theObject];
845   return anIO;
846 }
847
848 ObjectPtr XGUI_Displayer::getObject(const AISObjectPtr& theIO) const
849 {
850   Handle(AIS_InteractiveObject) aRefAIS = theIO->impl<Handle(AIS_InteractiveObject)>();
851   return getObject(aRefAIS);
852 }
853
854 ObjectPtr XGUI_Displayer::getObject(const Handle(AIS_InteractiveObject)& theIO) const
855 {
856   ObjectPtr anObject;
857   foreach (ObjectPtr anObj, myResult2AISObjectMap.keys()) {
858     AISObjectPtr aAIS = myResult2AISObjectMap[anObj];
859     Handle(AIS_InteractiveObject) anAIS = aAIS->impl<Handle(AIS_InteractiveObject)>();
860     if (anAIS == theIO)
861       anObject = anObj;
862     if (anObject.get())
863       break;
864   }
865   if (!anObject.get()) {
866     std::shared_ptr<GeomAPI_AISObject> anAISObj = AISObjectPtr(new GeomAPI_AISObject());
867     if (!theIO.IsNull()) {
868       anAISObj->setImpl(new Handle(AIS_InteractiveObject)(theIO));
869     }
870     anObject = myWorkshop->module()->findPresentedObject(anAISObj);
871   }
872   return anObject;
873 }
874
875 bool XGUI_Displayer::enableUpdateViewer(const bool isEnabled)
876 {
877   bool aWasEnabled = isUpdateEnabled();
878   if (isEnabled)
879     myViewerBlockedRecursiveCount--;
880   else
881     myViewerBlockedRecursiveCount++;
882
883   if (myNeedUpdate && isUpdateEnabled()) {
884     updateViewer();
885     myNeedUpdate = false;
886   }
887   return aWasEnabled;
888 }
889
890 bool XGUI_Displayer::isUpdateEnabled() const
891 {
892   return myViewerBlockedRecursiveCount == 0;
893 }
894
895 void XGUI_Displayer::updateViewer() const
896 {
897   Handle(AIS_InteractiveContext) aContext = AISContext();
898   if (!aContext.IsNull() && isUpdateEnabled()) {
899     myWorkshop->viewer()->Zfitall();
900     aContext->UpdateCurrentViewer();
901   } else {
902     myNeedUpdate = true;
903   }
904 }
905
906 void XGUI_Displayer::activateAIS(const Handle(AIS_InteractiveObject)& theIO,
907                                  const int theMode, const bool theUpdateViewer) const
908 {
909   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
910   if (!aContext.IsNull()) {
911     if (myWorkshop->module()) {
912       int aMode = (theMode > 8)? theMode : AIS_Shape::SelectionType(theMode);
913       aContext->Activate(theIO, theMode, false);
914     } else
915       aContext->Activate(theIO, theMode, false);
916
917     // the fix from VPA for more suitable selection of sketcher lines
918     if (theIO->Width() > 1) {
919       double aPrecision = theIO->Width() + 2;
920       if (theMode == getSelectionMode(TopAbs_VERTEX)) 
921         aPrecision = ModuleBase_Preferences::resourceMgr()->doubleValue("Viewer", "point-selection-sensitivity", 20);
922       else if ((theMode == getSelectionMode(TopAbs_EDGE)) || (theMode == getSelectionMode(TopAbs_WIRE)))
923         aPrecision = theIO->Width() + 
924                      ModuleBase_Preferences::resourceMgr()->doubleValue("Viewer", "edge-selection-sensitivity", 2);
925       aContext->SetSelectionSensitivity(theIO, theMode, aPrecision);
926     }
927     ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::activateAIS -- Activate");
928
929 #ifdef DEBUG_ACTIVATE_AIS
930     ObjectPtr anObject = getObject(theIO);
931     anInfo.append(ModuleBase_Tools::objectInfo((*anIt)));
932     qDebug(QString("activateAIS: theMode = %1, object = %2").arg(theMode).arg(anInfo).toStdString().c_str());
933 #endif
934     if (theUpdateViewer)
935       updateViewer();
936   }
937 }
938
939 void XGUI_Displayer::deactivateAIS(const Handle(AIS_InteractiveObject)& theIO, const int theMode) const
940 {
941   Handle(AIS_InteractiveContext) aContext = AISContext();
942   if (!aContext.IsNull()) {
943     if (theMode == -1)
944       aContext->Deactivate(theIO);
945     else 
946       aContext->Deactivate(theIO, theMode);
947     ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::deactivateAIS -- Deactivate");
948    
949 #ifdef DEBUG_DEACTIVATE_AIS
950     ObjectPtr anObject = getObject(theIO);
951     anInfo.append(ModuleBase_Tools::objectInfo((*anIt)));
952     qDebug(QString("deactivateAIS: theMode = %1, object = %2").arg(theMode).arg(anInfo).toStdString().c_str());
953 #endif
954   }
955 }
956
957 Handle(AIS_InteractiveContext) XGUI_Displayer::AISContext() const
958 {
959   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
960   if (!aContext.IsNull() && !aContext->HasOpenedContext()) {
961     aContext->OpenLocalContext();
962     if (!isTrihedronActive())
963       deactivateTrihedron(true);
964     aContext->DefaultDrawer()->VIsoAspect()->SetNumber(0);
965     aContext->DefaultDrawer()->UIsoAspect()->SetNumber(0);
966   }
967   return aContext;
968 }
969
970 Handle(SelectMgr_AndFilter) XGUI_Displayer::GetFilter()
971 {
972   Handle(AIS_InteractiveContext) aContext = AISContext();
973   if (!aContext.IsNull() && myAndFilter.IsNull()) {
974     myAndFilter = new SelectMgr_AndFilter();
975     aContext->AddFilter(myAndFilter);
976   }
977   return myAndFilter;
978 }
979
980 bool XGUI_Displayer::displayAIS(AISObjectPtr theAIS, const bool toActivateInSelectionModes,
981                                 bool theUpdateViewer)
982 {
983   bool aDisplayed = false;
984   Handle(AIS_InteractiveContext) aContext = AISContext();
985   Handle(AIS_InteractiveObject) anAISIO = theAIS->impl<Handle(AIS_InteractiveObject)>();
986   if (!aContext.IsNull() && !anAISIO.IsNull()) {
987     aContext->Display(anAISIO, 0/*wireframe*/, 0, false/*update viewer*/, true, AIS_DS_Displayed);
988     aDisplayed = true;
989     aContext->Deactivate(anAISIO);
990     aContext->Load(anAISIO);
991     if (toActivateInSelectionModes) {
992       if (aContext->HasOpenedContext()) {
993         if (myActiveSelectionModes.size() == 0)
994           activateAIS(anAISIO, 0, theUpdateViewer);
995         else {
996           foreach(int aMode, myActiveSelectionModes) {
997             activateAIS(anAISIO, aMode, theUpdateViewer);
998           }
999         }
1000       }
1001     }
1002     if (theUpdateViewer)
1003       updateViewer();
1004   }
1005   return aDisplayed;
1006 }
1007
1008 bool XGUI_Displayer::eraseAIS(AISObjectPtr theAIS, const bool theUpdateViewer)
1009 {
1010   bool aErased = false;
1011   Handle(AIS_InteractiveContext) aContext = AISContext();
1012   if (!aContext.IsNull()) {
1013     Handle(AIS_InteractiveObject) anAISIO = theAIS->impl<Handle(AIS_InteractiveObject)>();
1014     if (!anAISIO.IsNull() && aContext->IsDisplayed(anAISIO)) {
1015       aContext->Remove(anAISIO, false/*update viewer*/);
1016       ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::eraseAIS -- Remove");
1017       aErased = true;
1018     }
1019   }
1020   if (aErased && theUpdateViewer)
1021     updateViewer();
1022   return aErased;
1023 }
1024
1025
1026 void XGUI_Displayer::setDisplayMode(ObjectPtr theObject, DisplayMode theMode, bool theUpdateViewer)
1027 {
1028   if (theMode == NoMode)
1029     return;
1030
1031   Handle(AIS_InteractiveContext) aContext = AISContext();
1032   if (aContext.IsNull())
1033     return;
1034
1035   AISObjectPtr aAISObj = getAISObject(theObject);
1036   if (!aAISObj)
1037     return;
1038
1039   Handle(AIS_InteractiveObject) aAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1040   aContext->SetDisplayMode(aAISIO, theMode, false);
1041   // Redisplay in order to update new mode because it could be not computed before
1042   if (theUpdateViewer)
1043     updateViewer();
1044 }
1045
1046 XGUI_Displayer::DisplayMode XGUI_Displayer::displayMode(ObjectPtr theObject) const
1047 {
1048   Handle(AIS_InteractiveContext) aContext = AISContext();
1049   if (aContext.IsNull())
1050     return NoMode;
1051
1052   AISObjectPtr aAISObj = getAISObject(theObject);
1053   if (!aAISObj)
1054     return NoMode;
1055
1056   Handle(AIS_InteractiveObject) aAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1057   return (XGUI_Displayer::DisplayMode) aAISIO->DisplayMode();
1058 }
1059
1060 void XGUI_Displayer::deactivateSelectionFilters()
1061 {
1062   Handle(AIS_InteractiveContext) aContext = AISContext();
1063   if (!myAndFilter.IsNull()) {
1064     bool aFound = false;
1065     if (!aContext.IsNull()) {
1066       const SelectMgr_ListOfFilter& aFilters = aContext->Filters();
1067       SelectMgr_ListIteratorOfListOfFilter anIt(aFilters);
1068       for (; anIt.More() && !aFound; anIt.Next()) {
1069         Handle(SelectMgr_Filter) aFilter = anIt.Value();
1070         aFound = aFilter == myAndFilter;
1071       }
1072       if (aFound)
1073         aContext->RemoveFilter(myAndFilter);
1074     }
1075     myAndFilter.Nullify();
1076   }
1077 }
1078
1079 void XGUI_Displayer::addSelectionFilter(const Handle(SelectMgr_Filter)& theFilter)
1080 {
1081   Handle(AIS_InteractiveContext) aContext = AISContext();
1082   if (aContext.IsNull() || hasSelectionFilter(theFilter))
1083     return;
1084
1085   Handle(SelectMgr_CompositionFilter) aCompositeFilter = GetFilter();
1086   if (!aCompositeFilter.IsNull()) {
1087     aCompositeFilter->Add(theFilter);
1088 #ifdef DEBUG_SELECTION_FILTERS
1089     int aCount = aCompositeFilter->StoredFilters().Extent();
1090     qDebug(QString("addSelectionFilter: filters.count() = %1").arg(aCount).toStdString().c_str());
1091 #endif
1092   }
1093 }
1094
1095 void XGUI_Displayer::removeSelectionFilter(const Handle(SelectMgr_Filter)& theFilter)
1096 {
1097   Handle(AIS_InteractiveContext) aContext = AISContext();
1098   if (aContext.IsNull())
1099     return;
1100
1101   Handle(SelectMgr_AndFilter) aCompositeFilter = GetFilter();
1102   if (!aCompositeFilter.IsNull() && aCompositeFilter->IsIn(theFilter)) {
1103     aCompositeFilter->Remove(theFilter);
1104 #ifdef DEBUG_SELECTION_FILTERS
1105     int aCount = aCompositeFilter->StoredFilters().Extent();
1106     qDebug(QString("removeSelectionFilter: filters.count() = %1").arg(aCount).toStdString().c_str());
1107 #endif
1108   }
1109 }
1110
1111 bool XGUI_Displayer::hasSelectionFilter(const Handle(SelectMgr_Filter)& theFilter)
1112 {
1113   bool aFilterFound = false;
1114
1115   Handle(AIS_InteractiveContext) aContext = AISContext();
1116   if (aContext.IsNull())
1117     return aFilterFound;
1118   const SelectMgr_ListOfFilter& aFilters = aContext->Filters();
1119   SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
1120   for (; aIt.More() && !aFilterFound; aIt.Next()) {
1121     if (theFilter.Access() == aIt.Value().Access())
1122       aFilterFound = true;
1123   }
1124   Handle(SelectMgr_CompositionFilter) aCompositeFilter = GetFilter();
1125   if (!aCompositeFilter.IsNull()) {
1126     const SelectMgr_ListOfFilter& aStoredFilters = aCompositeFilter->StoredFilters();
1127     for (aIt.Initialize(aStoredFilters); aIt.More() && !aFilterFound; aIt.Next()) {
1128       if (theFilter.Access() == aIt.Value().Access())
1129         aFilterFound = true;
1130     }
1131   }
1132   return aFilterFound;
1133 }
1134
1135 void XGUI_Displayer::removeFilters()
1136 {
1137   Handle(AIS_InteractiveContext) aContext = AISContext();
1138   if (aContext.IsNull())
1139     return;
1140
1141   Handle(SelectMgr_CompositionFilter) aCompositeFilter = GetFilter();
1142   if (!aCompositeFilter.IsNull())
1143     aCompositeFilter->Clear();
1144 }
1145
1146 void XGUI_Displayer::showOnly(const QObjectPtrList& theList)
1147 {
1148   QObjectPtrList aDispList = myResult2AISObjectMap.keys();
1149   foreach(ObjectPtr aObj, aDispList) {
1150     if (!theList.contains(aObj))
1151       erase(aObj, false);
1152   }
1153   foreach(ObjectPtr aObj, theList) {
1154     if (!isVisible(aObj))
1155       display(aObj, false);
1156   }
1157   updateViewer();
1158 }
1159
1160 bool XGUI_Displayer::canBeShaded(ObjectPtr theObject) const
1161
1162   if (!isVisible(theObject))
1163     return false;
1164
1165   AISObjectPtr aAISObj = getAISObject(theObject);
1166   if (aAISObj.get() == NULL)
1167     return false;
1168
1169   Handle(AIS_InteractiveObject) anAIS = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1170   return ::canBeShaded(anAIS, myWorkshop->module());
1171 }
1172
1173 bool XGUI_Displayer::activate(const Handle(AIS_InteractiveObject)& theIO,
1174                               const QIntList& theModes,
1175                               const bool theUpdateViewer) const
1176 {
1177   Handle(AIS_InteractiveContext) aContext = AISContext();
1178   if (aContext.IsNull() || theIO.IsNull())
1179     return false;
1180   
1181   bool isActivationChanged = false;
1182   // deactivate object in all modes, which are not in the list of activation
1183   // It seems that after the IO deactivation the selected state of the IO's owners
1184   // is modified in OCC(version: 6.8.0) and the selection of the object later is lost.
1185   // By this reason, the number of the IO deactivate is decreased and the object is deactivated
1186   // only if there is a difference in the current modes and the parameters modes.
1187   // If the selection problem happens again, it is possible to write a test scenario and create
1188   // a bug. The bug steps are the following:
1189   // Create two IO, activate them in 5 modes, select the first IO, deactivate 3 modes for both,
1190   // with clicked SHIFT select the second object. The result is the selection of the first IO is lost.
1191   TColStd_ListOfInteger aTColModes;
1192   aContext->ActivatedModes(theIO, aTColModes);
1193   TColStd_ListIteratorOfListOfInteger itr( aTColModes );
1194   QIntList aModesActivatedForIO;
1195   bool isDeactivated = false;
1196   for (; itr.More(); itr.Next() ) {
1197     Standard_Integer aMode = itr.Value();
1198     int aShapeMode = (aMode > 8)? aMode : AIS_Shape::SelectionType(aMode);
1199     if (!theModes.contains(aMode)) {
1200       deactivateAIS(theIO, aMode);
1201       isDeactivated = true;
1202     }
1203     else {
1204       aModesActivatedForIO.append(aMode);
1205     }
1206   }
1207   if (isDeactivated) {
1208     // the selection from the previous activation modes should be cleared manually (#26172)
1209     theIO->ClearSelected();
1210     aContext->LocalContext()->ClearOutdatedSelection(theIO, true);
1211     ModuleBase_Tools::selectionInfo(aContext, "XGUI_Displayer::activate -- ClearSelected/ClearOutdatedSelection");
1212     // For performance issues
1213     //if (theUpdateViewer)
1214     //  updateViewer();
1215     isActivationChanged = true;
1216   }
1217
1218   // loading the interactive object allowing the decomposition
1219   if (aTColModes.IsEmpty()) {
1220     aContext->Load(theIO, -1, true);
1221   }
1222
1223   // trihedron AIS check should be after the AIS loading.
1224   // If it is not loaded, it is steel selectable in the viewer.
1225   Handle(AIS_Trihedron) aTrihedron;
1226   if (!isTrihedronActive())
1227     aTrihedron = Handle(AIS_Trihedron)::DownCast(theIO);
1228   if (aTrihedron.IsNull()) {
1229       // In order to clear active modes list
1230     if (theModes.size() == 0) {
1231       activateAIS(theIO, 0, theUpdateViewer);
1232     } else {
1233       foreach(int aMode, theModes) {
1234         if (!aModesActivatedForIO.contains(aMode)) {
1235           activateAIS(theIO, aMode, theUpdateViewer);
1236           isActivationChanged = true;
1237         }
1238       }
1239     }
1240   }
1241   return isActivationChanged;
1242 }
1243
1244 bool XGUI_Displayer::customizeObject(ObjectPtr theObject)
1245 {
1246   AISObjectPtr anAISObj = getAISObject(theObject);
1247   // correct the result's color it it has the attribute
1248   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1249
1250   // Customization of presentation
1251   GeomCustomPrsPtr aCustomPrs;
1252   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1253   if (aFeature.get() != NULL) {
1254     GeomCustomPrsPtr aCustPrs = std::dynamic_pointer_cast<GeomAPI_ICustomPrs>(aFeature);
1255     if (aCustPrs.get() != NULL)
1256       aCustomPrs = aCustPrs;
1257   }
1258   if (aCustomPrs.get() == NULL) {
1259     GeomPresentablePtr aPrs = std::dynamic_pointer_cast<GeomAPI_IPresentable>(theObject);
1260     // we ignore presentable not customized objects
1261     if (aPrs.get() == NULL)
1262       aCustomPrs = myCustomPrs;
1263   }
1264   bool isCustomized = aCustomPrs.get() &&
1265                       aCustomPrs->customisePresentation(aResult, anAISObj, myCustomPrs);
1266   return isCustomized;
1267 }
1268
1269
1270 QColor XGUI_Displayer::setObjectColor(ObjectPtr theObject, const QColor& theColor, bool theUpdateViewer)
1271 {
1272   if (!isVisible(theObject))
1273     return Qt::black;
1274
1275   AISObjectPtr anAISObj = getAISObject(theObject);
1276   int aR, aG, aB;
1277   anAISObj->getColor(aR, aG, aB);
1278   anAISObj->setColor(theColor.red(), theColor.green(), theColor.blue());
1279   if (theUpdateViewer)
1280     updateViewer();
1281   return QColor(aR, aG, aB);
1282 }
1283
1284 void XGUI_Displayer::appendResultObject(ObjectPtr theObject, AISObjectPtr theAIS)
1285 {
1286   myResult2AISObjectMap[theObject] = theAIS;
1287
1288 #ifdef DEBUG_DISPLAY
1289   std::ostringstream aPtrStr;
1290   aPtrStr << theObject.get();
1291   qDebug(QString("display object: %1").arg(aPtrStr.str().c_str()).toStdString().c_str());
1292   qDebug(getResult2AISObjectMapInfo().c_str());
1293 #endif
1294 }
1295
1296 std::string XGUI_Displayer::getResult2AISObjectMapInfo() const
1297 {
1298   QStringList aContent;
1299   foreach (ObjectPtr aObj, myResult2AISObjectMap.keys()) {
1300     AISObjectPtr aAISObj = myResult2AISObjectMap[aObj];
1301     std::ostringstream aPtrStr;
1302     aPtrStr << "aObj = " << aObj.get() << ":";
1303     aPtrStr << "anAIS = " << aAISObj.get() << ":";
1304     aPtrStr << "[" << ModuleBase_Tools::objectInfo(aObj).toStdString().c_str() << "]";
1305     
1306     aContent.append(aPtrStr.str().c_str());
1307   }
1308   return QString("myResult2AISObjectMap: size = %1\n%2\n").arg(myResult2AISObjectMap.size()).
1309                                             arg(aContent.join("\n")).toStdString().c_str();
1310 }
1311
1312 void XGUI_Displayer::getPresentations(const ObjectPtr& theObject,
1313                                   NCollection_Map<Handle(AIS_InteractiveObject)>& thePresentations)
1314 {
1315   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1316   if (aResult.get()) {
1317     AISObjectPtr aAISObj = getAISObject(aResult);
1318     if (aAISObj.get() != NULL) {
1319       Handle(AIS_InteractiveObject) anAIS = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1320       if (!anAIS.IsNull() && !thePresentations.Contains(anAIS))
1321         thePresentations.Add(anAIS);
1322     }
1323   }
1324   else {
1325     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
1326     // find presentation of the feature
1327     AISObjectPtr aAISObj = getAISObject(aFeature);
1328     if (aAISObj.get() != NULL) {
1329       Handle(AIS_InteractiveObject) anAIS = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1330       if (!anAIS.IsNull() && !thePresentations.Contains(anAIS))
1331         thePresentations.Add(anAIS);
1332     }
1333     // find presentations of the feature results
1334     std::list<ResultPtr> aResults;
1335     ModelAPI_Tools::allResults(aFeature, aResults);
1336     std::list<ResultPtr>::const_iterator anIt = aResults.begin(), aLast = aResults.end();
1337     for (; anIt != aLast; ++anIt) {
1338       AISObjectPtr aAISObj = getAISObject(*anIt);
1339       if (aAISObj.get() != NULL) {
1340         Handle(AIS_InteractiveObject) anAIS = aAISObj->impl<Handle(AIS_InteractiveObject)>();
1341         if (!anAIS.IsNull() && !thePresentations.Contains(anAIS))
1342           thePresentations.Add(anAIS);
1343       }
1344     }
1345   }
1346 }
1347
1348 void XGUI_Displayer::activateTrihedron(bool theIsActive) 
1349 {  
1350   myIsTrihedronActive = theIsActive; 
1351   if (!myIsTrihedronActive) {
1352     deactivateTrihedron(true);
1353   }
1354 }
1355
1356 void XGUI_Displayer::displayTrihedron(bool theToDisplay) const
1357 {
1358   Handle(AIS_InteractiveContext) aContext = AISContext();
1359   if (aContext.IsNull())
1360     return;
1361
1362   Handle(AIS_Trihedron) aTrihedron = myWorkshop->viewer()->trihedron();
1363
1364   if (theToDisplay) {
1365     if (!aContext->IsDisplayed(aTrihedron))
1366       aContext->Display(aTrihedron,
1367                         0 /*wireframe*/,
1368                         -1 /* selection mode */,
1369                         Standard_True /* update viewer*/,
1370                         Standard_False /* allow decomposition */,
1371                         AIS_DS_Displayed /* xdisplay status */);
1372
1373     if (!isTrihedronActive())
1374       deactivateTrihedron(false);
1375     else
1376       activate(aTrihedron, myActiveSelectionModes, false);
1377   } else {
1378     deactivateTrihedron(false);
1379     //aContext->LocalContext()->ClearOutdatedSelection(aTrihedron, true);
1380     // the selection from the previous activation modes should be cleared manually (#26172)
1381
1382     aContext->Erase(aTrihedron);
1383   }
1384
1385   updateViewer();
1386 }
1387
1388 QIntList XGUI_Displayer::activeSelectionModes() const 
1389
1390   QIntList aModes;
1391   foreach (int aMode, myActiveSelectionModes) {
1392     // aMode < 9 is a Shape Enum values
1393     aModes << ((aMode < 9)? AIS_Shape::SelectionType(aMode) : aMode);
1394   }
1395   return aModes; 
1396 }
1397
1398 void XGUI_Displayer::AddOrRemoveSelectedShapes(Handle(AIS_InteractiveContext) theContext,
1399  const NCollection_DataMap<TopoDS_Shape,
1400                            NCollection_Map<Handle(AIS_InteractiveObject)>>& theShapesToBeSelected)
1401 {
1402   Handle(AIS_LocalContext) aLContext = theContext->LocalContext();
1403   TCollection_AsciiString aSelectionName = aLContext->SelectionName();
1404   aLContext->UnhilightPicked(Standard_False);
1405
1406   NCollection_List<Handle(SelectBasics_EntityOwner)> anActiveOwners;
1407   aLContext->MainSelector()->ActiveOwners(anActiveOwners);
1408   NCollection_List<Handle(SelectBasics_EntityOwner)>::Iterator anOwnersIt (anActiveOwners);
1409   Handle(SelectMgr_EntityOwner) anOwner;
1410   for (; anOwnersIt.More(); anOwnersIt.Next()) {
1411     anOwner = Handle(SelectMgr_EntityOwner)::DownCast (anOwnersIt.Value());
1412     Handle(StdSelect_BRepOwner) BROwnr = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
1413     if (!BROwnr.IsNull() && BROwnr->HasShape()) {
1414       const TopoDS_Shape& aShape = BROwnr->Shape();
1415       if (!aShape.IsNull() && theShapesToBeSelected.IsBound(aShape)) {
1416         Handle(AIS_InteractiveObject) anOwnerPresentation =
1417                                     Handle(AIS_InteractiveObject)::DownCast(anOwner->Selectable());
1418         NCollection_Map<Handle(AIS_InteractiveObject)> aPresentations =
1419                                     theShapesToBeSelected.Find(aShape);
1420         if (aPresentations.Contains(anOwnerPresentation)) {
1421           AIS_Selection::Selection(aSelectionName.ToCString())->Select(anOwner);
1422           anOwner->SetSelected (Standard_True);
1423         }
1424       }
1425     }
1426   }
1427   aLContext->HilightPicked(Standard_False);
1428 }