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