Salome HOME
cb24aa4805330e5ddee73462098a363f59af5458
[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 #include <AppElements_Viewer.h>
15
16 #include <ModelAPI_Document.h>
17 #include <ModelAPI_Data.h>
18 #include <ModelAPI_Object.h>
19 #include <ModelAPI_Tools.h>
20 #include <ModelAPI_AttributeIntArray.h>
21 #include <ModelAPI_ResultCompSolid.h>
22
23 #include <ModuleBase_ResultPrs.h>
24 #include <ModuleBase_Tools.h>
25 #include <ModuleBase_IModule.h>
26
27 #include <GeomAPI_Shape.h>
28 #include <GeomAPI_IPresentable.h>
29 #include <GeomAPI_ICustomPrs.h>
30
31 #include <AIS_InteractiveContext.hxx>
32 #include <AIS_LocalContext.hxx>
33 #include <AIS_ListOfInteractive.hxx>
34 #include <AIS_ListIteratorOfListOfInteractive.hxx>
35 #include <AIS_DimensionSelectionMode.hxx>
36 #include <AIS_Shape.hxx>
37 #include <AIS_Dimension.hxx>
38 #include <TColStd_ListIteratorOfListOfInteger.hxx>
39 #include <SelectMgr_ListOfFilter.hxx>
40 #include <SelectMgr_ListIteratorOfListOfFilter.hxx>
41 #include <Prs3d_Drawer.hxx>
42 #include <Prs3d_IsoAspect.hxx>
43
44 #include <StdSelect_ViewerSelector3d.hxx>
45
46 #include <TColStd_MapOfTransient.hxx>
47 #include <TColStd_MapIteratorOfMapOfTransient.hxx>
48
49 #include <Events_Loop.h>
50 #include <ModelAPI_Events.h>
51
52 #include <set>
53
54 const int MOUSE_SENSITIVITY_IN_PIXEL = 10;  ///< defines the local context mouse selection sensitivity
55
56 //#define DEBUG_ACTIVATE_OBJECTS
57 //#define DEBUG_DEACTIVATE
58 //#define DEBUG_ACTIVATE_AIS
59 //#define DEBUG_DEACTIVATE_AIS
60
61 //#define DEBUG_DISPLAY
62 //#define DEBUG_FEATURE_REDISPLAY
63 //#define DEBUG_SELECTION_FILTERS
64
65 //#define DEBUG_COMPOSILID_DISPLAY
66 // Workaround for bug #25637
67 void displayedObjects(const Handle(AIS_InteractiveContext)& theAIS, AIS_ListOfInteractive& theList)
68 {
69   // Get from null point
70   theAIS->DisplayedObjects(theList, true);
71   if (theAIS->HasOpenedContext()) {
72     // get from local context
73     const Handle(AIS_LocalContext)& aLC = theAIS->LocalContext();
74     TColStd_MapOfTransient aMap;
75     int NbDisp = aLC->DisplayedObjects(aMap);
76     TColStd_MapIteratorOfMapOfTransient aIt(aMap);
77
78     Handle(AIS_InteractiveObject) curIO;
79     Handle(Standard_Transient) Tr;
80     for(; aIt.More(); aIt.Next()){
81       Tr = aIt.Key();
82       curIO = *((Handle(AIS_InteractiveObject)*) &Tr);
83       theList.Append(curIO);
84     }
85   }
86 }
87
88 QString qIntListInfo(const QIntList& theValues, const QString& theSeparator = QString(", "))
89 {
90   QStringList anInfo;
91   QIntList::const_iterator anIt = theValues.begin(), aLast = theValues.end();
92   for (; anIt != aLast; anIt++) {
93     anInfo.append(QString::number(*anIt));
94   }
95   return anInfo.join(theSeparator);
96 }
97
98 XGUI_Displayer::XGUI_Displayer(XGUI_Workshop* theWorkshop)
99   : myWorkshop(theWorkshop)
100 {
101   enableUpdateViewer(true);
102   myCustomPrs = std::shared_ptr<GeomAPI_ICustomPrs>(new XGUI_CustomPrs());
103 }
104
105 XGUI_Displayer::~XGUI_Displayer()
106 {
107 }
108
109 bool XGUI_Displayer::isVisible(ObjectPtr theObject) const
110 {
111   return myResult2AISObjectMap.contains(theObject);
112 }
113
114 bool XGUI_Displayer::display(ObjectPtr theObject, bool theUpdateViewer)
115 {
116   bool aDisplayed = false;
117   if (isVisible(theObject)) {
118 #ifdef DEBUG_COMPOSILID_DISPLAY
119     ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
120     if (aCompsolidResult.get()) {
121       for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
122         ResultPtr aSubResult = aCompsolidResult->subResult(i);
123         if (aSubResult.get())
124           redisplay(aSubResult, false);
125       }
126       if (theUpdateViewer)
127         updateViewer();
128     }
129     else
130 #endif
131     aDisplayed = redisplay(theObject, theUpdateViewer);
132   } else {
133     AISObjectPtr anAIS;
134     GeomPresentablePtr aPrs = std::dynamic_pointer_cast<GeomAPI_IPresentable>(theObject);
135     bool isShading = false;
136     if (aPrs.get() != NULL) {
137       anAIS = aPrs->getAISObject(anAIS);
138     } else {
139       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
140       if (aResult.get() != NULL) {
141 #ifdef DEBUG_COMPOSILID_DISPLAY
142         ResultCompSolidPtr aCompsolidResult = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(theObject);
143         if (aCompsolidResult.get()) {
144           for(int i = 0; i < aCompsolidResult->numberOfSubs(); i++) {
145             ResultPtr aSubResult = aCompsolidResult->subResult(i);
146             if (aSubResult.get())
147               display(aSubResult, false);
148           }
149           if (theUpdateViewer)
150             updateViewer();
151         }
152         else {
153 #endif
154         std::shared_ptr<GeomAPI_Shape> aShapePtr = ModelAPI_Tools::shape(aResult);
155         if (aShapePtr.get() != NULL) {
156           anAIS = AISObjectPtr(new GeomAPI_AISObject());
157           anAIS->setImpl(new Handle(AIS_InteractiveObject)(new ModuleBase_ResultPrs(aResult)));
158           //anAIS->createShape(aShapePtr);
159           isShading = true;
160         }
161 #ifdef DEBUG_COMPOSILID_DISPLAY
162         } // close else
163 #endif
164       }
165     }
166     if (anAIS)
167       aDisplayed = display(theObject, anAIS, isShading, theUpdateViewer);
168   }
169   return aDisplayed;
170 }
171
172 bool canBeShaded(Handle(AIS_InteractiveObject) theAIS)
173 {
174   Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(theAIS);
175   if (!aShapePrs.IsNull()) {
176     TopoDS_Shape aShape = aShapePrs->Shape();
177     if (aShape.IsNull())
178       return false;
179     TopAbs_ShapeEnum aType = aShape.ShapeType();
180     if ((aType == TopAbs_VERTEX) || (aType == TopAbs_EDGE) || (aType == TopAbs_WIRE))
181       return false;
182     else {
183       // Check that the presentation is not a sketch
184       Handle(ModuleBase_ResultPrs) aPrs = Handle(ModuleBase_ResultPrs)::DownCast(theAIS);
185       if (!aPrs.IsNull()) 
186         return !aPrs->isSketchMode();
187       return true;
188     }
189   }
190   return false;
191 }
192
193 bool XGUI_Displayer::display(ObjectPtr theObject, AISObjectPtr theAIS, 
194                              bool isShading, bool theUpdateViewer)
195 {
196   bool aDisplayed = false;
197
198   Handle(AIS_InteractiveContext) aContext = AISContext();
199   if (aContext.IsNull())
200     return aDisplayed;
201
202   Handle(AIS_InteractiveObject) anAISIO = theAIS->impl<Handle(AIS_InteractiveObject)>();
203   if (!anAISIO.IsNull()) {
204     appendResultObject(theObject, theAIS);
205
206     bool isCustomized = customizeObject(theObject);
207
208     int aDispMode = isShading? Shading : Wireframe;
209     if (isShading)
210       anAISIO->Attributes()->SetFaceBoundaryDraw( Standard_True );
211     anAISIO->SetDisplayMode(aDispMode);
212     aContext->Display(anAISIO, aDispMode, 0, false, true, AIS_DS_Displayed); 
213     aDisplayed = true;
214
215     emit objectDisplayed(theObject, theAIS);
216     activate(anAISIO, myActiveSelectionModes, theUpdateViewer);
217     // the fix from VPA for more suitable selection of sketcher lines
218     if(anAISIO->Width() > 1) {
219       for(int aModeIdx = 0; aModeIdx < myActiveSelectionModes.length(); ++aModeIdx) {
220         aContext->SetSelectionSensitivity(anAISIO,
221           myActiveSelectionModes.value(aModeIdx), anAISIO->Width() + 2);
222       }
223     }
224   } 
225   if (theUpdateViewer)
226     updateViewer();
227
228   return aDisplayed;
229 }
230
231 bool XGUI_Displayer::erase(ObjectPtr theObject, const bool theUpdateViewer)
232 {
233   bool aErased = false;
234   if (!isVisible(theObject))
235     return aErased;
236
237   Handle(AIS_InteractiveContext) aContext = AISContext();
238   if (aContext.IsNull())
239     return aErased;
240
241   AISObjectPtr anObject = myResult2AISObjectMap[theObject];
242   if (anObject) {
243     Handle(AIS_InteractiveObject) anAIS = anObject->impl<Handle(AIS_InteractiveObject)>();
244     if (!anAIS.IsNull()) {
245       emit beforeObjectErase(theObject, anObject);
246       aContext->Remove(anAIS, theUpdateViewer);
247       aErased = true;
248     }
249   }
250   myResult2AISObjectMap.remove(theObject);
251
252 #ifdef DEBUG_DISPLAY
253   std::ostringstream aPtrStr;
254   aPtrStr << theObject.get();
255   qDebug(QString("erase object: %1").arg(aPtrStr.str().c_str()).toStdString().c_str());
256   qDebug(getResult2AISObjectMapInfo().c_str());
257 #endif
258   return aErased;
259 }
260
261 bool XGUI_Displayer::redisplay(ObjectPtr theObject, bool theUpdateViewer)
262 {
263   bool aRedisplayed = false;
264   if (!isVisible(theObject))
265     return aRedisplayed;
266
267   AISObjectPtr aAISObj = getAISObject(theObject);
268   Handle(AIS_InteractiveObject) aAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
269
270   GeomPresentablePtr aPrs = std::dynamic_pointer_cast<GeomAPI_IPresentable>(theObject);
271   if (aPrs) {
272     AISObjectPtr aAIS_Obj = aPrs->getAISObject(aAISObj);
273     if (!aAIS_Obj) {
274       aRedisplayed = erase(theObject, theUpdateViewer);
275       return aRedisplayed;
276     }
277     if (aAIS_Obj != aAISObj) {
278       appendResultObject(theObject, aAIS_Obj);
279     }
280     aAISIO = aAIS_Obj->impl<Handle(AIS_InteractiveObject)>();
281   }
282
283   Handle(AIS_InteractiveContext) aContext = AISContext();
284   if (!aContext.IsNull() && !aAISIO.IsNull()) {
285     // Check that the visualized shape is the same and the redisplay is not necessary
286     // Redisplay of AIS object leads to this object selection compute and the selection 
287     // in the browser is lost
288     // this check is not necessary anymore because the selection store/restore is realized
289     // before and after the values modification.
290     // Moreother, this check avoids customize and redisplay presentation if the presentable
291     // parameter is changed.
292     bool isEqualShapes = false;
293     ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
294     if (aResult.get() != NULL) {
295       Handle(AIS_Shape) aShapePrs = Handle(AIS_Shape)::DownCast(aAISIO);
296       if (!aShapePrs.IsNull()) {
297         std::shared_ptr<GeomAPI_Shape> aShapePtr = ModelAPI_Tools::shape(aResult);
298         if (aShapePtr.get()) {
299           const TopoDS_Shape& aOldShape = aShapePrs->Shape();
300           if (!aOldShape.IsNull())
301             isEqualShapes = aOldShape.IsEqual(aShapePtr->impl<TopoDS_Shape>());
302         }
303       }
304     }
305     // Customization of presentation
306     bool isCustomized = customizeObject(theObject);
307     #ifdef DEBUG_FEATURE_REDISPLAY
308       qDebug(QString("Redisplay: %1, isEqualShapes=%2, isCustomized=%3").
309         arg(!isEqualShapes || isCustomized).arg(isEqualShapes).arg(isCustomized).toStdString().c_str());
310     #endif
311     if (!isEqualShapes || isCustomized) {
312       aContext->Redisplay(aAISIO, false);
313       aRedisplayed = true;
314       #ifdef DEBUG_FEATURE_REDISPLAY
315         qDebug("  Redisplay happens");
316       #endif
317       if (theUpdateViewer)
318         updateViewer();
319     }
320   }
321   return aRedisplayed;
322 }
323
324 void XGUI_Displayer::redisplayObjects()
325 {
326   // redisplay objects visualized in the viewer
327   static Events_ID EVENT_DISP = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
328   static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
329   QObjectPtrList aDisplayed = myWorkshop->displayer()->displayedObjects();
330   QObjectPtrList::const_iterator anIt = aDisplayed.begin(), aLast = aDisplayed.end();
331   for (; anIt != aLast; anIt++) {
332     aECreator->sendUpdated(*anIt, EVENT_DISP);
333   }
334   Events_Loop::loop()->flush(EVENT_DISP);
335 }
336
337 void XGUI_Displayer::deactivate(ObjectPtr theObject, const bool theUpdateViewer)
338 {
339 #ifdef DEBUG_DEACTIVATE
340   QString anInfoStr = ModuleBase_Tools::objectInfo(theObject);
341   qDebug(QString("deactivate: myActiveSelectionModes[%1]: %2, objects = ").
342     arg(myActiveSelectionModes.size()).arg(qIntListInfo(myActiveSelectionModes)).
343     arg(anInfoStr).
344     toStdString().c_str());
345 #endif
346   Handle(AIS_InteractiveContext) aContext = AISContext();
347   if (!aContext.IsNull() && isVisible(theObject)) {
348     AISObjectPtr anObj = myResult2AISObjectMap[theObject];
349     Handle(AIS_InteractiveObject) anAIS = anObj->impl<Handle(AIS_InteractiveObject)>();
350
351     deactivateAIS(anAIS);
352     // the selection from the previous activation modes should be cleared manually (#26172)
353     aContext->LocalContext()->ClearOutdatedSelection(anAIS, true);
354     if (theUpdateViewer)
355       updateViewer();
356   }
357 }
358
359 void XGUI_Displayer::deactivateObjects(const QObjectPtrList& theObjList,
360                                        const bool theUpdateViewer)
361 {
362   QObjectPtrList::const_iterator anIt = theObjList.begin(), aLast = theObjList.end();
363   for (; anIt != aLast; anIt++) {
364     deactivate(*anIt, false);
365   }
366   if (theUpdateViewer)
367     updateViewer();
368 }
369
370 void XGUI_Displayer::getModesOfActivation(ObjectPtr theObject, QIntList& theModes)
371 {
372   Handle(AIS_InteractiveContext) aContext = AISContext();
373   if (aContext.IsNull() || !isVisible(theObject))
374     return;
375
376   AISObjectPtr aAISObj = getAISObject(theObject);
377
378   if (aAISObj.get() != NULL) {
379     Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
380     TColStd_ListOfInteger aTColModes;
381     aContext->ActivatedModes(anAISIO, aTColModes);
382     TColStd_ListIteratorOfListOfInteger itr( aTColModes );
383     for (; itr.More(); itr.Next() ) {
384       theModes.append(itr.Value());
385     }
386   }
387 }
388
389 void XGUI_Displayer::activateObjects(const QIntList& theModes, const QObjectPtrList& theObjList,
390                                      const bool theUpdateViewer)
391 {
392   // Convert shape types to selection types
393   QIntList aModes;
394   foreach(int aType, theModes) {
395     if (aType >= TopAbs_SHAPE) 
396       aModes.append(aType);
397     else
398       aModes.append(AIS_Shape::SelectionMode((TopAbs_ShapeEnum)aType));
399   }
400
401 #ifdef DEBUG_ACTIVATE_OBJECTS
402   QStringList anInfo;
403   QObjectPtrList::const_iterator anIt = theObjList.begin(), aLast = theObjList.end();
404   for (; anIt != aLast; ++anIt) {
405     anInfo.append(ModuleBase_Tools::objectInfo((*anIt)));
406   }
407   QString anInfoStr = anInfo.join(", ");
408
409   qDebug(QString("activateObjects: aModes[%1] = %2, myActiveSelectionModes[%3] = %4, objects = %5").
410     arg(aModes.size()).arg(qIntListInfo(aModes)).
411     arg(myActiveSelectionModes.size()).arg(qIntListInfo(myActiveSelectionModes)).
412     arg(anInfoStr).
413     toStdString().c_str());
414 #endif
415   // In order to avoid doblications of selection modes
416   QIntList aNewModes;
417   foreach (int aMode, aModes) {
418     if (!aNewModes.contains(aMode))
419       aNewModes.append(aMode);
420   }
421   myActiveSelectionModes = aNewModes;
422   Handle(AIS_InteractiveContext) aContext = AISContext();
423   // Open local context if there is no one
424   if (aContext.IsNull() || !aContext->HasOpenedContext()) 
425     return;
426
427   //aContext->UseDisplayedObjects();
428   //myUseExternalObjects = true;
429
430   Handle(AIS_InteractiveObject) anAISIO;
431   AIS_ListOfInteractive aPrsList;
432   if (theObjList.isEmpty())
433     return;
434   else {
435     foreach(ObjectPtr aObj, theObjList) {
436       if (myResult2AISObjectMap.contains(aObj))
437         aPrsList.Append(myResult2AISObjectMap[aObj]->impl<Handle(AIS_InteractiveObject)>());
438     }
439   }
440
441   AIS_ListIteratorOfListOfInteractive aLIt(aPrsList);
442   for(aLIt.Initialize(aPrsList); aLIt.More(); aLIt.Next()){
443     anAISIO = aLIt.Value();
444     activate(anAISIO, myActiveSelectionModes, false);
445   }
446   if (theUpdateViewer)
447     updateViewer();
448 }
449
450 bool XGUI_Displayer::isActive(ObjectPtr theObject) const
451 {
452   Handle(AIS_InteractiveContext) aContext = AISContext();
453   if (aContext.IsNull() || !isVisible(theObject))
454     return false;
455     
456   AISObjectPtr anObj = myResult2AISObjectMap[theObject];
457   Handle(AIS_InteractiveObject) anAIS = anObj->impl<Handle(AIS_InteractiveObject)>();
458
459   TColStd_ListOfInteger aModes;
460   aContext->ActivatedModes(anAIS, aModes);
461   return aModes.Extent() > 0;
462 }
463 void XGUI_Displayer::setSelected(const  QList<ModuleBase_ViewerPrs>& theValues, bool theUpdateViewer)
464 {
465   Handle(AIS_InteractiveContext) aContext = AISContext();
466   if (aContext.IsNull())
467     return;
468   if (aContext->HasOpenedContext()) {
469     aContext->UnhilightSelected();
470     aContext->ClearSelected();
471     foreach (ModuleBase_ViewerPrs aPrs, theValues) {
472       const TopoDS_Shape& aShape = aPrs.shape();
473       if (!aShape.IsNull()) {
474         aContext->AddOrRemoveSelected(aShape, false);
475       } else {
476         ObjectPtr anObject = aPrs.object();
477         ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
478         if (aResult.get() && isVisible(aResult)) {
479           AISObjectPtr anObj = myResult2AISObjectMap[aResult];
480           Handle(AIS_InteractiveObject) anAIS = anObj->impl<Handle(AIS_InteractiveObject)>();
481           if (!anAIS.IsNull()) {
482             // The methods are replaced in order to provide multi-selection, e.g. restore selection
483             // by activating multi selector widget. It also gives an advantage that the multi
484             // selection in OB gives multi-selection in the viewer
485             //aContext->SetSelected(anAIS, false);
486             // The selection in the context was cleared, so the method sets the objects are selected
487             aContext->AddOrRemoveSelected(anAIS, false);
488           }
489         }
490       }
491     }
492   } else {
493     aContext->UnhilightCurrents();
494     aContext->ClearCurrents();
495     foreach (ModuleBase_ViewerPrs aPrs, theValues) {
496       ObjectPtr anObject = aPrs.object();
497       ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(anObject);
498       if (aResult.get() && isVisible(aResult)) {
499         AISObjectPtr anObj = myResult2AISObjectMap[aResult];
500         Handle(AIS_InteractiveObject) anAIS = anObj->impl<Handle(AIS_InteractiveObject)>();
501         if (!anAIS.IsNull())
502           aContext->SetCurrentObject(anAIS, false);
503       }
504     }
505   }
506   if (theUpdateViewer)
507     updateViewer();
508 }
509
510 void XGUI_Displayer::clearSelected()
511 {
512   Handle(AIS_InteractiveContext) aContext = AISContext();
513   if (!aContext.IsNull()) {
514     aContext->UnhilightCurrents(false);
515     aContext->ClearSelected();
516   }
517 }
518
519 bool XGUI_Displayer::eraseAll(const bool theUpdateViewer)
520 {
521   bool aErased = false;
522   Handle(AIS_InteractiveContext) aContext = AISContext();
523   if (!aContext.IsNull()) {
524     foreach (ObjectPtr aObj, myResult2AISObjectMap.keys()) {
525       AISObjectPtr aAISObj = myResult2AISObjectMap[aObj];
526       // erase an object
527       Handle(AIS_InteractiveObject) anIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
528       if (!anIO.IsNull()) {
529         emit beforeObjectErase(aObj, aAISObj);
530         aContext->Remove(anIO, false);
531         aErased = true;
532       }
533     }
534     if (theUpdateViewer)
535       updateViewer();
536   }
537   myResult2AISObjectMap.clear();
538 #ifdef DEBUG_DISPLAY
539   qDebug("eraseAll");
540   qDebug(getResult2AISObjectMapInfo().c_str());
541 #endif
542   return aErased;
543 }
544
545 void XGUI_Displayer::deactivateTrihedron() const
546 {
547   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
548   if (!aContext.IsNull()) {
549     AIS_ListOfInteractive aList;
550     aContext->DisplayedObjects(aList, true);
551     AIS_ListIteratorOfListOfInteractive aIt;
552     for (aIt.Initialize(aList); aIt.More(); aIt.Next()) {
553       Handle(AIS_Trihedron) aTrihedron = Handle(AIS_Trihedron)::DownCast(aIt.Value());
554       if (!aTrihedron.IsNull()) {
555         aContext->Deactivate(aTrihedron);
556       }
557     }
558   }
559 }
560
561 void XGUI_Displayer::openLocalContext()
562 {
563   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
564   // Open local context if there is no one
565   if (!aContext.IsNull() && !aContext->HasOpenedContext()) {
566     // Preserve selected objects
567     //AIS_ListOfInteractive aAisList;
568     //for (aContext->InitCurrent(); aContext->MoreCurrent(); aContext->NextCurrent())
569     //  aAisList.Append(aContext->Current());
570
571     // get the filters from the global context and append them to the local context
572     // a list of filters in the global context is not cleared and should be cleared here
573     SelectMgr_ListOfFilter aFilters;
574     aFilters.Assign(aContext->Filters());
575     // it is important to remove the filters in the global context, because there is a code
576     // in the closeLocalContex, which restore the global context filters
577     aContext->RemoveFilters();
578
579     //aContext->ClearCurrents();
580     aContext->OpenLocalContext();
581     deactivateTrihedron();
582     //aContext->NotUseDisplayedObjects();
583
584     //myUseExternalObjects = false;
585
586     SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
587     for (;aIt.More(); aIt.Next()) {
588       aContext->AddFilter(aIt.Value());
589     }
590     // Restore selection
591     //AIS_ListIteratorOfListOfInteractive aIt2(aAisList);
592     //for(; aIt2.More(); aIt2.Next()) {
593     //  aContext->SetSelected(aIt2.Value(), false);
594     //}
595   }
596 }
597
598 void XGUI_Displayer::closeLocalContexts(const bool theUpdateViewer)
599 {
600   Handle(AIS_InteractiveContext) aContext = AISContext();
601   if (!aContext.IsNull() && aContext->HasOpenedContext()) {
602     // Preserve selected objects
603     //AIS_ListOfInteractive aAisList;
604     //for (aContext->InitSelected(); aContext->MoreSelected(); aContext->NextSelected())
605     //  aAisList.Append(aContext->SelectedInteractive());
606
607     // get the filters from the local context and append them to the global context
608     // a list of filters in the local context is cleared
609     SelectMgr_ListOfFilter aFilters;
610     aFilters.Assign(aContext->Filters());
611
612     //aContext->ClearSelected();
613     aContext->CloseAllContexts(false);
614
615     // From the moment when the AIS_DS_Displayed flag is used in the Display of AIS object,
616     // this code is obsolete. It is temporaty commented and should be removed after
617     // the test campaign.
618     // Redisplay all object if they were displayed in localContext
619     /*Handle(AIS_InteractiveObject) aAISIO;
620     foreach (AISObjectPtr aAIS, myResult2AISObjectMap) {
621       aAISIO = aAIS->impl<Handle(AIS_InteractiveObject)>();
622       if (aContext->DisplayStatus(aAISIO) != AIS_DS_Displayed) {
623         aContext->Display(aAISIO, false);
624         aContext->SetDisplayMode(aAISIO, Shading, false);
625       }
626     }*/
627
628     // Append the filters from the local selection in the global selection context
629     SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
630     for (;aIt.More(); aIt.Next()) {
631       Handle(SelectMgr_Filter) aFilter = aIt.Value();
632       aContext->AddFilter(aFilter);
633     }
634
635     if (theUpdateViewer)
636       updateViewer();
637     //myUseExternalObjects = false;
638
639     // Restore selection
640     //AIS_ListIteratorOfListOfInteractive aIt2(aAisList);
641     //for(; aIt2.More(); aIt2.Next()) {
642     //  if (aContext->IsDisplayed(aIt2.Value()))
643     //    aContext->SetCurrentObject(aIt2.Value(), false);
644     //}
645   }
646 }
647
648 AISObjectPtr XGUI_Displayer::getAISObject(ObjectPtr theObject) const
649 {
650   AISObjectPtr anIO;
651   if (myResult2AISObjectMap.contains(theObject))
652     anIO = myResult2AISObjectMap[theObject];
653   return anIO;
654 }
655
656 ObjectPtr XGUI_Displayer::getObject(const AISObjectPtr& theIO) const
657 {
658   Handle(AIS_InteractiveObject) aRefAIS = theIO->impl<Handle(AIS_InteractiveObject)>();
659   return getObject(aRefAIS);
660 }
661
662 ObjectPtr XGUI_Displayer::getObject(const Handle(AIS_InteractiveObject)& theIO) const
663 {
664   ObjectPtr anObject;
665   foreach (ObjectPtr anObj, myResult2AISObjectMap.keys()) {
666     AISObjectPtr aAIS = myResult2AISObjectMap[anObj];
667     Handle(AIS_InteractiveObject) anAIS = aAIS->impl<Handle(AIS_InteractiveObject)>();
668     if (anAIS == theIO)
669       anObject = anObj;
670     if (anObject.get())
671       break;
672   }
673   if (!anObject.get()) {
674     std::shared_ptr<GeomAPI_AISObject> anAISObj = AISObjectPtr(new GeomAPI_AISObject());
675     if (!theIO.IsNull()) {
676       anAISObj->setImpl(new Handle(AIS_InteractiveObject)(theIO));
677     }
678     anObject = myWorkshop->module()->findPresentedObject(anAISObj);
679   }
680   return anObject;
681 }
682
683 bool XGUI_Displayer::enableUpdateViewer(const bool isEnabled)
684 {
685   bool aWasEnabled = myEnableUpdateViewer;
686
687   myEnableUpdateViewer = isEnabled;
688
689   return aWasEnabled;
690 }
691
692 void XGUI_Displayer::updateViewer() const
693 {
694   Handle(AIS_InteractiveContext) aContext = AISContext();
695   if (!aContext.IsNull() && myEnableUpdateViewer) {
696     myWorkshop->viewer()->Zfitall();
697     aContext->UpdateCurrentViewer();
698   }
699 }
700
701 void XGUI_Displayer::activateAIS(const Handle(AIS_InteractiveObject)& theIO,
702                                  const int theMode, const bool theUpdateViewer) const
703 {
704   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
705   if (!aContext.IsNull()) {
706     aContext->Activate(theIO, theMode, theUpdateViewer);
707
708 #ifdef DEBUG_ACTIVATE_AIS
709     ObjectPtr anObject = getObject(theIO);
710     anInfo.append(ModuleBase_Tools::objectInfo((*anIt)));
711     qDebug(QString("activateAIS: theMode = %1, object = %2").arg(theMode).arg(anInfo).toStdString().c_str());
712 #endif
713   }
714 }
715
716 void XGUI_Displayer::deactivateAIS(const Handle(AIS_InteractiveObject)& theIO, const int theMode) const
717 {
718   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
719   if (!aContext.IsNull()) {
720     if (theMode == -1)
721       aContext->Deactivate(theIO);
722     else
723       aContext->Deactivate(theIO, theMode);
724
725 #ifdef DEBUG_DEACTIVATE_AIS
726     ObjectPtr anObject = getObject(theIO);
727     anInfo.append(ModuleBase_Tools::objectInfo((*anIt)));
728     qDebug(QString("deactivateAIS: theMode = %1, object = %2").arg(theMode).arg(anInfo).toStdString().c_str());
729 #endif
730   }
731 }
732
733 Handle(AIS_InteractiveContext) XGUI_Displayer::AISContext() const
734 {
735   Handle(AIS_InteractiveContext) aContext = myWorkshop->viewer()->AISContext();
736   if (!aContext.IsNull() && !aContext->HasOpenedContext()) {
737     aContext->OpenLocalContext();
738     deactivateTrihedron();
739     aContext->DefaultDrawer()->VIsoAspect()->SetNumber(0);
740     aContext->DefaultDrawer()->UIsoAspect()->SetNumber(0);
741   }
742   return aContext;
743 }
744
745 Handle(SelectMgr_AndFilter) XGUI_Displayer::GetFilter()
746 {
747   Handle(AIS_InteractiveContext) aContext = AISContext();
748   if (!aContext.IsNull() && myAndFilter.IsNull()) {
749     myAndFilter = new SelectMgr_AndFilter();
750     aContext->AddFilter(myAndFilter);
751   }
752   return myAndFilter;
753 }
754
755 bool XGUI_Displayer::displayAIS(AISObjectPtr theAIS, const bool toActivateInSelectionModes,
756                                 bool theUpdateViewer)
757 {
758   bool aDisplayed = false;
759   Handle(AIS_InteractiveContext) aContext = AISContext();
760   Handle(AIS_InteractiveObject) anAISIO = theAIS->impl<Handle(AIS_InteractiveObject)>();
761   if (!aContext.IsNull() && !anAISIO.IsNull()) {
762     aContext->Display(anAISIO, 0/*wireframe*/, 0, theUpdateViewer, true, AIS_DS_Displayed);
763     aDisplayed = true;
764     aContext->Deactivate(anAISIO);
765     aContext->Load(anAISIO);
766     if (toActivateInSelectionModes) {
767       if (aContext->HasOpenedContext()) {
768         if (myActiveSelectionModes.size() == 0)
769           activateAIS(anAISIO, 0, theUpdateViewer);
770         else {
771           foreach(int aMode, myActiveSelectionModes) {
772             activateAIS(anAISIO, aMode, theUpdateViewer);
773           }
774         }
775       }
776     }
777   }
778   return aDisplayed;
779 }
780
781 bool XGUI_Displayer::eraseAIS(AISObjectPtr theAIS, const bool theUpdateViewer)
782 {
783   bool aErased = false;
784   Handle(AIS_InteractiveContext) aContext = AISContext();
785   if (!aContext.IsNull()) {
786     Handle(AIS_InteractiveObject) anAISIO = theAIS->impl<Handle(AIS_InteractiveObject)>();
787     if (!anAISIO.IsNull() && aContext->IsDisplayed(anAISIO)) {
788       aContext->Remove(anAISIO, theUpdateViewer);
789       aErased = true;
790     }
791   }
792   return aErased;
793 }
794
795
796 void XGUI_Displayer::setDisplayMode(ObjectPtr theObject, DisplayMode theMode, bool theUpdateViewer)
797 {
798   if (theMode == NoMode)
799     return;
800
801   Handle(AIS_InteractiveContext) aContext = AISContext();
802   if (aContext.IsNull())
803     return;
804
805   AISObjectPtr aAISObj = getAISObject(theObject);
806   if (!aAISObj)
807     return;
808
809   Handle(AIS_InteractiveObject) aAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
810   aContext->SetDisplayMode(aAISIO, theMode, false);
811   // Redisplay in order to update new mode because it could be not computed before
812   if (theUpdateViewer)
813     updateViewer();
814 }
815
816 XGUI_Displayer::DisplayMode XGUI_Displayer::displayMode(ObjectPtr theObject) const
817 {
818   Handle(AIS_InteractiveContext) aContext = AISContext();
819   if (aContext.IsNull())
820     return NoMode;
821
822   AISObjectPtr aAISObj = getAISObject(theObject);
823   if (!aAISObj)
824     return NoMode;
825
826   Handle(AIS_InteractiveObject) aAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
827   return (XGUI_Displayer::DisplayMode) aAISIO->DisplayMode();
828 }
829
830 void XGUI_Displayer::deactivateSelectionFilters()
831 {
832   Handle(AIS_InteractiveContext) aContext = AISContext();
833   if (!myAndFilter.IsNull()) {
834     bool aFound = false;
835     if (!aContext.IsNull()) {
836       const SelectMgr_ListOfFilter& aFilters = aContext->Filters();
837       SelectMgr_ListIteratorOfListOfFilter anIt(aFilters);
838       for (; anIt.More() && !aFound; anIt.Next()) {
839         Handle(SelectMgr_Filter) aFilter = anIt.Value();
840         aFound = aFilter == myAndFilter;
841       }
842       if (aFound)
843         aContext->RemoveFilter(myAndFilter);
844     }
845     myAndFilter.Nullify();
846   }
847 }
848
849 void XGUI_Displayer::addSelectionFilter(const Handle(SelectMgr_Filter)& theFilter)
850 {
851   Handle(AIS_InteractiveContext) aContext = AISContext();
852   if (aContext.IsNull() || hasSelectionFilter(theFilter))
853     return;
854
855   Handle(SelectMgr_CompositionFilter) aCompositeFilter = GetFilter();
856   if (!aCompositeFilter.IsNull()) {
857     aCompositeFilter->Add(theFilter);
858 #ifdef DEBUG_SELECTION_FILTERS
859     int aCount = aCompositeFilter->StoredFilters().Extent();
860     qDebug(QString("addSelectionFilter: filters.count() = %1").arg(aCount).toStdString().c_str());
861 #endif
862   }
863 }
864
865 void XGUI_Displayer::removeSelectionFilter(const Handle(SelectMgr_Filter)& theFilter)
866 {
867   Handle(AIS_InteractiveContext) aContext = AISContext();
868   if (aContext.IsNull())
869     return;
870
871   Handle(SelectMgr_AndFilter) aCompositeFilter = GetFilter();
872   if (!aCompositeFilter.IsNull() && aCompositeFilter->IsIn(theFilter)) {
873     aCompositeFilter->Remove(theFilter);
874 #ifdef DEBUG_SELECTION_FILTERS
875     int aCount = aCompositeFilter->StoredFilters().Extent();
876     qDebug(QString("removeSelectionFilter: filters.count() = %1").arg(aCount).toStdString().c_str());
877 #endif
878   }
879 }
880
881 bool XGUI_Displayer::hasSelectionFilter(const Handle(SelectMgr_Filter)& theFilter)
882 {
883   bool aFilterFound = false;
884
885   Handle(AIS_InteractiveContext) aContext = AISContext();
886   if (aContext.IsNull())
887     return aFilterFound;
888   const SelectMgr_ListOfFilter& aFilters = aContext->Filters();
889   SelectMgr_ListIteratorOfListOfFilter aIt(aFilters);
890   for (; aIt.More() && !aFilterFound; aIt.Next()) {
891     if (theFilter.Access() == aIt.Value().Access())
892       aFilterFound = true;
893   }
894   Handle(SelectMgr_CompositionFilter) aCompositeFilter = GetFilter();
895   if (!aCompositeFilter.IsNull()) {
896     const SelectMgr_ListOfFilter& aStoredFilters = aCompositeFilter->StoredFilters();
897     for (aIt.Initialize(aStoredFilters); aIt.More() && !aFilterFound; aIt.Next()) {
898       if (theFilter.Access() == aIt.Value().Access())
899         aFilterFound = true;
900     }
901   }
902   return aFilterFound;
903 }
904
905 void XGUI_Displayer::removeFilters()
906 {
907   Handle(AIS_InteractiveContext) aContext = AISContext();
908   if (aContext.IsNull())
909     return;
910
911   Handle(SelectMgr_CompositionFilter) aCompositeFilter = GetFilter();
912   if (!aCompositeFilter.IsNull())
913     aCompositeFilter->Clear();
914 }
915
916 void XGUI_Displayer::showOnly(const QObjectPtrList& theList)
917 {
918   QObjectPtrList aDispList = myResult2AISObjectMap.keys();
919   foreach(ObjectPtr aObj, aDispList) {
920     if (!theList.contains(aObj))
921       erase(aObj, false);
922   }
923   foreach(ObjectPtr aObj, theList) {
924     if (!isVisible(aObj))
925       display(aObj, false);
926   }
927   updateViewer();
928 }
929
930 bool XGUI_Displayer::canBeShaded(ObjectPtr theObject) const
931
932   if (!isVisible(theObject))
933     return false;
934
935   AISObjectPtr aAISObj = getAISObject(theObject);
936   if (aAISObj.get() == NULL)
937     return false;
938
939   Handle(AIS_InteractiveObject) anAIS = aAISObj->impl<Handle(AIS_InteractiveObject)>();
940   return ::canBeShaded(anAIS);
941 }
942
943 void XGUI_Displayer::activate(const Handle(AIS_InteractiveObject)& theIO,
944                               const QIntList& theModes,
945                               const bool theUpdateViewer) const
946 {
947   Handle(AIS_InteractiveContext) aContext = AISContext();
948   if (aContext.IsNull() || theIO.IsNull())
949     return;
950
951   // deactivate object in all modes, which are not in the list of activation
952   // It seems that after the IO deactivation the selected state of the IO's owners
953   // is modified in OCC(version: 6.8.0) and the selection of the object later is lost.
954   // By this reason, the number of the IO deactivate is decreased and the object is deactivated
955   // only if there is a difference in the current modes and the parameters modes.
956   // If the selection problem happens again, it is possible to write a test scenario and create
957   // a bug. The bug steps are the following:
958   // Create two IO, activate them in 5 modes, select the first IO, deactivate 3 modes for both,
959   // with clicked SHIFT select the second object. The result is the selection of the first IO is lost.
960   TColStd_ListOfInteger aTColModes;
961   aContext->ActivatedModes(theIO, aTColModes);
962   TColStd_ListIteratorOfListOfInteger itr( aTColModes );
963   QIntList aModesActivatedForIO;
964   bool isDeactivated = false;
965   for (; itr.More(); itr.Next() ) {
966     Standard_Integer aMode = itr.Value();
967     if (!theModes.contains(aMode)) {
968       deactivateAIS(theIO, aMode);
969       isDeactivated = true;
970     }
971     else {
972       aModesActivatedForIO.append(aMode);
973     }
974   }
975   if (isDeactivated) {
976     // the selection from the previous activation modes should be cleared manually (#26172)
977     aContext->LocalContext()->ClearOutdatedSelection(theIO, true);
978     if (theUpdateViewer)
979       updateViewer();
980   }
981
982   // loading the interactive object allowing the decomposition
983   if (aTColModes.IsEmpty()) {
984     aContext->Load(theIO, -1, true);
985   }
986
987   // trihedron AIS check should be after the AIS loading.
988   // If it is not loaded, it is steel selectable in the viewer.
989   Handle(AIS_Trihedron) aTrihedron = Handle(AIS_Trihedron)::DownCast(theIO);
990   if (aTrihedron.IsNull()) {
991       //aContext->Load(anAISIO, -1, true);
992       // In order to clear active modes list
993     if (theModes.size() == 0) {
994       //aContext->Load(anAISIO, 0, true);
995       activateAIS(theIO, 0, theUpdateViewer);
996     } else {
997       foreach(int aMode, theModes) {
998         //aContext->Load(anAISIO, aMode, true);
999         if (!aModesActivatedForIO.contains(aMode)) {
1000           activateAIS(theIO, aMode, theUpdateViewer);
1001         }
1002       }
1003     }
1004   }
1005 }
1006
1007 bool XGUI_Displayer::customizeObject(ObjectPtr theObject)
1008 {
1009   AISObjectPtr anAISObj = getAISObject(theObject);
1010   // correct the result's color it it has the attribute
1011   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
1012
1013   // Customization of presentation
1014   GeomCustomPrsPtr aCustomPrs;
1015   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1016   if (aFeature.get() != NULL) {
1017     GeomCustomPrsPtr aCustPrs = std::dynamic_pointer_cast<GeomAPI_ICustomPrs>(aFeature);
1018     if (aCustPrs.get() != NULL)
1019       aCustomPrs = aCustPrs;
1020   }
1021   if (aCustomPrs.get() == NULL) {
1022     GeomPresentablePtr aPrs = std::dynamic_pointer_cast<GeomAPI_IPresentable>(theObject);
1023     // we ignore presentable not customized objects
1024     if (aPrs.get() == NULL)
1025       aCustomPrs = myCustomPrs;
1026   }
1027   bool isCustomized = aCustomPrs.get() &&
1028                       aCustomPrs->customisePresentation(aResult, anAISObj, myCustomPrs);
1029   return isCustomized;
1030 }
1031
1032
1033 QColor XGUI_Displayer::setObjectColor(ObjectPtr theObject, const QColor& theColor, bool theUpdateViewer)
1034 {
1035   if (!isVisible(theObject))
1036     return Qt::black;
1037
1038   AISObjectPtr anAISObj = getAISObject(theObject);
1039   int aR, aG, aB;
1040   anAISObj->getColor(aR, aG, aB);
1041   anAISObj->setColor(theColor.red(), theColor.green(), theColor.blue());
1042   if (theUpdateViewer)
1043     updateViewer();
1044   return QColor(aR, aG, aB);
1045 }
1046
1047 void XGUI_Displayer::appendResultObject(ObjectPtr theObject, AISObjectPtr theAIS)
1048 {
1049   myResult2AISObjectMap[theObject] = theAIS;
1050
1051 #ifdef DEBUG_DISPLAY
1052   std::ostringstream aPtrStr;
1053   aPtrStr << theObject.get();
1054   qDebug(QString("display object: %1").arg(aPtrStr.str().c_str()).toStdString().c_str());
1055   qDebug(getResult2AISObjectMapInfo().c_str());
1056 #endif
1057 }
1058
1059 std::string XGUI_Displayer::getResult2AISObjectMapInfo() const
1060 {
1061   QStringList aContent;
1062   foreach (ObjectPtr aObj, myResult2AISObjectMap.keys()) {
1063     AISObjectPtr aAISObj = myResult2AISObjectMap[aObj];
1064     std::ostringstream aPtrStr;
1065     aPtrStr << "aObj = " << aObj.get() << ":";
1066     aPtrStr << "anAIS = " << aAISObj.get() << ":";
1067     aPtrStr << "[" << ModuleBase_Tools::objectInfo(aObj).toStdString().c_str() << "]";
1068     
1069     aContent.append(aPtrStr.str().c_str());
1070   }
1071   return QString("myResult2AISObjectMap: size = %1\n%2\n").arg(myResult2AISObjectMap.size()).
1072                                             arg(aContent.join("\n")).toStdString().c_str();
1073 }