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