]> git.mxchange.org Git - flightgear.git/blob - src/Viewer/FGEventHandler.cxx
commradio: improvements for atis speech
[flightgear.git] / src / Viewer / FGEventHandler.cxx
1 #ifdef HAVE_CONFIG_H
2 #  include <config.h>
3 #endif
4 #include <osg/Camera>
5 #include <osg/GraphicsContext>
6 #include <osg/Math>
7 #include <osg/Viewport>
8 #include <osgViewer/Viewer>
9
10 #include <plib/pu.h>
11 #include <Main/fg_props.hxx>
12 #include "CameraGroup.hxx"
13 #include "FGEventHandler.hxx"
14 #include "WindowSystemAdapter.hxx"
15 #include "renderer.hxx"
16
17 #if !defined(X_DISPLAY_MISSING)
18 #define X_DOUBLE_SCROLL_BUG 1
19 #endif
20
21 #ifdef SG_MAC
22 // hack - during interactive resize on Mac, OSG queues and then flushes
23 // a large number of resize events, without doing any drawing.
24 extern void puCleanUpJunk ( void ) ;
25 #endif
26
27 namespace flightgear
28 {
29 const int displayStatsKey = 1;
30 const int printStatsKey = 2;
31
32
33 // The manipulator is responsible for updating a Viewer's camera. Its
34 // event handling method is also a convenient place to run the FG idle
35 // and draw handlers.
36
37 FGEventHandler::FGEventHandler() :
38     idleHandler(0),
39     keyHandler(0),
40     mouseClickHandler(0),
41     mouseMotionHandler(0),
42     statsHandler(new FGStatsHandler),
43     statsEvent(new osgGA::GUIEventAdapter),
44     statsType(osgViewer::StatsHandler::NO_STATS),
45     currentModifiers(0),
46     resizable(true),
47     mouseWarped(false),
48     scrollButtonPressed(false),
49     changeStatsCameraRenderOrder(false)
50 {
51     using namespace osgGA;
52     statsHandler->setKeyEventTogglesOnScreenStats(displayStatsKey);
53     statsHandler->setKeyEventPrintsOutStats(printStatsKey);
54     statsEvent->setEventType(GUIEventAdapter::KEYDOWN);
55
56     // OSG reports NumPad keycodes independent of the NumLock modifier.
57     // Both KP-4 and KP-Left are reported as KEY_KP_Left (0xff96), so we
58     // have to generate the locked keys ourselves.
59     numlockKeyMap[GUIEventAdapter::KEY_KP_Insert]  = '0';
60     numlockKeyMap[GUIEventAdapter::KEY_KP_End] = '1';
61     numlockKeyMap[GUIEventAdapter::KEY_KP_Down] = '2';
62     numlockKeyMap[GUIEventAdapter::KEY_KP_Page_Down] = '3';
63     numlockKeyMap[GUIEventAdapter::KEY_KP_Left] = '4';
64     numlockKeyMap[GUIEventAdapter::KEY_KP_Begin] = '5';
65     numlockKeyMap[GUIEventAdapter::KEY_KP_Right] = '6';
66     numlockKeyMap[GUIEventAdapter::KEY_KP_Home] = '7';
67     numlockKeyMap[GUIEventAdapter::KEY_KP_Up] = '8';
68     numlockKeyMap[GUIEventAdapter::KEY_KP_Page_Up] = '9';
69     numlockKeyMap[GUIEventAdapter::KEY_KP_Delete] = '.';
70
71     // The comment above is incorrect on Mac osgViewer, at least. So we
72     // need to map the 'num-locked' key codes to real values.
73     numlockKeyMap[GUIEventAdapter::KEY_KP_0]  = '0';
74     numlockKeyMap[GUIEventAdapter::KEY_KP_1] = '1';
75     numlockKeyMap[GUIEventAdapter::KEY_KP_2] = '2';
76     numlockKeyMap[GUIEventAdapter::KEY_KP_3] = '3';
77     numlockKeyMap[GUIEventAdapter::KEY_KP_4] = '4';
78     numlockKeyMap[GUIEventAdapter::KEY_KP_5] = '5';
79     numlockKeyMap[GUIEventAdapter::KEY_KP_6] = '6';
80     numlockKeyMap[GUIEventAdapter::KEY_KP_7] = '7';
81     numlockKeyMap[GUIEventAdapter::KEY_KP_8] = '8';
82     numlockKeyMap[GUIEventAdapter::KEY_KP_9] = '9';
83     numlockKeyMap[GUIEventAdapter::KEY_KP_Decimal] = '.';
84
85     
86     // mapping when NumLock is off
87     noNumlockKeyMap[GUIEventAdapter::KEY_KP_Insert]     = PU_KEY_INSERT;
88     noNumlockKeyMap[GUIEventAdapter::KEY_KP_End]        = PU_KEY_END;
89     noNumlockKeyMap[GUIEventAdapter::KEY_KP_Down]       = PU_KEY_DOWN;
90     noNumlockKeyMap[GUIEventAdapter::KEY_KP_Page_Down]  = PU_KEY_PAGE_DOWN;
91     noNumlockKeyMap[GUIEventAdapter::KEY_KP_Left]       = PU_KEY_LEFT;
92     noNumlockKeyMap[GUIEventAdapter::KEY_KP_Begin]      = '5';
93     noNumlockKeyMap[GUIEventAdapter::KEY_KP_Right]      = PU_KEY_RIGHT;
94     noNumlockKeyMap[GUIEventAdapter::KEY_KP_Home]       = PU_KEY_HOME;
95     noNumlockKeyMap[GUIEventAdapter::KEY_KP_Up]         = PU_KEY_UP;
96     noNumlockKeyMap[GUIEventAdapter::KEY_KP_Page_Up]    = PU_KEY_PAGE_UP;
97     noNumlockKeyMap[GUIEventAdapter::KEY_KP_Delete]     = 127;
98
99     for (int i = 0; i < 128; i++)
100         release_keys[i] = i;
101
102     _display = fgGetNode("/sim/rendering/on-screen-statistics", true);
103     _print = fgGetNode("/sim/rendering/print-statistics", true);
104 }
105
106 void FGEventHandler::reset()
107 {
108     _display = fgGetNode("/sim/rendering/on-screen-statistics", true);
109     _print = fgGetNode("/sim/rendering/print-statistics", true);
110     statsHandler->reset();
111 }
112     
113 namespace
114 {
115 // Translate OSG modifier mask to FG modifier mask.
116 int osgToFGModifiers(int modifiers)
117 {
118     int result = 0;
119     if (modifiers & osgGA::GUIEventAdapter::MODKEY_SHIFT)
120         result |= KEYMOD_SHIFT;
121
122     if (modifiers & osgGA::GUIEventAdapter::MODKEY_CTRL)
123         result |= KEYMOD_CTRL;
124
125     if (modifiers & osgGA::GUIEventAdapter::MODKEY_ALT)
126         result |= KEYMOD_ALT;
127
128     if (modifiers & osgGA::GUIEventAdapter::MODKEY_META)
129         result |= KEYMOD_META;
130
131     if (modifiers & osgGA::GUIEventAdapter::MODKEY_SUPER)
132         result |= KEYMOD_SUPER;
133
134     if (modifiers & osgGA::GUIEventAdapter::MODKEY_HYPER)
135         result |= KEYMOD_HYPER;
136     return result;
137 }
138 }
139
140 #if 0
141 void FGEventHandler::init(const osgGA::GUIEventAdapter& ea,
142                           osgGA::GUIActionAdapter& us)
143 {
144     currentModifiers = osgToFGModifiers(ea.getModKeyMask());
145     (void)handle(ea, us);
146 }
147 #endif
148
149 // Calculate event coordinates in the viewport of the GUI camera, if
150 // possible. Otherwise return false and (-1, -1).
151 namespace
152 {
153 bool
154 eventToViewport(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us,
155                 int& x, int& y)
156 {
157     x = -1;
158     y = -1;
159
160     const osg::GraphicsContext* eventGC = ea.getGraphicsContext();
161     if( !eventGC )
162       return false; // TODO how can this happen?
163     const osg::GraphicsContext::Traits* traits = eventGC->getTraits();
164     osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
165     if (!guiCamera)
166         return false;
167     osg::Viewport* vport = guiCamera->getViewport();
168     if (!vport)
169         return false;
170     
171     // Scale x, y to the dimensions of the window
172     double wx = (((ea.getX() - ea.getXmin()) / (ea.getXmax() - ea.getXmin()))
173                  * (float)traits->width);
174     double wy = (((ea.getY() - ea.getYmin()) / (ea.getYmax() - ea.getYmin()))
175                  * (float)traits->height);
176     if (vport->x() <= wx && wx <= vport->x() + vport->width()
177         && vport->y() <= wy && wy <= vport->y() + vport->height()) {
178         // Finally, into viewport coordinates. Change y to "increasing
179         // downwards".
180         x = wx - vport->x();
181         y = vport->height() - (wy - vport->y());
182         return true;
183     } else {
184         return false;
185     }
186 }
187 }
188
189 bool FGEventHandler::handle(const osgGA::GUIEventAdapter& ea,
190                             osgGA::GUIActionAdapter& us)
191 {
192     // Event handlers seem to be called even if the according event has already
193     // been handled. Already handled events shouldn't be handled multiple times
194     // so we need to exit here manually.
195     if(    ea.getHandled()
196            // Let mouse move events pass to correctly handle mouse cursor hide
197            // timeout while moving just on the canvas gui.
198            // TODO We should clean up the whole mouse input and make hide
199            //      timeout independent of the event handler which consumed the
200            //      event.
201         && ea.getEventType() != osgGA::GUIEventAdapter::MOVE
202         && ea.getEventType() != osgGA::GUIEventAdapter::DRAG )
203       return false;
204
205     int x = 0;
206     int y = 0;
207
208     switch (ea.getEventType()) {
209     case osgGA::GUIEventAdapter::FRAME:
210         mouseWarped = false;
211         handleStats(us);
212         return true;
213     case osgGA::GUIEventAdapter::KEYDOWN:
214     case osgGA::GUIEventAdapter::KEYUP:
215     {
216         int key, modmask;
217         handleKey(ea, key, modmask);
218         eventToViewport(ea, us, x, y);
219         if (keyHandler)
220             (*keyHandler)(key, modmask, x, y);
221         return true;
222     }
223     case osgGA::GUIEventAdapter::PUSH:
224     case osgGA::GUIEventAdapter::RELEASE:
225     {
226         bool mainWindow = eventToViewport(ea, us, x, y);
227         int button = 0;
228         switch (ea.getButton()) {
229         case osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON:
230             button = 0;
231             break;
232         case osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON:
233             button = 1;
234             break;
235         case osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON:
236             button = 2;
237             break;
238         }
239         if (mouseClickHandler)
240             (*mouseClickHandler)(button,
241                                  (ea.getEventType()
242                                   == osgGA::GUIEventAdapter::RELEASE), x, y, mainWindow, &ea);
243         return true;
244     }
245     case osgGA::GUIEventAdapter::SCROLL:
246     {
247         bool mainWindow = eventToViewport(ea, us, x, y);
248 #ifdef X_DOUBLE_SCROLL_BUG
249         scrollButtonPressed = !scrollButtonPressed;
250         if (!scrollButtonPressed) // Drop the button release event
251             return true;
252 #endif
253         int button;
254         if (ea.getScrollingMotion() == osgGA::GUIEventAdapter::SCROLL_2D) {
255             if (ea.getScrollingDeltaY() > 0)
256                 button = 3;
257             else if (ea.getScrollingDeltaY() < 0)
258                 button = 4;
259             else
260                 button = -1;
261             
262 #if defined(SG_MAC)
263             // bug https://code.google.com/p/flightgear-bugs/issues/detail?id=1286
264             // Mac (Cocoa) interprets shuft+wheel as horizontal scroll
265             if (ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_SHIFT) {
266                 if (ea.getScrollingDeltaX() > 0)
267                     button = 3;
268                 else if (ea.getScrollingDeltaX() < 0)
269                     button = 4;
270             }
271 #endif
272             
273         } else if (ea.getScrollingMotion() == osgGA::GUIEventAdapter::SCROLL_UP)
274             button = 3;
275         else
276             button = 4;
277         if (mouseClickHandler && button != -1) {
278             (*mouseClickHandler)(button, 0, x, y, mainWindow, &ea);
279             (*mouseClickHandler)(button, 1, x, y, mainWindow, &ea);
280         }
281         return true;
282     }
283     case osgGA::GUIEventAdapter::MOVE:
284     case osgGA::GUIEventAdapter::DRAG:
285         // If we warped the mouse, then disregard all pointer motion
286         // events for this frame. We really want to flush the event
287         // queue of mouse events, but don't have the ability to do
288         // that with osgViewer.
289         if (mouseWarped)
290             return true;
291         if (eventToViewport(ea, us, x, y) && mouseMotionHandler)
292             (*mouseMotionHandler)(x, y, &ea);
293         return true;
294     case osgGA::GUIEventAdapter::RESIZE:
295         SG_LOG(SG_VIEW, SG_DEBUG, "FGEventHandler::handle: RESIZE event " << ea.getWindowHeight() << " x " << ea.getWindowWidth() << ", resizable: " << resizable);
296         CameraGroup::getDefault()->resized();
297         if (resizable)
298           globals->get_renderer()->resize(ea.getWindowWidth(), ea.getWindowHeight());
299         statsHandler->handle(ea, us);
300       #ifdef SG_MAC
301         // work around OSG Cocoa-Viewer issue with resize event handling,
302         // where resize events are queued up, then dispatched in a batch, with
303         // no interveningd drawing calls.
304         puCleanUpJunk();
305       #endif
306         return true;
307      case osgGA::GUIEventAdapter::CLOSE_WINDOW:
308     case osgGA::GUIEventAdapter::QUIT_APPLICATION:
309         fgOSExit(0);
310         return true;
311     default:
312         return false;
313     }
314 }
315
316 void FGEventHandler::handleKey(const osgGA::GUIEventAdapter& ea, int& key,
317                                int& modifiers)
318 {
319     using namespace osgGA;
320     key = ea.getKey();
321     // XXX Probably other translations are needed too.
322     switch (key) {
323     case GUIEventAdapter::KEY_Escape:      key = 0x1b; break;
324     case GUIEventAdapter::KEY_Return:      key = '\n'; break;
325     case GUIEventAdapter::KEY_BackSpace:   key = '\b'; break;
326     case GUIEventAdapter::KEY_Delete:      key = 0x7f; break;
327     case GUIEventAdapter::KEY_Tab:         key = '\t'; break;
328     case GUIEventAdapter::KEY_Left:        key = PU_KEY_LEFT;      break;
329     case GUIEventAdapter::KEY_Up:          key = PU_KEY_UP;        break;
330     case GUIEventAdapter::KEY_Right:       key = PU_KEY_RIGHT;     break;
331     case GUIEventAdapter::KEY_Down:        key = PU_KEY_DOWN;      break;
332     case GUIEventAdapter::KEY_Page_Up:     key = PU_KEY_PAGE_UP;   break;
333     case GUIEventAdapter::KEY_Page_Down:   key = PU_KEY_PAGE_DOWN; break;
334     case GUIEventAdapter::KEY_Home:        key = PU_KEY_HOME;      break;
335     case GUIEventAdapter::KEY_End:         key = PU_KEY_END;       break;
336     case GUIEventAdapter::KEY_Insert:      key = PU_KEY_INSERT;    break;
337     case GUIEventAdapter::KEY_F1:          key = PU_KEY_F1;        break;
338     case GUIEventAdapter::KEY_F2:          key = PU_KEY_F2;        break;
339     case GUIEventAdapter::KEY_F3:          key = PU_KEY_F3;        break;
340     case GUIEventAdapter::KEY_F4:          key = PU_KEY_F4;        break;
341     case GUIEventAdapter::KEY_F5:          key = PU_KEY_F5;        break;
342     case GUIEventAdapter::KEY_F6:          key = PU_KEY_F6;        break;
343     case GUIEventAdapter::KEY_F7:          key = PU_KEY_F7;        break;
344     case GUIEventAdapter::KEY_F8:          key = PU_KEY_F8;        break;
345     case GUIEventAdapter::KEY_F9:          key = PU_KEY_F9;        break;
346     case GUIEventAdapter::KEY_F10:         key = PU_KEY_F10;       break;
347     case GUIEventAdapter::KEY_F11:         key = PU_KEY_F11;       break;
348     case GUIEventAdapter::KEY_F12:         key = PU_KEY_F12;       break;
349     case GUIEventAdapter::KEY_KP_Enter:    key = '\r'; break;
350     case GUIEventAdapter::KEY_KP_Add:      key = '+';  break;
351     case GUIEventAdapter::KEY_KP_Divide:   key = '/';  break;
352     case GUIEventAdapter::KEY_KP_Multiply: key = '*';  break;
353     case GUIEventAdapter::KEY_KP_Subtract: key = '-';  break;
354     }
355     osgGA::GUIEventAdapter::EventType eventType = ea.getEventType();
356
357 #ifdef __APPLE__
358     // Num Lock is always true on Mac
359     std::map<int, int>::iterator numPadIter = numlockKeyMap.find(key);
360     if (numPadIter != numlockKeyMap.end()) {
361         key = numPadIter->second;
362     }
363 #else
364     if (ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_NUM_LOCK)
365     {
366         // NumLock on: map to numeric keys
367         std::map<int, int>::iterator numPadIter = numlockKeyMap.find(key);
368         if (numPadIter != numlockKeyMap.end()) {
369             key = numPadIter->second;
370         }
371     }
372     else
373     {
374         // NumLock off: map to PU arrow keys
375         std::map<int, int>::iterator numPadIter = noNumlockKeyMap.find(key);
376         if (numPadIter != noNumlockKeyMap.end()) {
377             key = numPadIter->second;
378         }
379     }
380 #endif
381
382     modifiers = osgToFGModifiers(ea.getModKeyMask());
383     currentModifiers = modifiers;
384     if (eventType == osgGA::GUIEventAdapter::KEYUP)
385         modifiers |= KEYMOD_RELEASED;
386
387     // Release the letter key, for which the key press was reported. This
388     // is to deal with Ctrl-press -> a-press -> Ctrl-release -> a-release
389     // correctly.
390     if (key >= 0 && key < 128) {
391         if (modifiers & KEYMOD_RELEASED) {
392             key = release_keys[key];
393         } else {
394             release_keys[key] = key;
395             if (key >= 1 && key <= 26) {
396                 release_keys[key + '@'] = key;
397                 release_keys[key + '`'] = key;
398             } else if (key >= 'A' && key <= 'Z') {
399                 release_keys[key - '@'] = key;
400                 release_keys[tolower(key)] = key;
401             } else if (key >= 'a' && key <= 'z') {
402                 release_keys[key - '`'] = key;
403                 release_keys[toupper(key)] = key;
404             }
405         }
406     }
407 }
408
409 void FGEventHandler::handleStats(osgGA::GUIActionAdapter& us)
410 {
411     int type = _display->getIntValue() % osgViewer::StatsHandler::LAST;
412     if (type != statsType) {
413         statsEvent->setKey(displayStatsKey);
414         do {
415             statsType = (statsType + 1) % osgViewer::StatsHandler::LAST;
416             statsHandler->handle(*statsEvent, us);
417             if (changeStatsCameraRenderOrder) {
418                 statsHandler->getCamera()->setRenderOrder(osg::Camera::POST_RENDER, 99999);
419                 changeStatsCameraRenderOrder = false;
420             }
421         } while (statsType != type);
422
423         _display->setIntValue(statsType);
424     }
425
426     if (_print->getBoolValue()) {
427         statsEvent->setKey(printStatsKey);
428         statsHandler->handle(*statsEvent, us);
429         _print->setBoolValue(false);
430     }
431 }
432
433 void eventToWindowCoords(const osgGA::GUIEventAdapter* ea,
434                          double& x, double& y)
435 {
436     using namespace osg;
437     const GraphicsContext* gc = ea->getGraphicsContext();
438     const GraphicsContext::Traits* traits = gc->getTraits() ;
439     // Scale x, y to the dimensions of the window
440     x = (((ea->getX() - ea->getXmin()) / (ea->getXmax() - ea->getXmin()))
441          * (double)traits->width);
442     y = (((ea->getY() - ea->getYmin()) / (ea->getYmax() - ea->getYmin()))
443          * (double)traits->height);
444     if (ea->getMouseYOrientation() == osgGA::GUIEventAdapter::Y_INCREASING_DOWNWARDS)
445         y = (double)traits->height - y;
446 }
447
448 #if 0
449 void eventToWindowCoordsYDown(const osgGA::GUIEventAdapter* ea,
450                               double& x, double& y)
451 {
452     using namespace osg;
453     const GraphicsContext* gc = ea->getGraphicsContext();
454     const GraphicsContext::Traits* traits = gc->getTraits() ;
455     // Scale x, y to the dimensions of the window
456     x = (((ea->getX() - ea->getXmin()) / (ea->getXmax() - ea->getXmin()))
457          * (double)traits->width);
458     y = (((ea->getY() - ea->getYmin()) / (ea->getYmax() - ea->getYmin()))
459          * (double)traits->height);
460     if (ea->getMouseYOrientation() == osgGA::GUIEventAdapter::Y_INCREASING_UPWARDS)
461         y = (double)traits->height - y;
462 }
463 #endif
464     
465 }