]> git.mxchange.org Git - flightgear.git/blob - src/Input/FGMouseInput.cxx
Pass key-mod state into pick-callbacks.
[flightgear.git] / src / Input / FGMouseInput.cxx
1 // FGMouseInput.cxx -- handle user input from mouse devices
2 //
3 // Written by Torsten Dreyer, started August 2009
4 // Based on work from David Megginson, started May 2001.
5 //
6 // Copyright (C) 2009 Torsten Dreyer, Torsten (at) t3r _dot_ de
7 // Copyright (C) 2001 David Megginson, david@megginson.com
8 //
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
13 //
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 // General Public License for more details.
18 //
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
22 //
23 // $Id$
24
25 #ifdef HAVE_CONFIG_H
26 #  include "config.h"
27 #endif
28
29 #include "FGMouseInput.hxx"
30
31 #include <boost/foreach.hpp>
32 #include <osgGA/GUIEventAdapter>
33
34 #include <simgear/scene/util/SGPickCallback.hxx>
35 #include <simgear/timing/timestamp.hxx>
36
37 #include "FGButton.hxx"
38 #include "Main/globals.hxx"
39 #include <Viewer/renderer.hxx>
40 #include <plib/pu.h>
41 #include <Model/panelnode.hxx>
42 #include <Cockpit/panel.hxx>
43 #include <Viewer/FGEventHandler.hxx>
44 #include <GUI/MouseCursor.hxx>
45
46 using std::ios_base;
47
48 const int MAX_MICE = 1;
49 const int MAX_MOUSE_BUTTONS = 8;
50
51 ////////////////////////////////////////////////////////////////////////
52
53 /**
54  * List of currently pressed mouse button events
55  */
56 class ActivePickCallbacks : public std::map<int, std::list<SGSharedPtr<SGPickCallback> > > {
57 public:
58     void update( double dt, unsigned int keyModState );
59     void init( int button, const osgGA::GUIEventAdapter* ea );
60 };
61
62
63 void ActivePickCallbacks::init( int button, const osgGA::GUIEventAdapter* ea )
64 {
65   osg::Vec2d windowPos;
66   flightgear::eventToWindowCoords(ea, windowPos.x(), windowPos.y());
67     
68   // Get the list of hit callbacks. Take the first callback that
69   // accepts the mouse button press and ignore the rest of them
70   // That is they get sorted by distance and by scenegraph depth.
71   // The nearest one is the first one and the deepest
72   // (the most specialized one in the scenegraph) is the first.
73   std::vector<SGSceneryPick> pickList;
74   if (!globals->get_renderer()->pick(pickList, windowPos)) {
75     return;
76   }
77
78   std::vector<SGSceneryPick>::const_iterator i;
79   for (i = pickList.begin(); i != pickList.end(); ++i) {
80     if (i->callback->buttonPressed(button, ea, i->info)) {
81         (*this)[button].push_back(i->callback);
82         return;
83     }
84   }
85 }
86
87 void ActivePickCallbacks::update( double dt, unsigned int keyModState )
88 {
89   // handle repeatable mouse press events
90   for( iterator mi = begin(); mi != end(); ++mi ) {
91     std::list<SGSharedPtr<SGPickCallback> >::iterator li;
92     for (li = mi->second.begin(); li != mi->second.end(); ++li) {
93       (*li)->update(dt, keyModState);
94     }
95   }
96 }
97
98 ////////////////////////////////////////////////////////////////////////
99
100
101 /**
102  * Settings for a mouse mode.
103  */
104 struct mouse_mode {
105     mouse_mode ();
106     virtual ~mouse_mode ();
107     FGMouseCursor::Cursor cursor;
108     bool constrained;
109     bool pass_through;
110     FGButton * buttons;
111     SGBindingList x_bindings[KEYMOD_MAX];
112     SGBindingList y_bindings[KEYMOD_MAX];
113 };
114
115
116 /**
117  * Settings for a mouse.
118  */
119 struct mouse {
120     mouse ();
121     virtual ~mouse ();
122     int x, y;
123     SGPropertyNode_ptr mode_node;
124     SGPropertyNode_ptr mouse_button_nodes[MAX_MOUSE_BUTTONS];
125     int nModes;
126     int current_mode;
127     
128     SGTimeStamp timeSinceLastMove;
129     mouse_mode * modes;
130 };
131
132 ////////////////////////////////////////////////////////////////////////
133
134 class FGMouseInput::FGMouseInputPrivate
135 {
136 public:
137     FGMouseInputPrivate() :
138         haveWarped(false),
139         xSizeNode(fgGetNode("/sim/startup/xsize", false ) ),
140         ySizeNode(fgGetNode("/sim/startup/ysize", false ) ),
141         xAccelNode(fgGetNode("/devices/status/mice/mouse/accel-x", true ) ),
142         yAccelNode(fgGetNode("/devices/status/mice/mouse/accel-y", true ) ),
143         hideCursorNode(fgGetNode("/sim/mouse/hide-cursor", true ) ),
144         cursorTimeoutNode(fgGetNode("/sim/mouse/cursor-timeout-sec", true ) ),
145         rightButtonModeCycleNode(fgGetNode("/sim/mouse/right-button-mode-cycle-enabled", true)),
146         tooltipShowDelayNode( fgGetNode("/sim/mouse/tooltip-delay-msec", true) ),
147         clickTriggersTooltipNode( fgGetNode("/sim/mouse/click-shows-tooltip", true) ),
148         mouseXNode(fgGetNode("/devices/status/mice/mouse/x", true)),
149         mouseYNode(fgGetNode("/devices/status/mice/mouse/y", true))
150     {
151         tooltipTimeoutDone = false;
152     }
153   
154     void centerMouseCursor(mouse& m)
155     {    
156       // center the cursor
157       m.x = (xSizeNode ? xSizeNode->getIntValue() : 800) / 2;
158       m.y = (ySizeNode ? ySizeNode->getIntValue() : 600) / 2;
159       fgWarpMouse(m.x, m.y);
160       haveWarped = true;
161     }
162   
163     void constrainMouse(int x, int y)
164     {
165         int new_x=x,new_y=y;
166         int xsize = xSizeNode ? xSizeNode->getIntValue() : 800;
167         int ysize = ySizeNode ? ySizeNode->getIntValue() : 600;
168         
169         bool need_warp = false;
170         if (x <= (xsize * .25) || x >= (xsize * .75)) {
171           new_x = int(xsize * .5);
172           need_warp = true;
173         }
174
175         if (y <= (ysize * .25) || y >= (ysize * .75)) {
176           new_y = int(ysize * .5);
177           need_warp = true;
178         }
179
180         if (need_warp)
181         {
182           fgWarpMouse(new_x, new_y);
183           haveWarped = true;
184         }
185     }
186
187     void doHoverPick(const osg::Vec2d& windowPos)
188     {
189         std::vector<SGSceneryPick> pickList;
190         SGPickCallback::Priority priority = SGPickCallback::PriorityScenery;
191         
192         if (globals->get_renderer()->pick(pickList, windowPos)) {
193             
194             std::vector<SGSceneryPick>::const_iterator i;
195             for (i = pickList.begin(); i != pickList.end(); ++i) {
196                 if (i->callback->hover(windowPos, i->info)) {
197                     return;
198                 }
199                 
200             // if the callback is of higher prioirty (lower enum index),
201             // record that.
202                 if (i->callback->getPriority() < priority) {
203                     priority = i->callback->getPriority();
204                 }
205             }
206         } // of have valid pick
207                 
208         if (priority == SGPickCallback::PriorityPanel) {
209             FGMouseCursor::instance()->setCursor(FGMouseCursor::CURSOR_HAND);
210         } else {
211             // restore normal cursor
212             FGMouseCursor::instance()->setCursor(FGMouseCursor::CURSOR_ARROW);
213         }
214         
215         updateHover();
216     }
217     
218     void updateHover()
219     {
220         SGPropertyNode_ptr args(new SGPropertyNode);
221         globals->get_commands()->execute("update-hover", args);
222     }
223
224     
225     ActivePickCallbacks activePickCallbacks;
226
227     mouse mice[MAX_MICE];
228     
229     bool haveWarped;
230     bool tooltipTimeoutDone;
231   
232     SGPropertyNode_ptr xSizeNode;
233     SGPropertyNode_ptr ySizeNode;
234     SGPropertyNode_ptr xAccelNode;
235     SGPropertyNode_ptr yAccelNode;
236     SGPropertyNode_ptr hideCursorNode;
237     SGPropertyNode_ptr cursorTimeoutNode;
238     SGPropertyNode_ptr rightButtonModeCycleNode;
239     SGPropertyNode_ptr tooltipShowDelayNode;
240     SGPropertyNode_ptr clickTriggersTooltipNode;
241     SGPropertyNode_ptr mouseXNode, mouseYNode;
242 };
243
244
245 ////////////////////////////////////////////////////////////////////////
246 // The Mouse Input Implementation
247 ////////////////////////////////////////////////////////////////////////
248
249 static FGMouseInput* global_mouseInput = NULL;
250
251 static void mouseClickHandler(int button, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
252 {
253     if(global_mouseInput)
254         global_mouseInput->doMouseClick(button, updown, x, y, mainWindow, ea);
255 }
256
257 static void mouseMotionHandler(int x, int y, const osgGA::GUIEventAdapter* ea)
258 {
259     if (global_mouseInput != 0)
260         global_mouseInput->doMouseMotion(x, y, ea);
261 }
262
263
264
265 FGMouseInput::FGMouseInput() :
266   d(new FGMouseInputPrivate)
267 {
268     global_mouseInput = this;
269 }
270
271 FGMouseInput::~FGMouseInput()
272 {
273     global_mouseInput = NULL;
274 }
275
276 void FGMouseInput::init()
277 {
278   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse bindings");
279   string module = "";
280
281   SGPropertyNode * mouse_nodes = fgGetNode("/input/mice");
282   if (mouse_nodes == 0) {
283     SG_LOG(SG_INPUT, SG_WARN, "No mouse bindings (/input/mice)!!");
284     mouse_nodes = fgGetNode("/input/mice", true);
285   }
286
287   int j;
288   for (int i = 0; i < MAX_MICE; i++) {
289     SGPropertyNode * mouse_node = mouse_nodes->getChild("mouse", i, true);
290     mouse &m = d->mice[i];
291
292                                 // Grab node pointers
293     std::ostringstream buf;
294     buf <<  "/devices/status/mice/mouse[" << i << "]/mode";
295     m.mode_node = fgGetNode(buf.str().c_str());
296     if (m.mode_node == NULL) {
297       m.mode_node = fgGetNode(buf.str().c_str(), true);
298       m.mode_node->setIntValue(0);
299     }
300     for (j = 0; j < MAX_MOUSE_BUTTONS; j++) {
301       buf.seekp(ios_base::beg);
302       buf << "/devices/status/mice/mouse["<< i << "]/button[" << j << "]";
303       m.mouse_button_nodes[j] = fgGetNode(buf.str().c_str(), true);
304       m.mouse_button_nodes[j]->setBoolValue(false);
305     }
306
307    // Read all the modes
308     m.nModes = mouse_node->getIntValue("mode-count", 1);
309     m.modes = new mouse_mode[m.nModes];
310
311     for (int j = 0; j < m.nModes; j++) {
312       int k;
313       SGPropertyNode * mode_node = mouse_node->getChild("mode", j, true);
314
315     // Read the mouse cursor for this mode
316       m.modes[j].cursor = FGMouseCursor::cursorFromString(mode_node->getStringValue("cursor", "inherit"));
317         
318       // Read other properties for this mode
319       m.modes[j].constrained = mode_node->getBoolValue("constrained", false);
320       m.modes[j].pass_through = mode_node->getBoolValue("pass-through", false);
321
322       // Read the button bindings for this mode
323       m.modes[j].buttons = new FGButton[MAX_MOUSE_BUTTONS];
324       std::ostringstream buf;
325       for (k = 0; k < MAX_MOUSE_BUTTONS; k++) {
326         buf.seekp(ios_base::beg);
327         buf << "mouse button " << k;
328         m.modes[j].buttons[k].init( mode_node->getChild("button", k), buf.str(), module );
329       }
330
331       // Read the axis bindings for this mode
332       read_bindings(mode_node->getChild("x-axis", 0, true), m.modes[j].x_bindings, KEYMOD_NONE, module );
333       read_bindings(mode_node->getChild("y-axis", 0, true), m.modes[j].y_bindings, KEYMOD_NONE, module );
334       
335       if (mode_node->hasChild("x-axis-ctrl")) {
336         read_bindings(mode_node->getChild("x-axis-ctrl"), m.modes[j].x_bindings, KEYMOD_CTRL, module );
337       }
338       
339       if (mode_node->hasChild("y-axis-ctrl")) {
340         read_bindings(mode_node->getChild("y-axis-ctrl"), m.modes[j].y_bindings, KEYMOD_CTRL, module );
341       }
342     } // of modes iteration
343   }
344
345   fgRegisterMouseClickHandler(mouseClickHandler);
346   fgRegisterMouseMotionHandler(mouseMotionHandler);
347 }
348
349 void FGMouseInput::update ( double dt )
350 {
351   int cursorTimeoutMsec = d->cursorTimeoutNode->getDoubleValue() * 1000;
352   int tooltipDelayMsec = d->tooltipShowDelayNode->getIntValue();
353   
354   mouse &m = d->mice[0];
355   int mode =  m.mode_node->getIntValue();
356   if (mode != m.current_mode) {
357     // current mode has changed
358     m.current_mode = mode;
359     m.timeSinceLastMove.stamp();
360       
361     if (mode >= 0 && mode < m.nModes) {
362       FGMouseCursor::instance()->setCursor(m.modes[mode].cursor);
363       d->centerMouseCursor(m);
364     } else {
365       SG_LOG(SG_INPUT, SG_WARN, "Mouse mode " << mode << " out of range");
366       FGMouseCursor::instance()->setCursor(FGMouseCursor::CURSOR_ARROW);
367     }
368   }
369
370   if ( d->hideCursorNode == NULL || d->hideCursorNode->getBoolValue() ) {
371       // if delay is <= 0, disable tooltips
372       if ( !d->tooltipTimeoutDone &&
373            (tooltipDelayMsec > 0) &&
374            (m.timeSinceLastMove.elapsedMSec() > tooltipDelayMsec))
375       {
376           d->tooltipTimeoutDone = true;
377           SGPropertyNode_ptr arg(new SGPropertyNode);
378           globals->get_commands()->execute("tooltip-timeout", arg);
379       }
380     
381       if ( m.timeSinceLastMove.elapsedMSec() > cursorTimeoutMsec) {
382           FGMouseCursor::instance()->hideCursorUntilMouseMove();
383           m.timeSinceLastMove.stamp();
384       }
385   }
386     
387   d->activePickCallbacks.update( dt, fgGetKeyModifiers() );
388 }
389
390 mouse::mouse ()
391   : x(-1),
392     y(-1),
393     nModes(1),
394     current_mode(0),
395     modes(NULL)
396 {
397 }
398
399 mouse::~mouse ()
400 {
401   delete [] modes;
402 }
403
404 mouse_mode::mouse_mode ()
405   : cursor(FGMouseCursor::CURSOR_ARROW),
406     constrained(false),
407     pass_through(false),
408     buttons(NULL)
409 {
410 }
411
412 mouse_mode::~mouse_mode ()
413 {
414                                 // FIXME: memory leak
415 //   for (int i = 0; i < KEYMOD_MAX; i++) {
416 //     int j;
417 //     for (j = 0; i < x_bindings[i].size(); j++)
418 //       delete bindings[i][j];
419 //     for (j = 0; j < y_bindings[i].size(); j++)
420 //       delete bindings[i][j];
421 //   }
422   if (buttons) {
423     delete [] buttons;
424   }
425 }
426
427 void FGMouseInput::doMouseClick (int b, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
428 {
429   int modifiers = fgGetKeyModifiers();
430
431   mouse &m = d->mice[0];
432   mouse_mode &mode = m.modes[m.current_mode];
433                                 // Let the property manager know.
434   if (b >= 0 && b < MAX_MOUSE_BUTTONS)
435     m.mouse_button_nodes[b]->setBoolValue(updown == MOUSE_BUTTON_DOWN);
436
437   if (!d->rightButtonModeCycleNode->getBoolValue() && (b == 2)) {
438     // in spring-loaded look mode, ignore right clicks entirely here
439     return;
440   }
441   
442   // Pass on to PUI and the panel if
443   // requested, and return if one of
444   // them consumes the event.
445
446   if (updown != MOUSE_BUTTON_DOWN) {
447     // Execute the mouse up event in any case, may be we should
448     // stop processing here?
449     while (!d->activePickCallbacks[b].empty()) {
450       d->activePickCallbacks[b].front()->buttonReleased(ea->getModKeyMask());
451       d->activePickCallbacks[b].pop_front();
452     }
453   }
454
455   if (mode.pass_through) {
456     // remove once PUI uses standard picking mechanism
457     if (0 <= x && 0 <= y && puMouse(b, updown, x, y))
458       return;
459     else {
460       // pui didn't want the click event so compute a
461       // scenegraph intersection point corresponding to the mouse click
462       if (updown == MOUSE_BUTTON_DOWN) {
463         d->activePickCallbacks.init( b, ea );
464       }
465     }
466   }
467
468   // OK, PUI and the panel didn't want the click
469   if (b >= MAX_MOUSE_BUTTONS) {
470     SG_LOG(SG_INPUT, SG_ALERT, "Mouse button " << b
471            << " where only " << MAX_MOUSE_BUTTONS << " expected");
472     return;
473   }
474
475   m.modes[m.current_mode].buttons[b].update( modifiers, 0 != updown, x, y);
476   
477   if (d->clickTriggersTooltipNode->getBoolValue()) {
478     SGPropertyNode_ptr args(new SGPropertyNode);
479     args->setStringValue("reason", "click");
480     globals->get_commands()->execute("tooltip-timeout", args);
481     d->tooltipTimeoutDone = true;
482   }
483 }
484
485 void FGMouseInput::processMotion(int x, int y, const osgGA::GUIEventAdapter* ea)
486 {
487   if (!d->activePickCallbacks[0].empty()) {
488     //SG_LOG(SG_GENERAL, SG_INFO, "mouse-motion, have active pick callback");
489     BOOST_FOREACH(SGPickCallback* cb, d->activePickCallbacks[0]) {
490       cb->mouseMoved(ea);
491     }
492     return;
493   }
494   
495   mouse &m = d->mice[0];
496   int modeIndex = m.current_mode;
497   // are we in spring-loaded look mode?
498   if (!d->rightButtonModeCycleNode->getBoolValue()) {
499     if (m.mouse_button_nodes[2]->getBoolValue()) {
500       // right mouse is down, force look mode
501       modeIndex = 3;
502     }
503   }
504
505   if (modeIndex == 0) {
506     osg::Vec2d windowPos;
507     flightgear::eventToWindowCoords(ea, windowPos.x(), windowPos.y());
508     d->doHoverPick(windowPos);
509     // mouse has moved, so we may need to issue tooltip-timeout command again
510     d->tooltipTimeoutDone = false;
511   }
512   
513   mouse_mode &mode = m.modes[modeIndex];
514   
515   // Pass on to PUI if requested, and return
516   // if PUI consumed the event.
517   if (mode.pass_through && puMouse(x, y)) {
518     return;
519   }
520
521   if (d->haveWarped)
522   {
523     // don't fire mouse-movement events at the first update after warping the mouse,
524     // just remember the new mouse position
525     d->haveWarped = false;
526   }
527   else
528   {
529     int modifiers = fgGetKeyModifiers();
530     int xsize = d->xSizeNode ? d->xSizeNode->getIntValue() : 800;
531     int ysize = d->ySizeNode ? d->ySizeNode->getIntValue() : 600;
532       
533     // OK, PUI didn't want the event,
534     // so we can play with it.
535     if (x != m.x) {
536       int delta = x - m.x;
537       d->xAccelNode->setIntValue( delta );
538       for (unsigned int i = 0; i < mode.x_bindings[modifiers].size(); i++)
539         mode.x_bindings[modifiers][i]->fire(double(delta), double(xsize));
540     }
541     if (y != m.y) {
542       int delta = y - m.y;
543       d->yAccelNode->setIntValue( -delta );
544       for (unsigned int i = 0; i < mode.y_bindings[modifiers].size(); i++)
545         mode.y_bindings[modifiers][i]->fire(double(delta), double(ysize));
546     }
547   }
548   
549   // Constrain the mouse if requested
550   if (mode.constrained) {
551     d->constrainMouse(x, y);
552   }
553 }
554
555 void FGMouseInput::doMouseMotion (int x, int y, const osgGA::GUIEventAdapter* ea)
556 {
557   mouse &m = d->mice[0];
558
559   if (m.current_mode < 0 || m.current_mode >= m.nModes) {
560       m.x = x;
561       m.y = y;
562       return;
563   }
564
565   m.timeSinceLastMove.stamp();
566   FGMouseCursor::instance()->mouseMoved();
567
568   processMotion(x, y, ea);
569     
570   m.x = x;
571   m.y = y;
572   d->mouseXNode->setIntValue(x);
573   d->mouseYNode->setIntValue(y);
574 }
575
576
577