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