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