]> git.mxchange.org Git - flightgear.git/blob - src/Input/FGMouseInput.cxx
Fix updating of mouse position props.
[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         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   }
336
337   fgRegisterMouseClickHandler(mouseClickHandler);
338   fgRegisterMouseMotionHandler(mouseMotionHandler);
339 }
340
341 void FGMouseInput::update ( double dt )
342 {
343   int cursorTimeoutMsec = d->cursorTimeoutNode->getDoubleValue() * 1000;
344   int tooltipDelayMsec = d->tooltipShowDelayNode->getIntValue();
345   
346   mouse &m = d->mice[0];
347   int mode =  m.mode_node->getIntValue();
348   if (mode != m.current_mode) {
349     // current mode has changed
350     m.current_mode = mode;
351     m.timeSinceLastMove.stamp();
352       
353     if (mode >= 0 && mode < m.nModes) {
354       FGMouseCursor::instance()->setCursor(m.modes[mode].cursor);
355       d->centerMouseCursor(m);
356     } else {
357       SG_LOG(SG_INPUT, SG_WARN, "Mouse mode " << mode << " out of range");
358       FGMouseCursor::instance()->setCursor(FGMouseCursor::CURSOR_ARROW);
359     }
360   }
361
362   if ( d->hideCursorNode == NULL || d->hideCursorNode->getBoolValue() ) {
363       // if delay is <= 0, disable tooltips
364       if ( !d->tooltipTimeoutDone &&
365            (tooltipDelayMsec > 0) &&
366            (m.timeSinceLastMove.elapsedMSec() > tooltipDelayMsec))
367       {
368           d->tooltipTimeoutDone = true;
369           SGPropertyNode_ptr arg(new SGPropertyNode);
370           globals->get_commands()->execute("tooltip-timeout", arg);
371       }
372     
373       if ( m.timeSinceLastMove.elapsedMSec() > cursorTimeoutMsec) {
374           FGMouseCursor::instance()->hideCursorUntilMouseMove();
375           m.timeSinceLastMove.stamp();
376       }
377   }
378     
379   d->activePickCallbacks.update( dt );
380 }
381
382 mouse::mouse ()
383   : x(-1),
384     y(-1),
385     nModes(1),
386     current_mode(0),
387     modes(NULL)
388 {
389 }
390
391 mouse::~mouse ()
392 {
393   delete [] modes;
394 }
395
396 mouse_mode::mouse_mode ()
397   : cursor(FGMouseCursor::CURSOR_ARROW),
398     constrained(false),
399     pass_through(false),
400     buttons(NULL)
401 {
402 }
403
404 mouse_mode::~mouse_mode ()
405 {
406                                 // FIXME: memory leak
407 //   for (int i = 0; i < KEYMOD_MAX; i++) {
408 //     int j;
409 //     for (j = 0; i < x_bindings[i].size(); j++)
410 //       delete bindings[i][j];
411 //     for (j = 0; j < y_bindings[i].size(); j++)
412 //       delete bindings[i][j];
413 //   }
414   if (buttons) {
415     delete [] buttons;
416   }
417 }
418
419 void FGMouseInput::doMouseClick (int b, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
420 {
421   int modifiers = fgGetKeyModifiers();
422
423   mouse &m = d->mice[0];
424   mouse_mode &mode = m.modes[m.current_mode];
425                                 // Let the property manager know.
426   if (b >= 0 && b < MAX_MOUSE_BUTTONS)
427     m.mouse_button_nodes[b]->setBoolValue(updown == MOUSE_BUTTON_DOWN);
428
429   if (!d->rightButtonModeCycleNode->getBoolValue() && (b == 2)) {
430     // in spring-loaded look mode, ignore right clicks entirely here
431     return;
432   }
433   
434   // Pass on to PUI and the panel if
435   // requested, and return if one of
436   // them consumes the event.
437
438   if (updown != MOUSE_BUTTON_DOWN) {
439     // Execute the mouse up event in any case, may be we should
440     // stop processing here?
441     while (!d->activePickCallbacks[b].empty()) {
442       d->activePickCallbacks[b].front()->buttonReleased();
443       d->activePickCallbacks[b].pop_front();
444     }
445   }
446
447   if (mode.pass_through) {
448     // remove once PUI uses standard picking mechanism
449     if (0 <= x && 0 <= y && puMouse(b, updown, x, y))
450       return;
451     else {
452       // pui didn't want the click event so compute a
453       // scenegraph intersection point corresponding to the mouse click
454       if (updown == MOUSE_BUTTON_DOWN) {
455         d->activePickCallbacks.init( b, ea );
456       }
457     }
458   }
459
460   // OK, PUI and the panel didn't want the click
461   if (b >= MAX_MOUSE_BUTTONS) {
462     SG_LOG(SG_INPUT, SG_ALERT, "Mouse button " << b
463            << " where only " << MAX_MOUSE_BUTTONS << " expected");
464     return;
465   }
466
467   m.modes[m.current_mode].buttons[b].update( modifiers, 0 != updown, x, y);
468   
469   if (d->clickTriggersTooltipNode->getBoolValue()) {
470     SGPropertyNode_ptr args(new SGPropertyNode);
471     args->setStringValue("reason", "click");
472     globals->get_commands()->execute("tooltip-timeout", args);
473     d->tooltipTimeoutDone = true;
474   }
475 }
476
477 void FGMouseInput::processMotion(int x, int y, const osgGA::GUIEventAdapter* ea)
478 {
479   if (!d->activePickCallbacks[0].empty()) {
480     //SG_LOG(SG_GENERAL, SG_INFO, "mouse-motion, have active pick callback");
481     BOOST_FOREACH(SGPickCallback* cb, d->activePickCallbacks[0]) {
482       cb->mouseMoved(ea);
483     }
484     return;
485   }
486   
487   mouse &m = d->mice[0];
488   int modeIndex = m.current_mode;
489   // are we in spring-loaded look mode?
490   if (!d->rightButtonModeCycleNode->getBoolValue()) {
491     if (m.mouse_button_nodes[2]->getBoolValue()) {
492       // right mouse is down, force look mode
493       modeIndex = 3;
494     }
495   }
496
497   if (modeIndex == 0) {
498     osg::Vec2d windowPos;
499     flightgear::eventToWindowCoords(ea, windowPos.x(), windowPos.y());
500     d->doHoverPick(windowPos);
501     // mouse has moved, so we may need to issue tooltip-timeout command again
502     d->tooltipTimeoutDone = false;
503   }
504   
505   mouse_mode &mode = m.modes[modeIndex];
506   
507   // Pass on to PUI if requested, and return
508   // if PUI consumed the event.
509   if (mode.pass_through && puMouse(x, y)) {
510     return;
511   }
512
513   if (d->haveWarped)
514   {
515     // don't fire mouse-movement events at the first update after warping the mouse,
516     // just remember the new mouse position
517     d->haveWarped = false;
518   }
519   else
520   {
521     int modifiers = fgGetKeyModifiers();
522     int xsize = d->xSizeNode ? d->xSizeNode->getIntValue() : 800;
523     int ysize = d->ySizeNode ? d->ySizeNode->getIntValue() : 600;
524       
525     // OK, PUI didn't want the event,
526     // so we can play with it.
527     if (x != m.x) {
528       int delta = x - m.x;
529       d->xAccelNode->setIntValue( delta );
530       for (unsigned int i = 0; i < mode.x_bindings[modifiers].size(); i++)
531         mode.x_bindings[modifiers][i]->fire(double(delta), double(xsize));
532     }
533     if (y != m.y) {
534       int delta = y - m.y;
535       d->yAccelNode->setIntValue( -delta );
536       for (unsigned int i = 0; i < mode.y_bindings[modifiers].size(); i++)
537         mode.y_bindings[modifiers][i]->fire(double(delta), double(ysize));
538     }
539   }
540   
541   // Constrain the mouse if requested
542   if (mode.constrained) {
543     d->constrainMouse(x, y);
544   }
545 }
546
547 void FGMouseInput::doMouseMotion (int x, int y, const osgGA::GUIEventAdapter* ea)
548 {
549   mouse &m = d->mice[0];
550
551   if (m.current_mode < 0 || m.current_mode >= m.nModes) {
552       m.x = x;
553       m.y = y;
554       return;
555   }
556
557   m.timeSinceLastMove.stamp();
558   FGMouseCursor::instance()->mouseMoved();
559
560   processMotion(x, y, ea);
561     
562   m.x = x;
563   m.y = y;
564   d->mouseXNode->setIntValue(x);
565   d->mouseYNode->setIntValue(y);
566 }
567
568
569