]> git.mxchange.org Git - flightgear.git/blob - src/Input/FGMouseInput.cxx
MouseInput changes to support hover.
[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 );
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 )
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);
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     {
149         tooltipTimeoutDone = false;
150     }
151   
152     void centerMouseCursor(mouse& m)
153     {    
154       // center the cursor
155       m.x = (xSizeNode ? xSizeNode->getIntValue() : 800) / 2;
156       m.y = (ySizeNode ? ySizeNode->getIntValue() : 600) / 2;
157       fgWarpMouse(m.x, m.y);
158       haveWarped = true;
159     }
160     
161     void doHoverPick(const osg::Vec2d& windowPos)
162     {
163         std::vector<SGSceneryPick> pickList;
164         SGPickCallback::Priority priority = SGPickCallback::PriorityScenery;
165         
166         if (globals->get_renderer()->pick(pickList, windowPos)) {
167             
168             std::vector<SGSceneryPick>::const_iterator i;
169             for (i = pickList.begin(); i != pickList.end(); ++i) {
170                 if (i->callback->hover(windowPos, i->info)) {
171                     return;
172                 }
173                 
174             // if the callback is of higher prioirty (lower enum index),
175             // record that.
176                 if (i->callback->getPriority() < priority) {
177                     priority = i->callback->getPriority();
178                 }
179             }
180         } // of have valid pick
181                 
182         if (priority < SGPickCallback::PriorityScenery) {
183             FGMouseCursor::instance()->setCursor(FGMouseCursor::CURSOR_HAND);
184         } else {
185             // restore normal cursor
186             FGMouseCursor::instance()->setCursor(FGMouseCursor::CURSOR_ARROW);
187         }
188         
189         updateHover();
190     }
191     
192     void updateHover()
193     {
194         SGPropertyNode_ptr args(new SGPropertyNode);
195         globals->get_commands()->execute("update-hover", args);
196     }
197
198     
199     ActivePickCallbacks activePickCallbacks;
200
201     mouse mice[MAX_MICE];
202     
203     bool haveWarped;
204     bool tooltipTimeoutDone;
205   
206     SGPropertyNode_ptr xSizeNode;
207     SGPropertyNode_ptr ySizeNode;
208     SGPropertyNode_ptr xAccelNode;
209     SGPropertyNode_ptr yAccelNode;
210     SGPropertyNode_ptr hideCursorNode;
211     SGPropertyNode_ptr cursorTimeoutNode;
212     SGPropertyNode_ptr rightButtonModeCycleNode;
213     SGPropertyNode_ptr tooltipShowDelayNode;
214     SGPropertyNode_ptr clickTriggersTooltipNode;
215 };
216
217
218 ////////////////////////////////////////////////////////////////////////
219 // The Mouse Input Implementation
220 ////////////////////////////////////////////////////////////////////////
221
222 static FGMouseInput* global_mouseInput = NULL;
223
224 static void mouseClickHandler(int button, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
225 {
226     if(global_mouseInput)
227         global_mouseInput->doMouseClick(button, updown, x, y, mainWindow, ea);
228 }
229
230 static void mouseMotionHandler(int x, int y, const osgGA::GUIEventAdapter* ea)
231 {
232     if (global_mouseInput != 0)
233         global_mouseInput->doMouseMotion(x, y, ea);
234 }
235
236
237
238 FGMouseInput::FGMouseInput() :
239   d(new FGMouseInputPrivate)
240 {
241     global_mouseInput = this;
242 }
243
244 FGMouseInput::~FGMouseInput()
245 {
246     global_mouseInput = NULL;
247 }
248
249 void FGMouseInput::init()
250 {
251   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse bindings");
252   string module = "";
253
254   SGPropertyNode * mouse_nodes = fgGetNode("/input/mice");
255   if (mouse_nodes == 0) {
256     SG_LOG(SG_INPUT, SG_WARN, "No mouse bindings (/input/mice)!!");
257     mouse_nodes = fgGetNode("/input/mice", true);
258   }
259
260   int j;
261   for (int i = 0; i < MAX_MICE; i++) {
262     SGPropertyNode * mouse_node = mouse_nodes->getChild("mouse", i, true);
263     mouse &m = d->mice[i];
264
265                                 // Grab node pointers
266     std::ostringstream buf;
267     buf <<  "/devices/status/mice/mouse[" << i << "]/mode";
268     m.mode_node = fgGetNode(buf.str().c_str());
269     if (m.mode_node == NULL) {
270       m.mode_node = fgGetNode(buf.str().c_str(), true);
271       m.mode_node->setIntValue(0);
272     }
273     for (j = 0; j < MAX_MOUSE_BUTTONS; j++) {
274       buf.seekp(ios_base::beg);
275       buf << "/devices/status/mice/mouse["<< i << "]/button[" << j << "]";
276       m.mouse_button_nodes[j] = fgGetNode(buf.str().c_str(), true);
277       m.mouse_button_nodes[j]->setBoolValue(false);
278     }
279
280                                 // Read all the modes
281     m.nModes = mouse_node->getIntValue("mode-count", 1);
282     m.modes = new mouse_mode[m.nModes];
283
284     for (int j = 0; j < m.nModes; j++) {
285       int k;
286       SGPropertyNode * mode_node = mouse_node->getChild("mode", j, true);
287
288     // Read the mouse cursor for this mode
289       m.modes[j].cursor = FGMouseCursor::cursorFromString(mode_node->getStringValue("cursor", "inherit"));
290         
291                                 // Read other properties for this mode
292       m.modes[j].constrained = mode_node->getBoolValue("constrained", false);
293       m.modes[j].pass_through = mode_node->getBoolValue("pass-through", false);
294
295                                 // Read the button bindings for this mode
296       m.modes[j].buttons = new FGButton[MAX_MOUSE_BUTTONS];
297       std::ostringstream buf;
298       for (k = 0; k < MAX_MOUSE_BUTTONS; k++) {
299         buf.seekp(ios_base::beg);
300         buf << "mouse button " << k;
301         m.modes[j].buttons[k].init( mode_node->getChild("button", k), buf.str(), module );
302       }
303
304                                 // Read the axis bindings for this mode
305       read_bindings(mode_node->getChild("x-axis", 0, true), m.modes[j].x_bindings, KEYMOD_NONE, module );
306       read_bindings(mode_node->getChild("y-axis", 0, true), m.modes[j].y_bindings, KEYMOD_NONE, module );
307     }
308   }
309
310   fgRegisterMouseClickHandler(mouseClickHandler);
311   fgRegisterMouseMotionHandler(mouseMotionHandler);
312 }
313
314 void FGMouseInput::update ( double dt )
315 {
316   int cursorTimeoutMsec = d->cursorTimeoutNode->getDoubleValue() * 1000;
317   int tooltipDelayMsec = d->tooltipShowDelayNode->getIntValue();
318   
319   mouse &m = d->mice[0];
320   int mode =  m.mode_node->getIntValue();
321   if (mode != m.current_mode) {
322     // current mode has changed
323     m.current_mode = mode;
324     m.timeSinceLastMove.stamp();
325       
326     if (mode >= 0 && mode < m.nModes) {
327       FGMouseCursor::instance()->setCursor(m.modes[mode].cursor);
328       d->centerMouseCursor(m);
329     } else {
330       SG_LOG(SG_INPUT, SG_WARN, "Mouse mode " << mode << " out of range");
331       FGMouseCursor::instance()->setCursor(FGMouseCursor::CURSOR_ARROW);
332     }
333   }
334
335   if ( d->hideCursorNode == NULL || d->hideCursorNode->getBoolValue() ) {
336       // if delay is <= 0, disable tooltips
337       if ( !d->tooltipTimeoutDone &&
338            (tooltipDelayMsec > 0) &&
339            (m.timeSinceLastMove.elapsedMSec() > tooltipDelayMsec))
340       {
341           d->tooltipTimeoutDone = true;
342           SGPropertyNode_ptr arg(new SGPropertyNode);
343           globals->get_commands()->execute("tooltip-timeout", arg);
344       }
345     
346       if ( m.timeSinceLastMove.elapsedMSec() > cursorTimeoutMsec) {
347           FGMouseCursor::instance()->hideCursorUntilMouseMove();
348           m.timeSinceLastMove.stamp();
349       }
350   }
351     
352   d->activePickCallbacks.update( dt );
353 }
354
355 mouse::mouse ()
356   : x(-1),
357     y(-1),
358     nModes(1),
359     current_mode(0),
360     modes(NULL)
361 {
362 }
363
364 mouse::~mouse ()
365 {
366   delete [] modes;
367 }
368
369 mouse_mode::mouse_mode ()
370   : cursor(FGMouseCursor::CURSOR_ARROW),
371     constrained(false),
372     pass_through(false),
373     buttons(NULL)
374 {
375 }
376
377 mouse_mode::~mouse_mode ()
378 {
379                                 // FIXME: memory leak
380 //   for (int i = 0; i < KEYMOD_MAX; i++) {
381 //     int j;
382 //     for (j = 0; i < x_bindings[i].size(); j++)
383 //       delete bindings[i][j];
384 //     for (j = 0; j < y_bindings[i].size(); j++)
385 //       delete bindings[i][j];
386 //   }
387   if (buttons) {
388     delete [] buttons;
389   }
390 }
391
392 void FGMouseInput::doMouseClick (int b, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
393 {
394   int modifiers = fgGetKeyModifiers();
395
396   mouse &m = d->mice[0];
397   mouse_mode &mode = m.modes[m.current_mode];
398                                 // Let the property manager know.
399   if (b >= 0 && b < MAX_MOUSE_BUTTONS)
400     m.mouse_button_nodes[b]->setBoolValue(updown == MOUSE_BUTTON_DOWN);
401
402   if (!d->rightButtonModeCycleNode->getBoolValue() && (b == 2)) {
403     // in spring-loaded look mode, ignore right clicks entirely here
404     return;
405   }
406   
407   // Pass on to PUI and the panel if
408   // requested, and return if one of
409   // them consumes the event.
410
411   if (updown != MOUSE_BUTTON_DOWN) {
412     // Execute the mouse up event in any case, may be we should
413     // stop processing here?
414     while (!d->activePickCallbacks[b].empty()) {
415       d->activePickCallbacks[b].front()->buttonReleased();
416       d->activePickCallbacks[b].pop_front();
417     }
418   }
419
420   if (mode.pass_through) {
421     // remove once PUI uses standard picking mechanism
422     if (0 <= x && 0 <= y && puMouse(b, updown, x, y))
423       return;
424     else {
425       // pui didn't want the click event so compute a
426       // scenegraph intersection point corresponding to the mouse click
427       if (updown == MOUSE_BUTTON_DOWN) {
428         d->activePickCallbacks.init( b, ea );
429       }
430     }
431   }
432
433   // OK, PUI and the panel didn't want the click
434   if (b >= MAX_MOUSE_BUTTONS) {
435     SG_LOG(SG_INPUT, SG_ALERT, "Mouse button " << b
436            << " where only " << MAX_MOUSE_BUTTONS << " expected");
437     return;
438   }
439
440   m.modes[m.current_mode].buttons[b].update( modifiers, 0 != updown, x, y);
441   
442   if (d->clickTriggersTooltipNode->getBoolValue()) {
443     SGPropertyNode_ptr args(new SGPropertyNode);
444     args->setStringValue("reason", "click");
445     globals->get_commands()->execute("tooltip-timeout", args);
446     d->tooltipTimeoutDone = true;
447   }
448 }
449
450 void FGMouseInput::doMouseMotion (int x, int y, const osgGA::GUIEventAdapter* ea)
451 {
452   int modifiers = fgGetKeyModifiers();
453
454   int xsize = d->xSizeNode ? d->xSizeNode->getIntValue() : 800;
455   int ysize = d->ySizeNode ? d->ySizeNode->getIntValue() : 600;
456
457   mouse &m = d->mice[0];
458
459   if (m.current_mode < 0 || m.current_mode >= m.nModes) {
460       m.x = x;
461       m.y = y;
462       return;
463   }
464
465   if (!d->activePickCallbacks[0].empty()) {
466     SG_LOG(SG_GENERAL, SG_INFO, "mouse-motion, have active pick callback");
467     BOOST_FOREACH(SGPickCallback* cb, d->activePickCallbacks[0]) {
468       cb->mouseMoved(ea);
469     }
470     
471     m.x = x;
472     m.y = y;
473     return;
474   }
475   
476   m.timeSinceLastMove.stamp();
477   FGMouseCursor::instance()->mouseMoved();
478
479   int modeIndex = m.current_mode;
480   // are we in spring-loaded look mode?
481   if (!d->rightButtonModeCycleNode->getBoolValue()) {
482     if (m.mouse_button_nodes[2]->getBoolValue()) {
483       // right mouse is down, force look mode
484       modeIndex = 3;
485     }
486   }
487
488   if (modeIndex == 0) {
489     osg::Vec2d windowPos;
490     flightgear::eventToWindowCoords(ea, windowPos.x(), windowPos.y());
491     d->doHoverPick(windowPos);
492     // mouse has moved, so we may need to issue tooltip-timeout command
493     // again
494     d->tooltipTimeoutDone = false;
495   }
496
497   mouse_mode &mode = m.modes[modeIndex];
498
499     // Pass on to PUI if requested, and return
500     // if PUI consumed the event.
501   if (mode.pass_through && puMouse(x, y)) {
502       m.x = x;
503       m.y = y;
504       return;
505   }
506   
507   if (d->haveWarped)
508   {
509       // don't fire mouse-movement events at the first update after warping the mouse,
510       // just remember the new mouse position
511       d->haveWarped = false;
512   }
513   else
514   {
515       // OK, PUI didn't want the event,
516       // so we can play with it.
517       if (x != m.x) {
518         int delta = x - m.x;
519         d->xAccelNode->setIntValue( delta );
520         for (unsigned int i = 0; i < mode.x_bindings[modifiers].size(); i++)
521           mode.x_bindings[modifiers][i]->fire(double(delta), double(xsize));
522       }
523       if (y != m.y) {
524         int delta = y - m.y;
525         d->yAccelNode->setIntValue( -delta );
526         for (unsigned int i = 0; i < mode.y_bindings[modifiers].size(); i++)
527           mode.y_bindings[modifiers][i]->fire(double(delta), double(ysize));
528       }
529   }
530                                 // Constrain the mouse if requested
531   if (mode.constrained) {
532     int new_x=x,new_y=y;
533     
534     bool need_warp = false;
535     if (x <= (xsize * .25) || x >= (xsize * .75)) {
536       new_x = int(xsize * .5);
537       need_warp = true;
538     }
539
540     if (y <= (ysize * .25) || y >= (ysize * .75)) {
541       new_y = int(ysize * .5);
542       need_warp = true;
543     }
544
545     if (need_warp)
546     {
547       fgWarpMouse(new_x, new_y);
548       d->haveWarped = true;
549     }
550   }
551
552   if (m.x != x)
553       fgSetInt("/devices/status/mice/mouse/x", m.x = x);
554
555   if (m.y != y)
556       fgSetInt("/devices/status/mice/mouse/y", m.y = y);
557 }
558
559
560