]> git.mxchange.org Git - flightgear.git/blob - src/Input/input.cxx
fdb13de5e5e828b81051838bd9bfdaf2bed09e9a
[flightgear.git] / src / Input / input.cxx
1 // input.cxx -- handle user input from various sources.
2 //
3 // Written by David Megginson, started May 2001.
4 //
5 // Copyright (C) 2001 David Megginson, david@megginson.com
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <config.h>
25 #endif
26
27 #ifdef HAVE_WINDOWS_H
28 #  include <windows.h>
29 #endif
30
31 #include <simgear/compiler.h>
32
33 #include <math.h>
34 #include <ctype.h>
35
36 #include STL_FSTREAM
37 #include STL_STRING
38 #include <vector>
39
40 #include <simgear/compiler.h>
41
42 #include <simgear/constants.h>
43 #include <simgear/debug/logstream.hxx>
44 #include <simgear/math/SGMath.hxx>
45 #include <simgear/props/props.hxx>
46 #include <simgear/scene/util/SGSceneUserData.hxx>
47
48 #include <Aircraft/aircraft.hxx>
49 #include <Autopilot/xmlauto.hxx>
50 #include <Cockpit/hud.hxx>
51 #include <Cockpit/panel.hxx>
52 #include <Cockpit/panel_io.hxx>
53 #include <GUI/gui.h>
54 #include <Model/panelnode.hxx>
55 #include <Scripting/NasalSys.hxx>
56
57 #include <Main/globals.hxx>
58 #include <Main/fg_props.hxx>
59
60 #include "input.hxx"
61
62 #include <Scenery/scenery.hxx>
63 #include <Main/renderer.hxx>
64
65 SG_USING_STD(ifstream);
66 SG_USING_STD(string);
67 SG_USING_STD(vector);
68
69 void mouseClickHandler(int button, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter*);
70 void mouseMotionHandler(int x, int y);
71 void keyHandler(int key, int keymod, int mousex, int mousey);
72
73 \f
74 ////////////////////////////////////////////////////////////////////////
75 // Local variables.
76 ////////////////////////////////////////////////////////////////////////
77
78 static FGInput * default_input = 0;
79
80 \f
81 ////////////////////////////////////////////////////////////////////////
82 // Local functions.
83 ////////////////////////////////////////////////////////////////////////
84
85 static bool
86 getModShift ()
87 {
88   return bool(fgGetKeyModifiers() & KEYMOD_SHIFT);
89 }
90
91 static bool
92 getModCtrl ()
93 {
94   return bool(fgGetKeyModifiers() & KEYMOD_CTRL);
95 }
96
97 static bool
98 getModAlt ()
99 {
100   return bool(fgGetKeyModifiers() & KEYMOD_ALT);
101 }
102
103 \f
104 ////////////////////////////////////////////////////////////////////////
105 // Implementation of FGInput.
106 ////////////////////////////////////////////////////////////////////////
107
108
109 FGInput::FGInput ()
110 {
111     if (default_input == 0)
112         default_input = this;
113 }
114
115 FGInput::~FGInput ()
116 {
117     if (default_input == this)
118         default_input = 0;
119 }
120
121 void
122 FGInput::init ()
123 {
124   _init_keyboard();
125   _init_joystick();
126   _init_mouse();
127
128   fgRegisterKeyHandler(keyHandler);
129   fgRegisterMouseClickHandler(mouseClickHandler);
130   fgRegisterMouseMotionHandler(mouseMotionHandler);
131 }
132
133 void
134 FGInput::reinit ()
135 {
136     init();
137 }
138
139 void
140 FGInput::postinit ()
141 {
142   _postinit_joystick();
143 }
144
145 void
146 FGInput::bind ()
147 {
148   fgTie("/devices/status/keyboard/shift", getModShift);
149   fgTie("/devices/status/keyboard/ctrl", getModCtrl);
150   fgTie("/devices/status/keyboard/alt", getModAlt);
151 }
152
153 void
154 FGInput::unbind ()
155 {
156   fgUntie("/devices/status/keyboard/shift");
157   fgUntie("/devices/status/keyboard/ctrl");
158   fgUntie("/devices/status/keyboard/alt");
159 }
160
161 void 
162 FGInput::update (double dt)
163 {
164   _update_keyboard();
165   _update_joystick(dt);
166   _update_mouse(dt);
167 }
168
169 void
170 FGInput::suspend ()
171 {
172     // NO-OP
173 }
174
175 void
176 FGInput::resume ()
177 {
178     // NO-OP
179 }
180
181 bool
182 FGInput::is_suspended () const
183 {
184     return false;
185 }
186
187 void
188 FGInput::makeDefault (bool status)
189 {
190     if (status)
191         default_input = this;
192     else if (default_input == this)
193         default_input = 0;
194 }
195
196 void
197 FGInput::doKey (int k, int modifiers, int x, int y)
198 {
199                                 // Sanity check.
200   if (k < 0 || k >= MAX_KEYS) {
201     SG_LOG(SG_INPUT, SG_WARN, "Key value " << k << " out of range");
202     return;
203   }
204
205   button &b = _key_bindings[k];
206
207                                 // Key pressed.
208   if (!(modifiers & KEYMOD_RELEASED)) {
209     SG_LOG( SG_INPUT, SG_DEBUG, "User pressed key " << k
210             << " with modifiers " << modifiers );
211     if (!b.last_state || b.is_repeatable) {
212       const binding_list_t &bindings = _find_key_bindings(k, modifiers);
213
214       for (unsigned int i = 0; i < bindings.size(); i++)
215         bindings[i]->fire();
216       b.last_state = 1;
217     }
218   }
219                                 // Key released.
220   else {
221     SG_LOG(SG_INPUT, SG_DEBUG, "User released key " << k
222            << " with modifiers " << modifiers);
223     if (b.last_state) {
224       const binding_list_t &bindings = _find_key_bindings(k, modifiers);
225       for (unsigned int i = 0; i < bindings.size(); i++)
226         bindings[i]->fire();
227       b.last_state = 0;
228     } else {
229       if (k >= 1 && k <= 26) {
230         if (_key_bindings[k + '@'].last_state)
231           doKey(k + '@', KEYMOD_RELEASED, x, y);
232         if (_key_bindings[k + '`'].last_state)
233           doKey(k + '`', KEYMOD_RELEASED, x, y);
234       } else if (k >= 'A' && k <= 'Z') {
235         if (_key_bindings[k - '@'].last_state)
236           doKey(k - '@', KEYMOD_RELEASED, x, y);
237         if (_key_bindings[tolower(k)].last_state)
238           doKey(tolower(k), KEYMOD_RELEASED, x, y);
239       } else if (k >= 'a' && k <= 'z') {
240         if (_key_bindings[k - '`'].last_state)
241           doKey(k - '`', KEYMOD_RELEASED, x, y);
242         if (_key_bindings[toupper(k)].last_state)
243           doKey(toupper(k), KEYMOD_RELEASED, x, y);
244       }
245     }
246   }
247 }
248
249 void
250 FGInput::doMouseClick (int b, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
251 {
252   int modifiers = fgGetKeyModifiers();
253
254   mouse &m = _mouse_bindings[0];
255   mouse_mode &mode = m.modes[m.current_mode];
256
257                                 // Let the property manager know.
258   if (b >= 0 && b < MAX_MOUSE_BUTTONS)
259     m.mouse_button_nodes[b]->setBoolValue(updown == MOUSE_BUTTON_DOWN);
260
261                                 // Pass on to PUI and the panel if
262                                 // requested, and return if one of
263                                 // them consumes the event.
264
265   if (updown != MOUSE_BUTTON_DOWN) {
266     // Execute the mouse up event in any case, may be we should
267     // stop processing here?
268     while (!_activePickCallbacks[b].empty()) {
269       _activePickCallbacks[b].front()->buttonReleased();
270       _activePickCallbacks[b].pop_front();
271     }
272   }
273
274   if (mode.pass_through) {
275     // The pu stuff seems to need that. May be it does opengl picking ...
276     fgMakeCurrent();
277     if (0 <= x && 0 <= y && puMouse(b, updown, x, y))
278       return;
279     else if (0 <= x && 0 <= y && (globals->get_current_panel() != 0) &&
280              globals->get_current_panel()->getVisibility() &&
281              globals->get_current_panel()->doMouseAction(b, updown, x, y))
282       return;
283     else if (0 <= x && 0 <= y && fgHandle3DPanelMouseEvent(b, updown, x, y))
284       return;
285     else {
286       // pui didn't want the click event so compute a
287       // scenegraph intersection point corresponding to the mouse click
288       if (updown == MOUSE_BUTTON_DOWN) {
289
290         // Get the list of hit callbacks. Take the first callback that
291         // accepts the mouse button press and ignore the rest of them
292         // That is they get sorted by distance and by scenegraph depth.
293         // The nearest one is the first one and the deepest
294         // (the most specialized one in the scenegraph) is the first.
295         std::vector<SGSceneryPick> pickList;
296         if (FGRenderer::pick(x, y, pickList, ea)) {
297           std::vector<SGSceneryPick>::const_iterator i;
298           for (i = pickList.begin(); i != pickList.end(); ++i) {
299             if (i->callback->buttonPressed(b, i->info)) {
300               _activePickCallbacks[b].push_back(i->callback);
301               return;
302             }
303           }
304         }
305       }
306     }
307   }
308
309   // OK, PUI and the panel didn't want the click
310   if (b >= MAX_MOUSE_BUTTONS) {
311     SG_LOG(SG_INPUT, SG_ALERT, "Mouse button " << b
312            << " where only " << MAX_MOUSE_BUTTONS << " expected");
313     return;
314   }
315
316   _update_button(m.modes[m.current_mode].buttons[b], modifiers, 0 != updown, x, y);
317 }
318
319 void
320 FGInput::doMouseMotion (int x, int y)
321 {
322   // Don't call fgGetKeyModifiers() here, until we are using a
323   // toolkit that supports getting the mods from outside a key
324   // callback.  Glut doesn't.
325   int modifiers = KEYMOD_NONE;
326
327   int xsize = fgGetInt("/sim/startup/xsize", 800);
328   int ysize = fgGetInt("/sim/startup/ysize", 600);
329
330   mouse &m = _mouse_bindings[0];
331
332   if (m.current_mode < 0 || m.current_mode >= m.nModes) {
333       m.x = x;
334       m.y = y;
335       return;
336   }
337   mouse_mode &mode = m.modes[m.current_mode];
338
339                                 // Pass on to PUI if requested, and return
340                                 // if PUI consumed the event.
341   if (mode.pass_through && puMouse(x, y)) {
342       m.x = x;
343       m.y = y;
344       return;
345   }
346
347                                 // OK, PUI didn't want the event,
348                                 // so we can play with it.
349   if (x != m.x) {
350     int delta = x - m.x;
351     for (unsigned int i = 0; i < mode.x_bindings[modifiers].size(); i++)
352       mode.x_bindings[modifiers][i]->fire(double(delta), double(xsize));
353   }
354   if (y != m.y) {
355     int delta = y - m.y;
356     for (unsigned int i = 0; i < mode.y_bindings[modifiers].size(); i++)
357       mode.y_bindings[modifiers][i]->fire(double(delta), double(ysize));
358   }
359
360                                 // Constrain the mouse if requested
361   if (mode.constrained) {
362     bool need_warp = false;
363     if (x <= (xsize * .25) || x >= (xsize * .75)) {
364       x = int(xsize * .5);
365       need_warp = true;
366     }
367
368     if (y <= (ysize * .25) || y >= (ysize * .75)) {
369       y = int(ysize * .5);
370       need_warp = true;
371     }
372
373     if (need_warp)
374       fgWarpMouse(x, y);
375   }
376
377   if (m.x != x)
378       fgSetInt("/devices/status/mice/mouse/x", m.x = x);
379
380   if (m.y != y)
381       fgSetInt("/devices/status/mice/mouse/y", m.y = y);
382 }
383
384 void
385 FGInput::_init_keyboard ()
386 {
387   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing key bindings");
388   _module[0] = 0;
389   SGPropertyNode * key_nodes = fgGetNode("/input/keyboard");
390   if (key_nodes == 0) {
391     SG_LOG(SG_INPUT, SG_WARN, "No key bindings (/input/keyboard)!!");
392     key_nodes = fgGetNode("/input/keyboard", true);
393   }
394   
395   vector<SGPropertyNode_ptr> keys = key_nodes->getChildren("key");
396   for (unsigned int i = 0; i < keys.size(); i++) {
397     int index = keys[i]->getIndex();
398     SG_LOG(SG_INPUT, SG_DEBUG, "Binding key " << index);
399
400     _key_bindings[index].bindings->clear();
401     _key_bindings[index].is_repeatable = keys[i]->getBoolValue("repeatable");
402     _key_bindings[index].last_state = 0;
403     _read_bindings(keys[i], _key_bindings[index].bindings, KEYMOD_NONE);
404   }
405 }
406
407
408 void
409 FGInput::_scan_joystick_dir(SGPath *path, SGPropertyNode* node, int *index)
410 {
411   ulDir *dir = ulOpenDir(path->c_str());
412   if (dir) {
413     ulDirEnt* dent;
414     while ((dent = ulReadDir(dir)) != 0) {
415       if (dent->d_name[0] == '.')
416         continue;
417
418       SGPath p(path->str());
419       p.append(dent->d_name);
420       _scan_joystick_dir(&p, node, index);
421     }
422     ulCloseDir(dir);
423
424   } else if (path->extension() == "xml") {
425     SG_LOG(SG_INPUT, SG_DEBUG, "Reading joystick file " << path->str());
426     SGPropertyNode *n = node->getChild("js-named", (*index)++, true);
427     readProperties(path->str(), n);
428     n->setStringValue("source", path->c_str());
429   }
430 }
431
432
433 void
434 FGInput::_init_joystick ()
435 {
436   jsInit();
437                                 // TODO: zero the old bindings first.
438   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing joystick bindings");
439   SGPropertyNode * js_nodes = fgGetNode("/input/joysticks", true);
440
441   // read all joystick xml files into /input/joysticks/js_named[1000++]
442   SGPath path(globals->get_fg_root());
443   path.append("Input/Joysticks");
444   int js_named_index = 1000;
445   _scan_joystick_dir(&path, js_nodes, &js_named_index);
446
447   // build name->node map with each <name> (reverse order)
448   map<string, SGPropertyNode_ptr> jsmap;
449   vector<SGPropertyNode_ptr> js_named = js_nodes->getChildren("js-named");
450
451   for (int k = (int)js_named.size() - 1; k >= 0; k--) {
452     SGPropertyNode *n = js_named[k];
453     vector<SGPropertyNode_ptr> names = n->getChildren("name");
454     if (names.size() && (n->getChildren("axis").size() || n->getChildren("button").size()))
455       for (unsigned int j = 0; j < names.size(); j++)
456         jsmap[names[j]->getStringValue()] = n;
457   }
458
459   // set up js[] nodes
460   for (int i = 0; i < MAX_JOYSTICKS; i++) {
461     jsJoystick * js = new jsJoystick(i);
462     _joystick_bindings[i].js = js;
463
464     if (js->notWorking()) {
465       SG_LOG(SG_INPUT, SG_DEBUG, "Joystick " << i << " not found");
466       continue;
467     }
468
469     const char * name = js->getName();
470     SGPropertyNode_ptr js_node = js_nodes->getChild("js", i);
471
472     if (js_node) {
473       SG_LOG(SG_INPUT, SG_INFO, "Using existing bindings for joystick " << i);
474
475     } else {
476       SG_LOG(SG_INPUT, SG_INFO, "Looking for bindings for joystick \"" << name << '"');
477       SGPropertyNode_ptr named;
478
479       if ((named = jsmap[name])) {
480         string source = named->getStringValue("source", "user defined");
481         SG_LOG(SG_INPUT, SG_INFO, "... found joystick: " << source);
482
483       } else if ((named = jsmap["default"])) {
484         string source = named->getStringValue("source", "user defined");
485         SG_LOG(SG_INPUT, SG_INFO, "No config found for joystick \"" << name
486             << "\"\nUsing default: \"" << source << '"');
487
488       } else {
489         throw sg_throwable(string("No joystick configuration file with "
490             "<name>default</name> entry found!"));
491       }
492
493       js_node = js_nodes->getChild("js", i, true);
494       copyProperties(named, js_node);
495       js_node->setStringValue("id", name);
496     }
497   }
498
499   // get rid of unused config nodes
500   js_nodes->removeChildren("js-named", false);
501 }
502
503
504 void
505 FGInput::_postinit_joystick()
506 {
507   FGNasalSys *nasalsys = (FGNasalSys *)globals->get_subsystem("nasal");
508   SGPropertyNode *js_nodes = fgGetNode("/input/joysticks");
509
510   for (int i = 0; i < MAX_JOYSTICKS; i++) {
511     SGPropertyNode_ptr js_node = js_nodes->getChild("js", i);
512     jsJoystick *js = _joystick_bindings[i].js;
513     if (!js_node || js->notWorking())
514       continue;
515
516 #ifdef WIN32
517     JOYCAPS jsCaps ;
518     joyGetDevCaps( i, &jsCaps, sizeof(jsCaps) );
519     unsigned int nbuttons = jsCaps.wNumButtons;
520     if (nbuttons > MAX_JOYSTICK_BUTTONS) nbuttons = MAX_JOYSTICK_BUTTONS;
521 #else
522     unsigned int nbuttons = MAX_JOYSTICK_BUTTONS;
523 #endif
524
525     int naxes = js->getNumAxes();
526     if (naxes > MAX_JOYSTICK_AXES) naxes = MAX_JOYSTICK_AXES;
527     _joystick_bindings[i].naxes = naxes;
528     _joystick_bindings[i].nbuttons = nbuttons;
529
530     SG_LOG(SG_INPUT, SG_DEBUG, "Initializing joystick " << i);
531
532                                 // Set up range arrays
533     float minRange[MAX_JOYSTICK_AXES];
534     float maxRange[MAX_JOYSTICK_AXES];
535     float center[MAX_JOYSTICK_AXES];
536
537                                 // Initialize with default values
538     js->getMinRange(minRange);
539     js->getMaxRange(maxRange);
540     js->getCenter(center);
541
542                                 // Allocate axes and buttons
543     _joystick_bindings[i].axes = new axis[naxes];
544     _joystick_bindings[i].buttons = new button[nbuttons];
545
546     //
547     // Initialize nasal groups.
548     //
549     string init;
550     init = "this=\"" + string(js_node->getPath()) + "\"";
551     sprintf(_module, "__js%d", i);
552     nasalsys->createModule(_module, _module, init.c_str(), init.size());
553
554     vector<SGPropertyNode_ptr> nasal = js_node->getChildren("nasal");
555     unsigned int j;
556     for (j = 0; j < nasal.size(); j++) {
557       nasal[j]->setStringValue("module", _module);
558       nasalsys->handleCommand(nasal[j]);
559     }
560
561     //
562     // Initialize the axes.
563     //
564     vector<SGPropertyNode_ptr> axes = js_node->getChildren("axis");
565     size_t nb_axes = axes.size();
566     for (j = 0; j < nb_axes; j++ ) {
567       const SGPropertyNode * axis_node = axes[j];
568       const SGPropertyNode * num_node = axis_node->getChild("number");
569       int n_axis = axis_node->getIndex();
570       if (num_node != 0) {
571           n_axis = num_node->getIntValue(TGT_PLATFORM, -1);
572
573           // Silently ignore platforms that are not specified within the
574           // <number></number> section
575           if (n_axis < 0)
576              continue;
577       }
578
579       if (n_axis >= naxes) {
580           SG_LOG(SG_INPUT, SG_DEBUG, "Dropping bindings for axis " << n_axis);
581           continue;
582       }
583       axis &a = _joystick_bindings[i].axes[n_axis];
584
585       js->setDeadBand(n_axis, axis_node->getDoubleValue("dead-band", 0.0));
586
587       a.tolerance = axis_node->getDoubleValue("tolerance", 0.002);
588       minRange[n_axis] = axis_node->getDoubleValue("min-range", minRange[n_axis]);
589       maxRange[n_axis] = axis_node->getDoubleValue("max-range", maxRange[n_axis]);
590       center[n_axis] = axis_node->getDoubleValue("center", center[n_axis]);
591
592       _read_bindings(axis_node, a.bindings, KEYMOD_NONE);
593
594       // Initialize the virtual axis buttons.
595       _init_button(axis_node->getChild("low"), a.low, "low");
596       a.low_threshold = axis_node->getDoubleValue("low-threshold", -0.9);
597
598       _init_button(axis_node->getChild("high"), a.high, "high");
599       a.high_threshold = axis_node->getDoubleValue("high-threshold", 0.9);
600       a.interval_sec = axis_node->getDoubleValue("interval-sec",0.0);
601       a.last_dt = 0.0;
602     }
603
604     //
605     // Initialize the buttons.
606     //
607     vector<SGPropertyNode_ptr> buttons = js_node->getChildren("button");
608     char buf[32];
609     for (j = 0; j < buttons.size() && j < nbuttons; j++) {
610       const SGPropertyNode * button_node = buttons[j];
611       const SGPropertyNode * num_node = button_node->getChild("number");
612       size_t n_but = button_node->getIndex();
613       if (num_node != 0) {
614           n_but = num_node->getIntValue(TGT_PLATFORM,n_but);
615       }
616
617       if (n_but >= nbuttons) {
618           SG_LOG(SG_INPUT, SG_DEBUG, "Dropping bindings for button " << n_but);
619           continue;
620       }
621
622       sprintf(buf, "%d", n_but);
623       SG_LOG(SG_INPUT, SG_DEBUG, "Initializing button " << n_but);
624       _init_button(button_node,
625                    _joystick_bindings[i].buttons[n_but],
626                    buf);
627
628       // get interval-sec property
629       button &b = _joystick_bindings[i].buttons[n_but];
630       if (button_node != 0) {
631         b.interval_sec = button_node->getDoubleValue("interval-sec",0.0);
632         b.last_dt = 0.0;
633       }
634     }
635
636     js->setMinRange(minRange);
637     js->setMaxRange(maxRange);
638     js->setCenter(center);
639   }
640 }
641
642
643 // 
644 // Map of all known cursor names
645 // This used to contain all the Glut cursors, but those are
646 // not defined by other toolkits.  It now supports only the cursor
647 // images we actually use, in the interest of portability.  Someday,
648 // it would be cool to write an OpenGL cursor renderer, with the
649 // cursors defined as textures referenced in the property tree.  This
650 // list could then be eliminated. -Andy
651 //
652 static struct {
653   const char * name;
654   int cursor;
655 } mouse_cursor_map[] = {
656   { "none", MOUSE_CURSOR_NONE },
657   { "inherit", MOUSE_CURSOR_POINTER },
658   { "wait", MOUSE_CURSOR_WAIT },
659   { "crosshair", MOUSE_CURSOR_CROSSHAIR },
660   { "left-right", MOUSE_CURSOR_LEFTRIGHT },
661   { 0, 0 }
662 };
663
664 void
665 FGInput::_init_mouse ()
666 {
667   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse bindings");
668   _module[0] = 0;
669
670   SGPropertyNode * mouse_nodes = fgGetNode("/input/mice");
671   if (mouse_nodes == 0) {
672     SG_LOG(SG_INPUT, SG_WARN, "No mouse bindings (/input/mice)!!");
673     mouse_nodes = fgGetNode("/input/mice", true);
674   }
675
676   int j;
677   for (int i = 0; i < MAX_MICE; i++) {
678     SGPropertyNode * mouse_node = mouse_nodes->getChild("mouse", i, true);
679     mouse &m = _mouse_bindings[i];
680
681                                 // Grab node pointers
682     char buf[64];
683     sprintf(buf, "/devices/status/mice/mouse[%d]/mode", i);
684     m.mode_node = fgGetNode(buf);
685     if (m.mode_node == NULL) {
686       m.mode_node = fgGetNode(buf, true);
687       m.mode_node->setIntValue(0);
688     }
689     for (j = 0; j < MAX_MOUSE_BUTTONS; j++) {
690       sprintf(buf, "/devices/status/mice/mouse[%d]/button[%d]", i, j);
691       m.mouse_button_nodes[j] = fgGetNode(buf, true);
692       m.mouse_button_nodes[j]->setBoolValue(false);
693     }
694
695                                 // Read all the modes
696     m.nModes = mouse_node->getIntValue("mode-count", 1);
697     m.modes = new mouse_mode[m.nModes];
698
699     for (int j = 0; j < m.nModes; j++) {
700       int k;
701
702                                 // Read the mouse cursor for this mode
703       SGPropertyNode * mode_node = mouse_node->getChild("mode", j, true);
704       const char * cursor_name =
705         mode_node->getStringValue("cursor", "inherit");
706       m.modes[j].cursor = MOUSE_CURSOR_POINTER;
707       for (k = 0; mouse_cursor_map[k].name != 0; k++) {
708         if (!strcmp(mouse_cursor_map[k].name, cursor_name)) {
709           m.modes[j].cursor = mouse_cursor_map[k].cursor;
710           break;
711         }
712       }
713
714                                 // Read other properties for this mode
715       m.modes[j].constrained = mode_node->getBoolValue("constrained", false);
716       m.modes[j].pass_through = mode_node->getBoolValue("pass-through", false);
717
718                                 // Read the button bindings for this mode
719       m.modes[j].buttons = new button[MAX_MOUSE_BUTTONS];
720       char buf[32];
721       for (k = 0; k < MAX_MOUSE_BUTTONS; k++) {
722         sprintf(buf, "mouse button %d", k);
723         SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse button " << k);
724         _init_button(mode_node->getChild("button", k),
725                      m.modes[j].buttons[k],
726                      buf);
727       }
728
729                                 // Read the axis bindings for this mode
730       _read_bindings(mode_node->getChild("x-axis", 0, true),
731                      m.modes[j].x_bindings,
732                      KEYMOD_NONE);
733       _read_bindings(mode_node->getChild("y-axis", 0, true),
734                      m.modes[j].y_bindings,
735                      KEYMOD_NONE);
736     }
737   }
738 }
739
740
741 void
742 FGInput::_init_button (const SGPropertyNode * node,
743                        button &b,
744                        const string name)
745 {       
746   if (node == 0) {
747     SG_LOG(SG_INPUT, SG_DEBUG, "No bindings for button " << name);
748   } else {
749     b.is_repeatable = node->getBoolValue("repeatable", b.is_repeatable);
750     
751                 // Get the bindings for the button
752     _read_bindings(node, b.bindings, KEYMOD_NONE);
753   }
754 }
755
756
757 void
758 FGInput::_update_keyboard ()
759 {
760   // no-op
761 }
762
763
764 void
765 FGInput::_update_joystick (double dt)
766 {
767   int modifiers = KEYMOD_NONE;  // FIXME: any way to get the real ones?
768   int buttons;
769   // float js_val, diff;
770   float axis_values[MAX_JOYSTICK_AXES];
771
772   int i;
773   int j;
774
775   for ( i = 0; i < MAX_JOYSTICKS; i++) {
776
777     jsJoystick * js = _joystick_bindings[i].js;
778     if (js == 0 || js->notWorking())
779       continue;
780
781     js->read(&buttons, axis_values);
782
783                                 // Fire bindings for the axes.
784     for ( j = 0; j < _joystick_bindings[i].naxes; j++) {
785       axis &a = _joystick_bindings[i].axes[j];
786       
787                                 // Do nothing if the axis position
788                                 // is unchanged; only a change in
789                                 // position fires the bindings.
790       if (fabs(axis_values[j] - a.last_value) > a.tolerance) {
791 //      SG_LOG(SG_INPUT, SG_DEBUG, "Axis " << j << " has moved");
792         a.last_value = axis_values[j];
793 //      SG_LOG(SG_INPUT, SG_DEBUG, "There are "
794 //             << a.bindings[modifiers].size() << " bindings");
795         for (unsigned int k = 0; k < a.bindings[modifiers].size(); k++)
796           a.bindings[modifiers][k]->fire(axis_values[j]);
797       }
798      
799                                 // do we have to emulate axis buttons?
800       a.last_dt += dt;
801       if(a.last_dt >= a.interval_sec) {
802         if (a.low.bindings[modifiers].size())
803           _update_button(_joystick_bindings[i].axes[j].low,
804                          modifiers,
805                          axis_values[j] < a.low_threshold,
806                          -1, -1);
807       
808         if (a.high.bindings[modifiers].size())
809           _update_button(_joystick_bindings[i].axes[j].high,
810                          modifiers,
811                          axis_values[j] > a.high_threshold,
812                          -1, -1);
813          a.last_dt -= a.interval_sec;
814       }
815     }
816
817                                 // Fire bindings for the buttons.
818     for (j = 0; j < _joystick_bindings[i].nbuttons; j++) {
819       button &b = _joystick_bindings[i].buttons[j];
820       b.last_dt += dt;
821       if(b.last_dt >= b.interval_sec) {
822         _update_button(_joystick_bindings[i].buttons[j],
823                        modifiers,
824                        (buttons & (1 << j)) > 0,
825                        -1, -1);
826         b.last_dt -= b.interval_sec;
827       }
828     }
829   }
830 }
831
832 void
833 FGInput::_update_mouse ( double dt )
834 {
835   mouse &m = _mouse_bindings[0];
836   int mode =  m.mode_node->getIntValue();
837   if (mode != m.current_mode) {
838     m.current_mode = mode;
839     m.timeout = fgGetDouble( "/sim/mouse/cursor-timeout-sec", 10.0 );
840     if (mode >= 0 && mode < m.nModes) {
841       fgSetMouseCursor(m.modes[mode].cursor);
842       m.x = fgGetInt("/sim/startup/xsize", 800) / 2;
843       m.y = fgGetInt("/sim/startup/ysize", 600) / 2;
844       fgWarpMouse(m.x, m.y);
845     } else {
846       SG_LOG(SG_INPUT, SG_DEBUG, "Mouse mode " << mode << " out of range");
847       fgSetMouseCursor(MOUSE_CURSOR_POINTER);
848     }
849   }
850
851   if ( fgGetBool( "/sim/mouse/hide-cursor", true ) ) {
852       if ( m.x != m.save_x || m.y != m.save_y ) {
853           m.timeout = fgGetDouble( "/sim/mouse/cursor-timeout-sec", 10.0 );
854           fgSetMouseCursor(m.modes[mode].cursor);
855       } else {
856           m.timeout -= dt;
857           if ( m.timeout <= 0.0 ) {
858               fgSetMouseCursor(MOUSE_CURSOR_NONE);
859               m.timeout = 0.0;
860           }
861       }
862       m.save_x = m.x;
863       m.save_y = m.y;
864   }
865
866   // handle repeatable mouse press events
867   std::map<int, std::list<SGSharedPtr<SGPickCallback> > >::iterator mi;
868   for (mi = _activePickCallbacks.begin();
869        mi != _activePickCallbacks.end(); ++mi) {
870     std::list<SGSharedPtr<SGPickCallback> >::iterator li;
871     for (li = mi->second.begin(); li != mi->second.end(); ++li) {
872       (*li)->update(dt);
873     }
874   }
875 }
876
877 void
878 FGInput::_update_button (button &b, int modifiers, bool pressed,
879                          int x, int y)
880 {
881   if (pressed) {
882                                 // The press event may be repeated.
883     if (!b.last_state || b.is_repeatable) {
884       SG_LOG( SG_INPUT, SG_DEBUG, "Button has been pressed" );
885       for (unsigned int k = 0; k < b.bindings[modifiers].size(); k++) {
886         b.bindings[modifiers][k]->fire(x, y);
887       }
888     }
889   } else {
890                                 // The release event is never repeated.
891     if (b.last_state) {
892       SG_LOG( SG_INPUT, SG_DEBUG, "Button has been released" );
893       for (unsigned int k = 0; k < b.bindings[modifiers|KEYMOD_RELEASED].size(); k++)
894         b.bindings[modifiers|KEYMOD_RELEASED][k]->fire(x, y);
895     }
896   }
897           
898   b.last_state = pressed;
899 }  
900
901
902 void
903 FGInput::_read_bindings (const SGPropertyNode * node, 
904                          binding_list_t * binding_list,
905                          int modifiers)
906 {
907   SG_LOG(SG_INPUT, SG_DEBUG, "Reading all bindings");
908   vector<SGPropertyNode_ptr> bindings = node->getChildren("binding");
909   for (unsigned int i = 0; i < bindings.size(); i++) {
910     const char *cmd = bindings[i]->getStringValue("command");
911     SG_LOG(SG_INPUT, SG_DEBUG, "Reading binding " << cmd);
912
913     if (!strcmp(cmd, "nasal") && _module[0])
914       bindings[i]->setStringValue("module", _module);
915     binding_list[modifiers].push_back(new SGBinding(bindings[i], globals->get_props()));
916   }
917
918                                 // Read nested bindings for modifiers
919   if (node->getChild("mod-up") != 0)
920     _read_bindings(node->getChild("mod-up"), binding_list,
921                    modifiers|KEYMOD_RELEASED);
922
923   if (node->getChild("mod-shift") != 0)
924     _read_bindings(node->getChild("mod-shift"), binding_list,
925                    modifiers|KEYMOD_SHIFT);
926
927   if (node->getChild("mod-ctrl") != 0)
928     _read_bindings(node->getChild("mod-ctrl"), binding_list,
929                    modifiers|KEYMOD_CTRL);
930
931   if (node->getChild("mod-alt") != 0)
932     _read_bindings(node->getChild("mod-alt"), binding_list,
933                    modifiers|KEYMOD_ALT);
934 }
935
936
937 const FGInput::binding_list_t&
938 FGInput::_find_key_bindings (unsigned int k, int modifiers)
939 {
940   unsigned char kc = (unsigned char)k;
941   button &b = _key_bindings[k];
942
943                                 // Try it straight, first.
944   if (b.bindings[modifiers].size() > 0)
945     return b.bindings[modifiers];
946
947                                 // Alt-Gr is CTRL+ALT
948   else if (modifiers&(KEYMOD_CTRL|KEYMOD_ALT))
949     return _find_key_bindings(k, modifiers&~(KEYMOD_CTRL|KEYMOD_ALT));
950
951                                 // Try removing the control modifier
952                                 // for control keys.
953   else if ((modifiers&KEYMOD_CTRL) && iscntrl(kc))
954     return _find_key_bindings(k, modifiers&~KEYMOD_CTRL);
955
956                                 // Try removing shift modifier 
957                                 // for upper case or any punctuation
958                                 // (since different keyboards will
959                                 // shift different punctuation types)
960   else if ((modifiers&KEYMOD_SHIFT) && (isupper(kc) || ispunct(kc)))
961     return _find_key_bindings(k, modifiers&~KEYMOD_SHIFT);
962
963                                 // Try removing alt modifier for
964                                 // high-bit characters.
965   else if ((modifiers&KEYMOD_ALT) && k >= 128 && k < 256)
966     return _find_key_bindings(k, modifiers&~KEYMOD_ALT);
967
968                                 // Give up and return the empty vector.
969   else
970     return b.bindings[modifiers];
971 }
972
973
974 \f
975 ////////////////////////////////////////////////////////////////////////
976 // Implementation of FGInput::button.
977 ////////////////////////////////////////////////////////////////////////
978
979 FGInput::button::button ()
980   : is_repeatable(false),
981     interval_sec(0),
982     last_dt(0),
983     last_state(0)
984 {
985 }
986
987 FGInput::button::~button ()
988 {
989                                 // FIXME: memory leak
990 //   for (int i = 0; i < KEYMOD_MAX; i++)
991 //     for (int j = 0; i < bindings[i].size(); j++)
992 //       delete bindings[i][j];
993 }
994
995
996 \f
997 ////////////////////////////////////////////////////////////////////////
998 // Implementation of FGInput::axis.
999 ////////////////////////////////////////////////////////////////////////
1000
1001 FGInput::axis::axis ()
1002   : last_value(9999999),
1003     tolerance(0.002),
1004     low_threshold(-0.9),
1005     high_threshold(0.9),
1006     interval_sec(0),
1007     last_dt(0)
1008 {
1009 }
1010
1011 FGInput::axis::~axis ()
1012 {
1013 //   for (int i = 0; i < KEYMOD_MAX; i++)
1014 //     for (int j = 0; i < bindings[i].size(); j++)
1015 //       delete bindings[i][j];
1016 }
1017
1018
1019 \f
1020 ////////////////////////////////////////////////////////////////////////
1021 // Implementation of FGInput::joystick.
1022 ////////////////////////////////////////////////////////////////////////
1023
1024 FGInput::joystick::joystick ()
1025   : jsnum(0),
1026     js(0),
1027     naxes(0),
1028     nbuttons(0),
1029     axes(0),
1030     buttons(0)
1031 {
1032 }
1033
1034 FGInput::joystick::~joystick ()
1035 {
1036 //   delete js;
1037   delete[] axes;
1038   delete[] buttons;
1039 }
1040
1041
1042 \f
1043 ////////////////////////////////////////////////////////////////////////
1044 // Implementation of FGInput::mouse_mode
1045 ////////////////////////////////////////////////////////////////////////
1046
1047 FGInput::mouse_mode::mouse_mode ()
1048   : cursor(MOUSE_CURSOR_POINTER),
1049     constrained(false),
1050     pass_through(false),
1051     buttons(0)
1052 {
1053 }
1054
1055 FGInput::mouse_mode::~mouse_mode ()
1056 {
1057                                 // FIXME: memory leak
1058 //   for (int i = 0; i < KEYMOD_MAX; i++) {
1059 //     int j;
1060 //     for (j = 0; i < x_bindings[i].size(); j++)
1061 //       delete bindings[i][j];
1062 //     for (j = 0; j < y_bindings[i].size(); j++)
1063 //       delete bindings[i][j];
1064 //   }
1065   delete [] buttons;
1066 }
1067
1068
1069 \f
1070 ////////////////////////////////////////////////////////////////////////
1071 // Implementation of FGInput::mouse
1072 ////////////////////////////////////////////////////////////////////////
1073
1074 FGInput::mouse::mouse ()
1075   : x(-1),
1076     y(-1),
1077     nModes(1),
1078     current_mode(0),
1079     modes(0)
1080 {
1081 }
1082
1083 FGInput::mouse::~mouse ()
1084 {
1085   delete [] modes;
1086 }
1087
1088 ////////////////////////////////////////////////////////////////////////
1089 // Implementation of OS callbacks.
1090 ////////////////////////////////////////////////////////////////////////
1091
1092 void keyHandler(int key, int keymod, int mousex, int mousey)
1093 {
1094     if((keymod & KEYMOD_RELEASED) == 0)
1095         if(puKeyboard(key, PU_DOWN))
1096             return;
1097
1098     if(default_input)
1099         default_input->doKey(key, keymod, mousex, mousey);
1100 }
1101
1102 void mouseClickHandler(int button, int updown, int x, int y, bool mainWindow, const osgGA::GUIEventAdapter* ea)
1103 {
1104     if(default_input)
1105       default_input->doMouseClick(button, updown, x, y, mainWindow, ea);
1106 }
1107
1108 void mouseMotionHandler(int x, int y)
1109 {
1110     if (default_input != 0)
1111         default_input->doMouseMotion(x, y);
1112 }