]> git.mxchange.org Git - flightgear.git/blob - src/Input/FGMouseInput.cxx
Make tooltips independent of cursor auto-hide.
[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 #include <simgear/scene/model/SGPickAnimation.hxx>
37
38 #include "FGButton.hxx"
39 #include "Main/globals.hxx"
40 #include <Viewer/renderer.hxx>
41 #include <plib/pu.h>
42 #include <Model/panelnode.hxx>
43 #include <Cockpit/panel.hxx>
44 #include <Viewer/FGEventHandler.hxx>
45 #include <GUI/MouseCursor.hxx>
46
47 using std::ios_base;
48
49 const int MAX_MICE = 1;
50 const int MAX_MOUSE_BUTTONS = 8;
51
52 ////////////////////////////////////////////////////////////////////////
53
54 /**
55  * List of currently pressed mouse button events
56  */
57 class ActivePickCallbacks : public std::map<int, std::list<SGSharedPtr<SGPickCallback> > > {
58 public:
59     void update( double dt, unsigned int keyModState );
60     void init( int button, const osgGA::GUIEventAdapter* ea );
61 };
62
63
64 void ActivePickCallbacks::init( int button, const osgGA::GUIEventAdapter* ea )
65 {
66   osg::Vec2d windowPos;
67   flightgear::eventToWindowCoords(ea, windowPos.x(), windowPos.y());
68     
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)) {
76     return;
77   }
78
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);
83         return;
84     }
85   }
86 }
87
88 void ActivePickCallbacks::update( double dt, unsigned int keyModState )
89 {
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);
95     }
96   }
97 }
98
99 ////////////////////////////////////////////////////////////////////////
100
101
102 /**
103  * Settings for a mouse mode.
104  */
105 struct mouse_mode {
106     mouse_mode ();
107     virtual ~mouse_mode ();
108     FGMouseCursor::Cursor cursor;
109     bool constrained;
110     bool pass_through;
111     FGButton * buttons;
112     SGBindingList x_bindings[KEYMOD_MAX];
113     SGBindingList y_bindings[KEYMOD_MAX];
114 };
115
116
117 /**
118  * Settings for a mouse.
119  */
120 struct mouse {
121     mouse ();
122     virtual ~mouse ();
123     int x, y;
124     SGPropertyNode_ptr mode_node;
125     SGPropertyNode_ptr mouse_button_nodes[MAX_MOUSE_BUTTONS];
126     int nModes;
127     int current_mode;
128     
129     SGTimeStamp timeSinceLastMove;
130     mouse_mode * modes;
131 };
132
133 ////////////////////////////////////////////////////////////////////////
134
135 class FGMouseInput::FGMouseInputPrivate : public SGPropertyChangeListener
136 {
137 public:
138     FGMouseInputPrivate() :
139         haveWarped(false),
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))
146     {
147         tooltipTimeoutDone = false;
148
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);
156     }
157   
158     void centerMouseCursor(mouse& m)
159     {    
160       // center the cursor
161       m.x = (xSizeNode ? xSizeNode->getIntValue() : 800) / 2;
162       m.y = (ySizeNode ? ySizeNode->getIntValue() : 600) / 2;
163       fgWarpMouse(m.x, m.y);
164       haveWarped = true;
165     }
166   
167     void constrainMouse(int x, int y)
168     {
169         int new_x=x,new_y=y;
170         int xsize = xSizeNode ? xSizeNode->getIntValue() : 800;
171         int ysize = ySizeNode ? ySizeNode->getIntValue() : 600;
172         
173         bool need_warp = false;
174         if (x <= (xsize * .25) || x >= (xsize * .75)) {
175           new_x = int(xsize * .5);
176           need_warp = true;
177         }
178
179         if (y <= (ysize * .25) || y >= (ysize * .75)) {
180           new_y = int(ysize * .5);
181           need_warp = true;
182         }
183
184         if (need_warp)
185         {
186           fgWarpMouse(new_x, new_y);
187           haveWarped = true;
188         }
189     }
190
191     void doHoverPick(const osg::Vec2d& windowPos)
192     {
193         std::vector<SGSceneryPick> pickList;
194         SGPickCallback::Priority priority = SGPickCallback::PriorityScenery;
195         
196         if (globals->get_renderer()->pick(pickList, windowPos)) {
197             
198             std::vector<SGSceneryPick>::const_iterator i;
199             for (i = pickList.begin(); i != pickList.end(); ++i) {
200                 if (i->callback->hover(windowPos, i->info)) {
201                     return;
202                 }
203                 
204             // if the callback is of higher prioirty (lower enum index),
205             // record that.
206                 if (i->callback->getPriority() < priority) {
207                     priority = i->callback->getPriority();
208                 }
209             }
210         } // of have valid pick
211                 
212         if (priority == SGPickCallback::PriorityPanel) {
213             FGMouseCursor::instance()->setCursor(FGMouseCursor::CURSOR_HAND);
214         } else {
215             // restore normal cursor
216             FGMouseCursor::instance()->setCursor(FGMouseCursor::CURSOR_ARROW);
217         }
218         
219         updateHover();
220     }
221     
222     void updateHover()
223     {
224         SGPropertyNode_ptr args(new SGPropertyNode);
225         globals->get_commands()->execute("update-hover", args);
226     }
227
228     
229     // implement the property-change-listener interfacee
230     virtual void valueChanged( SGPropertyNode * node )
231     {
232         if (node->getNameString() == "drag-sensitivity") {
233             SGKnobAnimation::setDragSensitivity(node->getDoubleValue());
234         } else if (node->getNameString() == "invert-mouse-wheel") {
235             SGKnobAnimation::setAlternateMouseWheelDirection(node->getBoolValue());
236         } else if (node->getNameString() == "hide-cursor") {
237             hideCursor = node->getBoolValue();
238         } else if (node->getNameString() == "cursor-timeout-sec") {
239             cursorTimeoutMsec = node->getDoubleValue() * 1000;
240         } else if (node->getNameString() == "tooltip-delay-msec") {
241             tooltipDelayMsec = node->getIntValue();
242         } else if (node->getNameString() == "right-button-mode-cycle-enabled") {
243             rightClickModeCycle = node->getBoolValue();
244         } else if (node->getNameString() == "click-shows-tooltip") {
245             clickTriggersTooltip = node->getBoolValue();
246
247         }
248     }
249     
250     ActivePickCallbacks activePickCallbacks;
251
252     mouse mice[MAX_MICE];
253     
254     bool hideCursor, haveWarped;
255     bool tooltipTimeoutDone;
256     bool clickTriggersTooltip;
257     int tooltipDelayMsec, cursorTimeoutMsec;
258     bool rightClickModeCycle;
259     
260     SGPropertyNode_ptr xSizeNode;
261     SGPropertyNode_ptr ySizeNode;
262     SGPropertyNode_ptr xAccelNode;
263     SGPropertyNode_ptr yAccelNode;
264     SGPropertyNode_ptr mouseXNode, mouseYNode;
265 };
266
267
268 ////////////////////////////////////////////////////////////////////////
269 // The Mouse Input Implementation
270 ////////////////////////////////////////////////////////////////////////
271
272 static FGMouseInput* global_mouseInput = NULL;
273
274 static void mouseClickHandler(int button, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
275 {
276     if(global_mouseInput)
277         global_mouseInput->doMouseClick(button, updown, x, y, mainWindow, ea);
278 }
279
280 static void mouseMotionHandler(int x, int y, const osgGA::GUIEventAdapter* ea)
281 {
282     if (global_mouseInput != 0)
283         global_mouseInput->doMouseMotion(x, y, ea);
284 }
285
286
287
288 FGMouseInput::FGMouseInput() :
289   d(new FGMouseInputPrivate)
290 {
291     global_mouseInput = this;
292 }
293
294 FGMouseInput::~FGMouseInput()
295 {
296     global_mouseInput = NULL;
297 }
298
299 void FGMouseInput::init()
300 {
301   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse bindings");
302   string module = "";
303
304   SGPropertyNode * mouse_nodes = fgGetNode("/input/mice");
305   if (mouse_nodes == 0) {
306     SG_LOG(SG_INPUT, SG_WARN, "No mouse bindings (/input/mice)!!");
307     mouse_nodes = fgGetNode("/input/mice", true);
308   }
309
310   int j;
311   for (int i = 0; i < MAX_MICE; i++) {
312     SGPropertyNode * mouse_node = mouse_nodes->getChild("mouse", i, true);
313     mouse &m = d->mice[i];
314
315                                 // Grab node pointers
316     std::ostringstream buf;
317     buf <<  "/devices/status/mice/mouse[" << i << "]/mode";
318     m.mode_node = fgGetNode(buf.str().c_str());
319     if (m.mode_node == NULL) {
320       m.mode_node = fgGetNode(buf.str().c_str(), true);
321       m.mode_node->setIntValue(0);
322     }
323     for (j = 0; j < MAX_MOUSE_BUTTONS; j++) {
324       buf.seekp(ios_base::beg);
325       buf << "/devices/status/mice/mouse["<< i << "]/button[" << j << "]";
326       m.mouse_button_nodes[j] = fgGetNode(buf.str().c_str(), true);
327       m.mouse_button_nodes[j]->setBoolValue(false);
328     }
329
330    // Read all the modes
331     m.nModes = mouse_node->getIntValue("mode-count", 1);
332     m.modes = new mouse_mode[m.nModes];
333
334     for (int j = 0; j < m.nModes; j++) {
335       int k;
336       SGPropertyNode * mode_node = mouse_node->getChild("mode", j, true);
337
338     // Read the mouse cursor for this mode
339       m.modes[j].cursor = FGMouseCursor::cursorFromString(mode_node->getStringValue("cursor", "inherit"));
340         
341       // Read other properties for this mode
342       m.modes[j].constrained = mode_node->getBoolValue("constrained", false);
343       m.modes[j].pass_through = mode_node->getBoolValue("pass-through", false);
344
345       // Read the button bindings for this mode
346       m.modes[j].buttons = new FGButton[MAX_MOUSE_BUTTONS];
347       std::ostringstream buf;
348       for (k = 0; k < MAX_MOUSE_BUTTONS; k++) {
349         buf.seekp(ios_base::beg);
350         buf << "mouse button " << k;
351         m.modes[j].buttons[k].init( mode_node->getChild("button", k), buf.str(), module );
352       }
353
354       // Read the axis bindings for this mode
355       read_bindings(mode_node->getChild("x-axis", 0, true), m.modes[j].x_bindings, KEYMOD_NONE, module );
356       read_bindings(mode_node->getChild("y-axis", 0, true), m.modes[j].y_bindings, KEYMOD_NONE, module );
357       
358       if (mode_node->hasChild("x-axis-ctrl")) {
359         read_bindings(mode_node->getChild("x-axis-ctrl"), m.modes[j].x_bindings, KEYMOD_CTRL, module );
360       }
361       
362       if (mode_node->hasChild("y-axis-ctrl")) {
363         read_bindings(mode_node->getChild("y-axis-ctrl"), m.modes[j].y_bindings, KEYMOD_CTRL, module );
364       }
365     } // of modes iteration
366   }
367
368   fgRegisterMouseClickHandler(mouseClickHandler);
369   fgRegisterMouseMotionHandler(mouseMotionHandler);
370 }
371
372 void FGMouseInput::update ( double dt )
373 {
374   mouse &m = d->mice[0];
375   int mode =  m.mode_node->getIntValue();
376   if (mode != m.current_mode) {
377     // current mode has changed
378     m.current_mode = mode;
379     m.timeSinceLastMove.stamp();
380       
381     if (mode >= 0 && mode < m.nModes) {
382       FGMouseCursor::instance()->setCursor(m.modes[mode].cursor);
383       d->centerMouseCursor(m);
384     } else {
385       SG_LOG(SG_INPUT, SG_WARN, "Mouse mode " << mode << " out of range");
386       FGMouseCursor::instance()->setCursor(FGMouseCursor::CURSOR_ARROW);
387     }
388   }
389
390   // if delay is <= 0, disable tooltips
391   if ( !d->tooltipTimeoutDone &&
392       (d->tooltipDelayMsec > 0) &&
393       (m.timeSinceLastMove.elapsedMSec() > d->tooltipDelayMsec))
394   {
395       d->tooltipTimeoutDone = true;
396       SGPropertyNode_ptr arg(new SGPropertyNode);
397       globals->get_commands()->execute("tooltip-timeout", arg);
398   }
399   
400   if ( d->hideCursor ) {
401       if ( m.timeSinceLastMove.elapsedMSec() > d->cursorTimeoutMsec) {
402           FGMouseCursor::instance()->hideCursorUntilMouseMove();
403           m.timeSinceLastMove.stamp();
404       }
405   }
406     
407   d->activePickCallbacks.update( dt, fgGetKeyModifiers() );
408 }
409
410 mouse::mouse ()
411   : x(-1),
412     y(-1),
413     nModes(1),
414     current_mode(0),
415     modes(NULL)
416 {
417 }
418
419 mouse::~mouse ()
420 {
421   delete [] modes;
422 }
423
424 mouse_mode::mouse_mode ()
425   : cursor(FGMouseCursor::CURSOR_ARROW),
426     constrained(false),
427     pass_through(false),
428     buttons(NULL)
429 {
430 }
431
432 mouse_mode::~mouse_mode ()
433 {
434                                 // FIXME: memory leak
435 //   for (int i = 0; i < KEYMOD_MAX; i++) {
436 //     int j;
437 //     for (j = 0; i < x_bindings[i].size(); j++)
438 //       delete bindings[i][j];
439 //     for (j = 0; j < y_bindings[i].size(); j++)
440 //       delete bindings[i][j];
441 //   }
442   if (buttons) {
443     delete [] buttons;
444   }
445 }
446
447 void FGMouseInput::doMouseClick (int b, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
448 {
449   int modifiers = fgGetKeyModifiers();
450
451   mouse &m = d->mice[0];
452   mouse_mode &mode = m.modes[m.current_mode];
453                                 // Let the property manager know.
454   if (b >= 0 && b < MAX_MOUSE_BUTTONS)
455     m.mouse_button_nodes[b]->setBoolValue(updown == MOUSE_BUTTON_DOWN);
456
457   if (!d->rightClickModeCycle && (b == 2)) {
458     // in spring-loaded look mode, ignore right clicks entirely here
459     return;
460   }
461   
462   // Pass on to PUI and the panel if
463   // requested, and return if one of
464   // them consumes the event.
465
466   if (updown != MOUSE_BUTTON_DOWN) {
467     // Execute the mouse up event in any case, may be we should
468     // stop processing here?
469     while (!d->activePickCallbacks[b].empty()) {
470       d->activePickCallbacks[b].front()->buttonReleased(ea->getModKeyMask());
471       d->activePickCallbacks[b].pop_front();
472     }
473   }
474
475   if (mode.pass_through) {
476     // remove once PUI uses standard picking mechanism
477     if (0 <= x && 0 <= y && puMouse(b, updown, x, y))
478       return;
479     else {
480       // pui didn't want the click event so compute a
481       // scenegraph intersection point corresponding to the mouse click
482       if (updown == MOUSE_BUTTON_DOWN) {
483         d->activePickCallbacks.init( b, ea );
484       }
485     }
486   }
487
488   // OK, PUI and the panel didn't want the click
489   if (b >= MAX_MOUSE_BUTTONS) {
490     SG_LOG(SG_INPUT, SG_ALERT, "Mouse button " << b
491            << " where only " << MAX_MOUSE_BUTTONS << " expected");
492     return;
493   }
494
495   m.modes[m.current_mode].buttons[b].update( modifiers, 0 != updown, x, y);
496   
497   if (d->clickTriggersTooltip) {
498     SGPropertyNode_ptr args(new SGPropertyNode);
499     args->setStringValue("reason", "click");
500     globals->get_commands()->execute("tooltip-timeout", args);
501     d->tooltipTimeoutDone = true;
502   }
503 }
504
505 void FGMouseInput::processMotion(int x, int y, const osgGA::GUIEventAdapter* ea)
506 {
507   if (!d->activePickCallbacks[0].empty()) {
508     //SG_LOG(SG_GENERAL, SG_INFO, "mouse-motion, have active pick callback");
509     BOOST_FOREACH(SGPickCallback* cb, d->activePickCallbacks[0]) {
510       cb->mouseMoved(ea);
511     }
512     return;
513   }
514   
515   mouse &m = d->mice[0];
516   int modeIndex = m.current_mode;
517   // are we in spring-loaded look mode?
518   if (!d->rightClickModeCycle) {
519     if (m.mouse_button_nodes[2]->getBoolValue()) {
520       // right mouse is down, force look mode
521       modeIndex = 3;
522     }
523   }
524
525   if (modeIndex == 0) {
526     osg::Vec2d windowPos;
527     flightgear::eventToWindowCoords(ea, windowPos.x(), windowPos.y());
528     d->doHoverPick(windowPos);
529     // mouse has moved, so we may need to issue tooltip-timeout command again
530     d->tooltipTimeoutDone = false;
531   }
532   
533   mouse_mode &mode = m.modes[modeIndex];
534   
535   // Pass on to PUI if requested, and return
536   // if PUI consumed the event.
537   if (mode.pass_through && puMouse(x, y)) {
538     return;
539   }
540
541   if (d->haveWarped)
542   {
543     // don't fire mouse-movement events at the first update after warping the mouse,
544     // just remember the new mouse position
545     d->haveWarped = false;
546   }
547   else
548   {
549     int modifiers = fgGetKeyModifiers();
550     int xsize = d->xSizeNode ? d->xSizeNode->getIntValue() : 800;
551     int ysize = d->ySizeNode ? d->ySizeNode->getIntValue() : 600;
552       
553     // OK, PUI didn't want the event,
554     // so we can play with it.
555     if (x != m.x) {
556       int delta = x - m.x;
557       d->xAccelNode->setIntValue( delta );
558       for (unsigned int i = 0; i < mode.x_bindings[modifiers].size(); i++)
559         mode.x_bindings[modifiers][i]->fire(double(delta), double(xsize));
560     }
561     if (y != m.y) {
562       int delta = y - m.y;
563       d->yAccelNode->setIntValue( -delta );
564       for (unsigned int i = 0; i < mode.y_bindings[modifiers].size(); i++)
565         mode.y_bindings[modifiers][i]->fire(double(delta), double(ysize));
566     }
567   }
568   
569   // Constrain the mouse if requested
570   if (mode.constrained) {
571     d->constrainMouse(x, y);
572   }
573 }
574
575 void FGMouseInput::doMouseMotion (int x, int y, const osgGA::GUIEventAdapter* ea)
576 {
577   mouse &m = d->mice[0];
578
579   if (m.current_mode < 0 || m.current_mode >= m.nModes) {
580       m.x = x;
581       m.y = y;
582       return;
583   }
584
585   m.timeSinceLastMove.stamp();
586   FGMouseCursor::instance()->mouseMoved();
587
588   processMotion(x, y, ea);
589     
590   m.x = x;
591   m.y = y;
592   d->mouseXNode->setIntValue(x);
593   d->mouseYNode->setIntValue(y);
594 }
595
596
597