]> git.mxchange.org Git - flightgear.git/blob - src/Input/FGMouseInput.cxx
Live cursor updating during pick-drags.
[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         FGMouseCursor::Cursor cur = FGMouseCursor::CURSOR_ARROW;
197         bool explicitCursor = false;
198         
199         if (globals->get_renderer()->pick(pickList, windowPos)) {
200             
201             std::vector<SGSceneryPick>::const_iterator i;
202             for (i = pickList.begin(); i != pickList.end(); ++i) {
203                 bool done = i->callback->hover(windowPos, i->info);
204                 std::string curName(i->callback->getCursor());
205                 if (!curName.empty()) {
206                     explicitCursor = true;
207                     cur = FGMouseCursor::cursorFromString(curName.c_str());
208                 }
209                 
210             // if the callback is of higher prioirty (lower enum index),
211             // record that.
212                 if (i->callback->getPriority() < priority) {
213                     priority = i->callback->getPriority();
214                 }
215                 
216                 if (done) {
217                     break;
218                 }
219             } // of picks iteration
220         } // of have valid pick
221       
222         
223         if (!explicitCursor && (priority == SGPickCallback::PriorityPanel)) {
224             cur = FGMouseCursor::CURSOR_HAND;
225         }
226         
227         FGMouseCursor::instance()->setCursor(cur);
228         updateHover();
229     }
230     
231     void doMouseMoveWithCallbacks(const osgGA::GUIEventAdapter* ea)
232     {
233         FGMouseCursor::Cursor cur = FGMouseCursor::CURSOR_CLOSED_HAND;
234         
235         BOOST_FOREACH(SGPickCallback* cb, activePickCallbacks[0]) {
236             cb->mouseMoved(ea);
237             std::string curName(cb->getCursor());
238             if (!curName.empty()) {
239                 cur = FGMouseCursor::cursorFromString(curName.c_str());
240             }
241         }
242
243         FGMouseCursor::instance()->setCursor(cur);
244     }
245     
246     void updateHover()
247     {
248         SGPropertyNode_ptr args(new SGPropertyNode);
249         globals->get_commands()->execute("update-hover", args);
250     }
251
252     
253     // implement the property-change-listener interfacee
254     virtual void valueChanged( SGPropertyNode * node )
255     {
256         if (node->getNameString() == "drag-sensitivity") {
257             SGKnobAnimation::setDragSensitivity(node->getDoubleValue());
258         } else if (node->getNameString() == "invert-mouse-wheel") {
259             SGKnobAnimation::setAlternateMouseWheelDirection(node->getBoolValue());
260         } else if (node->getNameString() == "hide-cursor") {
261             hideCursor = node->getBoolValue();
262         } else if (node->getNameString() == "cursor-timeout-sec") {
263             cursorTimeoutMsec = node->getDoubleValue() * 1000;
264         } else if (node->getNameString() == "tooltip-delay-msec") {
265             tooltipDelayMsec = node->getIntValue();
266         } else if (node->getNameString() == "right-button-mode-cycle-enabled") {
267             rightClickModeCycle = node->getBoolValue();
268         } else if (node->getNameString() == "click-shows-tooltip") {
269             clickTriggersTooltip = node->getBoolValue();
270
271         }
272     }
273     
274     ActivePickCallbacks activePickCallbacks;
275
276     mouse mice[MAX_MICE];
277     
278     bool hideCursor, haveWarped;
279     bool tooltipTimeoutDone;
280     bool clickTriggersTooltip;
281     int tooltipDelayMsec, cursorTimeoutMsec;
282     bool rightClickModeCycle;
283     
284     SGPropertyNode_ptr xSizeNode;
285     SGPropertyNode_ptr ySizeNode;
286     SGPropertyNode_ptr xAccelNode;
287     SGPropertyNode_ptr yAccelNode;
288     SGPropertyNode_ptr mouseXNode, mouseYNode;
289 };
290
291
292 ////////////////////////////////////////////////////////////////////////
293 // The Mouse Input Implementation
294 ////////////////////////////////////////////////////////////////////////
295
296 static FGMouseInput* global_mouseInput = NULL;
297
298 static void mouseClickHandler(int button, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
299 {
300     if(global_mouseInput)
301         global_mouseInput->doMouseClick(button, updown, x, y, mainWindow, ea);
302 }
303
304 static void mouseMotionHandler(int x, int y, const osgGA::GUIEventAdapter* ea)
305 {
306     if (global_mouseInput != 0)
307         global_mouseInput->doMouseMotion(x, y, ea);
308 }
309
310
311
312 FGMouseInput::FGMouseInput() :
313   d(new FGMouseInputPrivate)
314 {
315     global_mouseInput = this;
316 }
317
318 FGMouseInput::~FGMouseInput()
319 {
320     global_mouseInput = NULL;
321 }
322
323 void FGMouseInput::init()
324 {
325   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse bindings");
326   string module = "";
327
328   SGPropertyNode * mouse_nodes = fgGetNode("/input/mice");
329   if (mouse_nodes == 0) {
330     SG_LOG(SG_INPUT, SG_WARN, "No mouse bindings (/input/mice)!!");
331     mouse_nodes = fgGetNode("/input/mice", true);
332   }
333
334   int j;
335   for (int i = 0; i < MAX_MICE; i++) {
336     SGPropertyNode * mouse_node = mouse_nodes->getChild("mouse", i, true);
337     mouse &m = d->mice[i];
338
339                                 // Grab node pointers
340     std::ostringstream buf;
341     buf <<  "/devices/status/mice/mouse[" << i << "]/mode";
342     m.mode_node = fgGetNode(buf.str().c_str());
343     if (m.mode_node == NULL) {
344       m.mode_node = fgGetNode(buf.str().c_str(), true);
345       m.mode_node->setIntValue(0);
346     }
347     for (j = 0; j < MAX_MOUSE_BUTTONS; j++) {
348       buf.seekp(ios_base::beg);
349       buf << "/devices/status/mice/mouse["<< i << "]/button[" << j << "]";
350       m.mouse_button_nodes[j] = fgGetNode(buf.str().c_str(), true);
351       m.mouse_button_nodes[j]->setBoolValue(false);
352     }
353
354    // Read all the modes
355     m.nModes = mouse_node->getIntValue("mode-count", 1);
356     m.modes = new mouse_mode[m.nModes];
357
358     for (int j = 0; j < m.nModes; j++) {
359       int k;
360       SGPropertyNode * mode_node = mouse_node->getChild("mode", j, true);
361
362     // Read the mouse cursor for this mode
363       m.modes[j].cursor = FGMouseCursor::cursorFromString(mode_node->getStringValue("cursor", "inherit"));
364         
365       // Read other properties for this mode
366       m.modes[j].constrained = mode_node->getBoolValue("constrained", false);
367       m.modes[j].pass_through = mode_node->getBoolValue("pass-through", false);
368
369       // Read the button bindings for this mode
370       m.modes[j].buttons = new FGButton[MAX_MOUSE_BUTTONS];
371       std::ostringstream buf;
372       for (k = 0; k < MAX_MOUSE_BUTTONS; k++) {
373         buf.seekp(ios_base::beg);
374         buf << "mouse button " << k;
375         m.modes[j].buttons[k].init( mode_node->getChild("button", k), buf.str(), module );
376       }
377
378       // Read the axis bindings for this mode
379       read_bindings(mode_node->getChild("x-axis", 0, true), m.modes[j].x_bindings, KEYMOD_NONE, module );
380       read_bindings(mode_node->getChild("y-axis", 0, true), m.modes[j].y_bindings, KEYMOD_NONE, module );
381       
382       if (mode_node->hasChild("x-axis-ctrl")) {
383         read_bindings(mode_node->getChild("x-axis-ctrl"), m.modes[j].x_bindings, KEYMOD_CTRL, module );
384       }
385       
386       if (mode_node->hasChild("y-axis-ctrl")) {
387         read_bindings(mode_node->getChild("y-axis-ctrl"), m.modes[j].y_bindings, KEYMOD_CTRL, module );
388       }
389     } // of modes iteration
390   }
391
392   fgRegisterMouseClickHandler(mouseClickHandler);
393   fgRegisterMouseMotionHandler(mouseMotionHandler);
394 }
395
396 void FGMouseInput::update ( double dt )
397 {
398   mouse &m = d->mice[0];
399   int mode =  m.mode_node->getIntValue();
400   if (mode != m.current_mode) {
401     // current mode has changed
402     m.current_mode = mode;
403     m.timeSinceLastMove.stamp();
404       
405     if (mode >= 0 && mode < m.nModes) {
406       FGMouseCursor::instance()->setCursor(m.modes[mode].cursor);
407       d->centerMouseCursor(m);
408     } else {
409       SG_LOG(SG_INPUT, SG_WARN, "Mouse mode " << mode << " out of range");
410       FGMouseCursor::instance()->setCursor(FGMouseCursor::CURSOR_ARROW);
411     }
412   }
413
414   // if delay is <= 0, disable tooltips
415   if ( !d->tooltipTimeoutDone &&
416       (d->tooltipDelayMsec > 0) &&
417       (m.timeSinceLastMove.elapsedMSec() > d->tooltipDelayMsec))
418   {
419       d->tooltipTimeoutDone = true;
420       SGPropertyNode_ptr arg(new SGPropertyNode);
421       globals->get_commands()->execute("tooltip-timeout", arg);
422   }
423   
424   if ( d->hideCursor ) {
425       if ( m.timeSinceLastMove.elapsedMSec() > d->cursorTimeoutMsec) {
426           FGMouseCursor::instance()->hideCursorUntilMouseMove();
427           m.timeSinceLastMove.stamp();
428       }
429   }
430     
431   d->activePickCallbacks.update( dt, fgGetKeyModifiers() );
432 }
433
434 mouse::mouse ()
435   : x(-1),
436     y(-1),
437     nModes(1),
438     current_mode(0),
439     modes(NULL)
440 {
441 }
442
443 mouse::~mouse ()
444 {
445   delete [] modes;
446 }
447
448 mouse_mode::mouse_mode ()
449   : cursor(FGMouseCursor::CURSOR_ARROW),
450     constrained(false),
451     pass_through(false),
452     buttons(NULL)
453 {
454 }
455
456 mouse_mode::~mouse_mode ()
457 {
458                                 // FIXME: memory leak
459 //   for (int i = 0; i < KEYMOD_MAX; i++) {
460 //     int j;
461 //     for (j = 0; i < x_bindings[i].size(); j++)
462 //       delete bindings[i][j];
463 //     for (j = 0; j < y_bindings[i].size(); j++)
464 //       delete bindings[i][j];
465 //   }
466   if (buttons) {
467     delete [] buttons;
468   }
469 }
470
471 void FGMouseInput::doMouseClick (int b, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
472 {
473   int modifiers = fgGetKeyModifiers();
474
475   mouse &m = d->mice[0];
476   mouse_mode &mode = m.modes[m.current_mode];
477                                 // Let the property manager know.
478   if (b >= 0 && b < MAX_MOUSE_BUTTONS)
479     m.mouse_button_nodes[b]->setBoolValue(updown == MOUSE_BUTTON_DOWN);
480
481   if (!d->rightClickModeCycle && (b == 2)) {
482     // in spring-loaded look mode, ignore right clicks entirely here
483     return;
484   }
485   
486   // Pass on to PUI and the panel if
487   // requested, and return if one of
488   // them consumes the event.
489
490   if (updown != MOUSE_BUTTON_DOWN) {
491     // Execute the mouse up event in any case, may be we should
492     // stop processing here?
493     while (!d->activePickCallbacks[b].empty()) {
494       d->activePickCallbacks[b].front()->buttonReleased(ea->getModKeyMask());
495       d->activePickCallbacks[b].pop_front();
496     }
497   }
498
499   if (mode.pass_through) {
500     // remove once PUI uses standard picking mechanism
501     if (0 <= x && 0 <= y && puMouse(b, updown, x, y))
502       return; // pui handled it
503
504     // pui didn't want the click event so compute a
505     // scenegraph intersection point corresponding to the mouse click
506     if (updown == MOUSE_BUTTON_DOWN) {
507       d->activePickCallbacks.init( b, ea );
508         
509       if (d->clickTriggersTooltip) {
510             SGPropertyNode_ptr args(new SGPropertyNode);
511             args->setStringValue("reason", "click");
512             globals->get_commands()->execute("tooltip-timeout", args);
513             d->tooltipTimeoutDone = true;
514       }
515     } else {
516       // do a hover pick now, to fix up cursor
517       osg::Vec2d windowPos;
518       flightgear::eventToWindowCoords(ea, windowPos.x(), windowPos.y());
519       d->doHoverPick(windowPos);
520     } // mouse button was released
521   } // of pass-through mode
522
523   // OK, PUI and the panel didn't want the click
524   if (b >= MAX_MOUSE_BUTTONS) {
525     SG_LOG(SG_INPUT, SG_ALERT, "Mouse button " << b
526            << " where only " << MAX_MOUSE_BUTTONS << " expected");
527     return;
528   }
529
530   m.modes[m.current_mode].buttons[b].update( modifiers, 0 != updown, x, y);  
531 }
532
533 void FGMouseInput::processMotion(int x, int y, const osgGA::GUIEventAdapter* ea)
534 {
535   if (!d->activePickCallbacks[0].empty()) {
536     d->doMouseMoveWithCallbacks(ea);
537     return;
538   }
539   
540   mouse &m = d->mice[0];
541   int modeIndex = m.current_mode;
542   // are we in spring-loaded look mode?
543   if (!d->rightClickModeCycle) {
544     if (m.mouse_button_nodes[2]->getBoolValue()) {
545       // right mouse is down, force look mode
546       modeIndex = 3;
547     }
548   }
549
550   if (modeIndex == 0) {
551     osg::Vec2d windowPos;
552     flightgear::eventToWindowCoords(ea, windowPos.x(), windowPos.y());
553     d->doHoverPick(windowPos);
554     // mouse has moved, so we may need to issue tooltip-timeout command again
555     d->tooltipTimeoutDone = false;
556   }
557   
558   mouse_mode &mode = m.modes[modeIndex];
559   
560   // Pass on to PUI if requested, and return
561   // if PUI consumed the event.
562   if (mode.pass_through && puMouse(x, y)) {
563     return;
564   }
565
566   if (d->haveWarped)
567   {
568     // don't fire mouse-movement events at the first update after warping the mouse,
569     // just remember the new mouse position
570     d->haveWarped = false;
571   }
572   else
573   {
574     int modifiers = fgGetKeyModifiers();
575     int xsize = d->xSizeNode ? d->xSizeNode->getIntValue() : 800;
576     int ysize = d->ySizeNode ? d->ySizeNode->getIntValue() : 600;
577       
578     // OK, PUI didn't want the event,
579     // so we can play with it.
580     if (x != m.x) {
581       int delta = x - m.x;
582       d->xAccelNode->setIntValue( delta );
583       for (unsigned int i = 0; i < mode.x_bindings[modifiers].size(); i++)
584         mode.x_bindings[modifiers][i]->fire(double(delta), double(xsize));
585     }
586     if (y != m.y) {
587       int delta = y - m.y;
588       d->yAccelNode->setIntValue( -delta );
589       for (unsigned int i = 0; i < mode.y_bindings[modifiers].size(); i++)
590         mode.y_bindings[modifiers][i]->fire(double(delta), double(ysize));
591     }
592   }
593   
594   // Constrain the mouse if requested
595   if (mode.constrained) {
596     d->constrainMouse(x, y);
597   }
598 }
599
600 void FGMouseInput::doMouseMotion (int x, int y, const osgGA::GUIEventAdapter* ea)
601 {
602   mouse &m = d->mice[0];
603
604   if (m.current_mode < 0 || m.current_mode >= m.nModes) {
605       m.x = x;
606       m.y = y;
607       return;
608   }
609
610   m.timeSinceLastMove.stamp();
611   FGMouseCursor::instance()->mouseMoved();
612
613   processMotion(x, y, ea);
614     
615   m.x = x;
616   m.y = y;
617   d->mouseXNode->setIntValue(x);
618   d->mouseYNode->setIntValue(y);
619 }
620
621
622