1 // FGMouseInput.cxx -- handle user input from mouse devices
3 // Written by Torsten Dreyer, started August 2009
4 // Based on work from David Megginson, started May 2001.
6 // Copyright (C) 2009 Torsten Dreyer, Torsten (at) t3r _dot_ de
7 // Copyright (C) 2001 David Megginson, david@megginson.com
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.
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.
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.
29 #include "FGMouseInput.hxx"
31 #include <boost/foreach.hpp>
32 #include <osgGA/GUIEventAdapter>
34 #include <simgear/scene/util/SGPickCallback.hxx>
35 #include <simgear/timing/timestamp.hxx>
36 #include <simgear/scene/model/SGPickAnimation.hxx>
38 #include "FGButton.hxx"
39 #include "Main/globals.hxx"
40 #include <Viewer/renderer.hxx>
42 #include <Model/panelnode.hxx>
43 #include <Cockpit/panel.hxx>
44 #include <Viewer/FGEventHandler.hxx>
45 #include <GUI/MouseCursor.hxx>
49 const int MAX_MICE = 1;
50 const int MAX_MOUSE_BUTTONS = 8;
52 ////////////////////////////////////////////////////////////////////////
55 * List of currently pressed mouse button events
57 class ActivePickCallbacks : public std::map<int, std::list<SGSharedPtr<SGPickCallback> > > {
59 void update( double dt, unsigned int keyModState );
60 void init( int button, const osgGA::GUIEventAdapter* ea );
64 void ActivePickCallbacks::init( int button, const osgGA::GUIEventAdapter* ea )
67 flightgear::eventToWindowCoords(ea, windowPos.x(), windowPos.y());
69 // Get the list of hit callbacks. Take the first callback that
70 // accepts the mouse button press and ignore the rest of them
71 // That is they get sorted by distance and by scenegraph depth.
72 // The nearest one is the first one and the deepest
73 // (the most specialized one in the scenegraph) is the first.
74 std::vector<SGSceneryPick> pickList;
75 if (!globals->get_renderer()->pick(pickList, windowPos)) {
79 std::vector<SGSceneryPick>::const_iterator i;
80 for (i = pickList.begin(); i != pickList.end(); ++i) {
81 if (i->callback->buttonPressed(button, ea, i->info)) {
82 (*this)[button].push_back(i->callback);
88 void ActivePickCallbacks::update( double dt, unsigned int keyModState )
90 // handle repeatable mouse press events
91 for( iterator mi = begin(); mi != end(); ++mi ) {
92 std::list<SGSharedPtr<SGPickCallback> >::iterator li;
93 for (li = mi->second.begin(); li != mi->second.end(); ++li) {
94 (*li)->update(dt, keyModState);
99 ////////////////////////////////////////////////////////////////////////
103 * Settings for a mouse mode.
107 virtual ~mouse_mode ();
108 FGMouseCursor::Cursor cursor;
112 SGBindingList x_bindings[KEYMOD_MAX];
113 SGBindingList y_bindings[KEYMOD_MAX];
118 * Settings for a mouse.
124 SGPropertyNode_ptr mode_node;
125 SGPropertyNode_ptr mouse_button_nodes[MAX_MOUSE_BUTTONS];
129 SGTimeStamp timeSinceLastMove;
133 ////////////////////////////////////////////////////////////////////////
135 class FGMouseInput::FGMouseInputPrivate : public SGPropertyChangeListener
138 FGMouseInputPrivate() :
140 xSizeNode(fgGetNode("/sim/startup/xsize", false ) ),
141 ySizeNode(fgGetNode("/sim/startup/ysize", false ) ),
142 xAccelNode(fgGetNode("/devices/status/mice/mouse/accel-x", true ) ),
143 yAccelNode(fgGetNode("/devices/status/mice/mouse/accel-y", true ) ),
144 mouseXNode(fgGetNode("/devices/status/mice/mouse/x", true)),
145 mouseYNode(fgGetNode("/devices/status/mice/mouse/y", true))
147 tooltipTimeoutDone = false;
149 fgGetNode("/sim/mouse/hide-cursor", true )->addChangeListener(this, true);
150 fgGetNode("/sim/mouse/cursor-timeout-sec", true )->addChangeListener(this, true);
151 fgGetNode("/sim/mouse/right-button-mode-cycle-enabled", true)->addChangeListener(this, true);
152 fgGetNode("/sim/mouse/tooltip-delay-msec", true)->addChangeListener(this, true);
153 fgGetNode("/sim/mouse/click-shows-tooltip", true)->addChangeListener(this, true);
154 fgGetNode("/sim/mouse/drag-sensitivity", true)->addChangeListener(this, true);
155 fgGetNode("/sim/mouse/invert-mouse-wheel", true)->addChangeListener(this, true);
158 void centerMouseCursor(mouse& m)
161 m.x = (xSizeNode ? xSizeNode->getIntValue() : 800) / 2;
162 m.y = (ySizeNode ? ySizeNode->getIntValue() : 600) / 2;
163 fgWarpMouse(m.x, m.y);
167 void constrainMouse(int x, int y)
170 int xsize = xSizeNode ? xSizeNode->getIntValue() : 800;
171 int ysize = ySizeNode ? ySizeNode->getIntValue() : 600;
173 bool need_warp = false;
174 if (x <= (xsize * .25) || x >= (xsize * .75)) {
175 new_x = int(xsize * .5);
179 if (y <= (ysize * .25) || y >= (ysize * .75)) {
180 new_y = int(ysize * .5);
186 fgWarpMouse(new_x, new_y);
191 void doHoverPick(const osg::Vec2d& windowPos)
193 std::vector<SGSceneryPick> pickList;
194 SGPickCallback::Priority priority = SGPickCallback::PriorityScenery;
196 FGMouseCursor::Cursor cur = FGMouseCursor::CURSOR_ARROW;
197 bool explicitCursor = false;
198 bool didPick = false;
200 if (globals->get_renderer()->pick(pickList, windowPos)) {
202 std::vector<SGSceneryPick>::const_iterator i;
203 for (i = pickList.begin(); i != pickList.end(); ++i) {
204 bool done = i->callback->hover(windowPos, i->info);
205 std::string curName(i->callback->getCursor());
206 if (!curName.empty()) {
207 explicitCursor = true;
208 cur = FGMouseCursor::cursorFromString(curName.c_str());
211 // if the callback is of higher prioirty (lower enum index),
213 if (i->callback->getPriority() < priority) {
214 priority = i->callback->getPriority();
221 } // of picks iteration
222 } else { // of have valid pick
225 if (!explicitCursor && (priority == SGPickCallback::PriorityPanel)) {
226 cur = FGMouseCursor::CURSOR_HAND;
229 FGMouseCursor::instance()->setCursor(cur);
235 void doMouseMoveWithCallbacks(const osgGA::GUIEventAdapter* ea)
237 FGMouseCursor::Cursor cur = FGMouseCursor::CURSOR_CLOSED_HAND;
239 BOOST_FOREACH(SGPickCallback* cb, activePickCallbacks[0]) {
241 std::string curName(cb->getCursor());
242 if (!curName.empty()) {
243 cur = FGMouseCursor::cursorFromString(curName.c_str());
247 FGMouseCursor::instance()->setCursor(cur);
252 SGPropertyNode_ptr args(new SGPropertyNode);
253 globals->get_commands()->execute("update-hover", args);
257 // implement the property-change-listener interfacee
258 virtual void valueChanged( SGPropertyNode * node )
260 if (node->getNameString() == "drag-sensitivity") {
261 SGKnobAnimation::setDragSensitivity(node->getDoubleValue());
262 } else if (node->getNameString() == "invert-mouse-wheel") {
263 SGKnobAnimation::setAlternateMouseWheelDirection(node->getBoolValue());
264 } else if (node->getNameString() == "hide-cursor") {
265 hideCursor = node->getBoolValue();
266 } else if (node->getNameString() == "cursor-timeout-sec") {
267 cursorTimeoutMsec = node->getDoubleValue() * 1000;
268 } else if (node->getNameString() == "tooltip-delay-msec") {
269 tooltipDelayMsec = node->getIntValue();
270 } else if (node->getNameString() == "right-button-mode-cycle-enabled") {
271 rightClickModeCycle = node->getBoolValue();
272 } else if (node->getNameString() == "click-shows-tooltip") {
273 clickTriggersTooltip = node->getBoolValue();
278 ActivePickCallbacks activePickCallbacks;
280 mouse mice[MAX_MICE];
282 bool hideCursor, haveWarped;
283 bool tooltipTimeoutDone;
284 bool clickTriggersTooltip;
285 int tooltipDelayMsec, cursorTimeoutMsec;
286 bool rightClickModeCycle;
288 SGPropertyNode_ptr xSizeNode;
289 SGPropertyNode_ptr ySizeNode;
290 SGPropertyNode_ptr xAccelNode;
291 SGPropertyNode_ptr yAccelNode;
292 SGPropertyNode_ptr mouseXNode, mouseYNode;
296 ////////////////////////////////////////////////////////////////////////
297 // The Mouse Input Implementation
298 ////////////////////////////////////////////////////////////////////////
300 static FGMouseInput* global_mouseInput = NULL;
302 static void mouseClickHandler(int button, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
304 if(global_mouseInput)
305 global_mouseInput->doMouseClick(button, updown, x, y, mainWindow, ea);
308 static void mouseMotionHandler(int x, int y, const osgGA::GUIEventAdapter* ea)
310 if (global_mouseInput != 0)
311 global_mouseInput->doMouseMotion(x, y, ea);
316 FGMouseInput::FGMouseInput() :
317 d(new FGMouseInputPrivate)
319 global_mouseInput = this;
322 FGMouseInput::~FGMouseInput()
324 global_mouseInput = NULL;
327 void FGMouseInput::init()
329 SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse bindings");
332 SGPropertyNode * mouse_nodes = fgGetNode("/input/mice");
333 if (mouse_nodes == 0) {
334 SG_LOG(SG_INPUT, SG_WARN, "No mouse bindings (/input/mice)!!");
335 mouse_nodes = fgGetNode("/input/mice", true);
339 for (int i = 0; i < MAX_MICE; i++) {
340 SGPropertyNode * mouse_node = mouse_nodes->getChild("mouse", i, true);
341 mouse &m = d->mice[i];
343 // Grab node pointers
344 std::ostringstream buf;
345 buf << "/devices/status/mice/mouse[" << i << "]/mode";
346 m.mode_node = fgGetNode(buf.str().c_str());
347 if (m.mode_node == NULL) {
348 m.mode_node = fgGetNode(buf.str().c_str(), true);
349 m.mode_node->setIntValue(0);
351 for (j = 0; j < MAX_MOUSE_BUTTONS; j++) {
352 buf.seekp(ios_base::beg);
353 buf << "/devices/status/mice/mouse["<< i << "]/button[" << j << "]";
354 m.mouse_button_nodes[j] = fgGetNode(buf.str().c_str(), true);
355 m.mouse_button_nodes[j]->setBoolValue(false);
358 // Read all the modes
359 m.nModes = mouse_node->getIntValue("mode-count", 1);
360 m.modes = new mouse_mode[m.nModes];
362 for (int j = 0; j < m.nModes; j++) {
364 SGPropertyNode * mode_node = mouse_node->getChild("mode", j, true);
366 // Read the mouse cursor for this mode
367 m.modes[j].cursor = FGMouseCursor::cursorFromString(mode_node->getStringValue("cursor", "inherit"));
369 // Read other properties for this mode
370 m.modes[j].constrained = mode_node->getBoolValue("constrained", false);
371 m.modes[j].pass_through = mode_node->getBoolValue("pass-through", false);
373 // Read the button bindings for this mode
374 m.modes[j].buttons = new FGButton[MAX_MOUSE_BUTTONS];
375 std::ostringstream buf;
376 for (k = 0; k < MAX_MOUSE_BUTTONS; k++) {
377 buf.seekp(ios_base::beg);
378 buf << "mouse button " << k;
379 m.modes[j].buttons[k].init( mode_node->getChild("button", k), buf.str(), module );
382 // Read the axis bindings for this mode
383 read_bindings(mode_node->getChild("x-axis", 0, true), m.modes[j].x_bindings, KEYMOD_NONE, module );
384 read_bindings(mode_node->getChild("y-axis", 0, true), m.modes[j].y_bindings, KEYMOD_NONE, module );
386 if (mode_node->hasChild("x-axis-ctrl")) {
387 read_bindings(mode_node->getChild("x-axis-ctrl"), m.modes[j].x_bindings, KEYMOD_CTRL, module );
389 if (mode_node->hasChild("x-axis-shift")) {
390 read_bindings(mode_node->getChild("x-axis-shift"), m.modes[j].x_bindings, KEYMOD_SHIFT, module );
392 if (mode_node->hasChild("x-axis-ctrl-shift")) {
393 read_bindings(mode_node->getChild("x-axis-ctrl-shift"), m.modes[j].x_bindings, KEYMOD_CTRL|KEYMOD_SHIFT, module );
396 if (mode_node->hasChild("y-axis-ctrl")) {
397 read_bindings(mode_node->getChild("y-axis-ctrl"), m.modes[j].y_bindings, KEYMOD_CTRL, module );
399 if (mode_node->hasChild("y-axis-shift")) {
400 read_bindings(mode_node->getChild("y-axis-shift"), m.modes[j].y_bindings, KEYMOD_SHIFT, module );
402 if (mode_node->hasChild("y-axis-ctrl-shift")) {
403 read_bindings(mode_node->getChild("y-axis-ctrl-shift"), m.modes[j].y_bindings, KEYMOD_CTRL|KEYMOD_SHIFT, module );
405 } // of modes iteration
408 fgRegisterMouseClickHandler(mouseClickHandler);
409 fgRegisterMouseMotionHandler(mouseMotionHandler);
412 void FGMouseInput::update ( double dt )
414 mouse &m = d->mice[0];
415 int mode = m.mode_node->getIntValue();
416 if (mode != m.current_mode) {
417 // current mode has changed
418 m.current_mode = mode;
419 m.timeSinceLastMove.stamp();
421 if (mode >= 0 && mode < m.nModes) {
422 FGMouseCursor::instance()->setCursor(m.modes[mode].cursor);
423 d->centerMouseCursor(m);
425 SG_LOG(SG_INPUT, SG_WARN, "Mouse mode " << mode << " out of range");
426 FGMouseCursor::instance()->setCursor(FGMouseCursor::CURSOR_ARROW);
430 // if delay is <= 0, disable tooltips
431 if ( !d->tooltipTimeoutDone &&
432 (d->tooltipDelayMsec > 0) &&
433 (m.timeSinceLastMove.elapsedMSec() > d->tooltipDelayMsec))
435 d->tooltipTimeoutDone = true;
436 SGPropertyNode_ptr arg(new SGPropertyNode);
437 globals->get_commands()->execute("tooltip-timeout", arg);
440 if ( d->hideCursor ) {
441 if ( m.timeSinceLastMove.elapsedMSec() > d->cursorTimeoutMsec) {
442 FGMouseCursor::instance()->hideCursorUntilMouseMove();
443 m.timeSinceLastMove.stamp();
447 d->activePickCallbacks.update( dt, fgGetKeyModifiers() );
464 mouse_mode::mouse_mode ()
465 : cursor(FGMouseCursor::CURSOR_ARROW),
472 mouse_mode::~mouse_mode ()
474 // FIXME: memory leak
475 // for (int i = 0; i < KEYMOD_MAX; i++) {
477 // for (j = 0; i < x_bindings[i].size(); j++)
478 // delete bindings[i][j];
479 // for (j = 0; j < y_bindings[i].size(); j++)
480 // delete bindings[i][j];
487 void FGMouseInput::doMouseClick (int b, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
489 int modifiers = fgGetKeyModifiers();
491 mouse &m = d->mice[0];
492 mouse_mode &mode = m.modes[m.current_mode];
493 // Let the property manager know.
494 if (b >= 0 && b < MAX_MOUSE_BUTTONS)
495 m.mouse_button_nodes[b]->setBoolValue(updown == MOUSE_BUTTON_DOWN);
497 if (!d->rightClickModeCycle && (b == 2)) {
498 // in spring-loaded look mode, ignore right clicks entirely here
502 // Pass on to PUI and the panel if
503 // requested, and return if one of
504 // them consumes the event.
506 if (updown != MOUSE_BUTTON_DOWN) {
507 // Execute the mouse up event in any case, may be we should
508 // stop processing here?
509 while (!d->activePickCallbacks[b].empty()) {
510 d->activePickCallbacks[b].front()->buttonReleased(ea->getModKeyMask());
511 d->activePickCallbacks[b].pop_front();
515 if (mode.pass_through) {
516 // remove once PUI uses standard picking mechanism
517 if (0 <= x && 0 <= y && puMouse(b, updown, x, y))
518 return; // pui handled it
520 // pui didn't want the click event so compute a
521 // scenegraph intersection point corresponding to the mouse click
522 if (updown == MOUSE_BUTTON_DOWN) {
523 d->activePickCallbacks.init( b, ea );
525 if (d->clickTriggersTooltip) {
526 SGPropertyNode_ptr args(new SGPropertyNode);
527 args->setStringValue("reason", "click");
528 globals->get_commands()->execute("tooltip-timeout", args);
529 d->tooltipTimeoutDone = true;
532 // do a hover pick now, to fix up cursor
533 osg::Vec2d windowPos;
534 flightgear::eventToWindowCoords(ea, windowPos.x(), windowPos.y());
535 d->doHoverPick(windowPos);
536 } // mouse button was released
537 } // of pass-through mode
539 // OK, PUI and the panel didn't want the click
540 if (b >= MAX_MOUSE_BUTTONS) {
541 SG_LOG(SG_INPUT, SG_ALERT, "Mouse button " << b
542 << " where only " << MAX_MOUSE_BUTTONS << " expected");
546 m.modes[m.current_mode].buttons[b].update( modifiers, 0 != updown, x, y);
549 void FGMouseInput::processMotion(int x, int y, const osgGA::GUIEventAdapter* ea)
551 if (!d->activePickCallbacks[0].empty()) {
552 d->doMouseMoveWithCallbacks(ea);
556 mouse &m = d->mice[0];
557 int modeIndex = m.current_mode;
558 // are we in spring-loaded look mode?
559 if (!d->rightClickModeCycle) {
560 if (m.mouse_button_nodes[2]->getBoolValue()) {
561 // right mouse is down, force look mode
566 if (modeIndex == 0) {
567 osg::Vec2d windowPos;
568 flightgear::eventToWindowCoords(ea, windowPos.x(), windowPos.y());
569 d->doHoverPick(windowPos);
570 // mouse has moved, so we may need to issue tooltip-timeout command again
571 d->tooltipTimeoutDone = false;
574 mouse_mode &mode = m.modes[modeIndex];
576 // Pass on to PUI if requested, and return
577 // if PUI consumed the event.
578 if (mode.pass_through && puMouse(x, y)) {
584 // don't fire mouse-movement events at the first update after warping the mouse,
585 // just remember the new mouse position
586 d->haveWarped = false;
590 int modifiers = fgGetKeyModifiers();
591 int xsize = d->xSizeNode ? d->xSizeNode->getIntValue() : 800;
592 int ysize = d->ySizeNode ? d->ySizeNode->getIntValue() : 600;
594 // OK, PUI didn't want the event,
595 // so we can play with it.
598 d->xAccelNode->setIntValue( delta );
599 for (unsigned int i = 0; i < mode.x_bindings[modifiers].size(); i++)
600 mode.x_bindings[modifiers][i]->fire(double(delta), double(xsize));
604 d->yAccelNode->setIntValue( -delta );
605 for (unsigned int i = 0; i < mode.y_bindings[modifiers].size(); i++)
606 mode.y_bindings[modifiers][i]->fire(double(delta), double(ysize));
610 // Constrain the mouse if requested
611 if (mode.constrained) {
612 d->constrainMouse(x, y);
616 void FGMouseInput::doMouseMotion (int x, int y, const osgGA::GUIEventAdapter* ea)
618 mouse &m = d->mice[0];
620 if (m.current_mode < 0 || m.current_mode >= m.nModes) {
626 m.timeSinceLastMove.stamp();
627 FGMouseCursor::instance()->mouseMoved();
629 processMotion(x, y, ea);
633 d->mouseXNode->setIntValue(x);
634 d->mouseYNode->setIntValue(y);