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