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