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