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