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