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