]> git.mxchange.org Git - flightgear.git/blob - src/Input/input.cxx
- fix type warnings
[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());
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
489
490 void
491 FGInput::_postinit_joystick()
492 {
493   FGNasalSys *nasalsys = (FGNasalSys *)globals->get_subsystem("nasal");
494   SGPropertyNode *js_nodes = fgGetNode("/input/joysticks");
495   js_nodes->removeChildren("js-named");
496
497   for (int i = 0; i < MAX_JOYSTICKS; i++) {
498     SGPropertyNode_ptr js_node = js_nodes->getChild("js", i);
499     jsJoystick *js = _joystick_bindings[i].js;
500     if (!js_node || js->notWorking())
501       continue;
502
503 #ifdef WIN32
504     JOYCAPS jsCaps ;
505     joyGetDevCaps( i, &jsCaps, sizeof(jsCaps) );
506     unsigned int nbuttons = jsCaps.wNumButtons;
507     if (nbuttons > MAX_JOYSTICK_BUTTONS) nbuttons = MAX_JOYSTICK_BUTTONS;
508 #else
509     unsigned int nbuttons = MAX_JOYSTICK_BUTTONS;
510 #endif
511
512     int naxes = js->getNumAxes();
513     if (naxes > MAX_JOYSTICK_AXES) naxes = MAX_JOYSTICK_AXES;
514     _joystick_bindings[i].naxes = naxes;
515     _joystick_bindings[i].nbuttons = nbuttons;
516
517     SG_LOG(SG_INPUT, SG_DEBUG, "Initializing joystick " << i);
518
519                                 // Set up range arrays
520     float minRange[MAX_JOYSTICK_AXES];
521     float maxRange[MAX_JOYSTICK_AXES];
522     float center[MAX_JOYSTICK_AXES];
523
524                                 // Initialize with default values
525     js->getMinRange(minRange);
526     js->getMaxRange(maxRange);
527     js->getCenter(center);
528
529                                 // Allocate axes and buttons
530     _joystick_bindings[i].axes = new axis[naxes];
531     _joystick_bindings[i].buttons = new button[nbuttons];
532
533     //
534     // Initialize nasal groups.
535     //
536     string init;
537     init = "this=\"" + string(js_node->getPath()) + "\"";
538     sprintf(_module, "__js%d", i);
539     nasalsys->createModule(_module, _module, init.c_str(), init.size());
540
541     vector<SGPropertyNode_ptr> nasal = js_node->getChildren("nasal");
542     unsigned int j;
543     for (j = 0; j < nasal.size(); j++) {
544       nasal[j]->setStringValue("module", _module);
545       nasalsys->handleCommand(nasal[j]);
546     }
547
548     //
549     // Initialize the axes.
550     //
551     vector<SGPropertyNode_ptr> axes = js_node->getChildren("axis");
552     size_t nb_axes = axes.size();
553     for (j = 0; j < nb_axes; j++ ) {
554       const SGPropertyNode * axis_node = axes[j];
555       const SGPropertyNode * num_node = axis_node->getChild("number");
556       int n_axis = axis_node->getIndex();
557       if (num_node != 0) {
558           n_axis = num_node->getIntValue(TGT_PLATFORM, -1);
559
560           // Silently ignore platforms that are not specified within the
561           // <number></number> section
562           if (n_axis < 0)
563              continue;
564       }
565
566       if (n_axis >= naxes) {
567           SG_LOG(SG_INPUT, SG_DEBUG, "Dropping bindings for axis " << n_axis);
568           continue;
569       }
570       axis &a = _joystick_bindings[i].axes[n_axis];
571
572       js->setDeadBand(n_axis, axis_node->getDoubleValue("dead-band", 0.0));
573
574       a.tolerance = axis_node->getDoubleValue("tolerance", 0.002);
575       minRange[n_axis] = axis_node->getDoubleValue("min-range", minRange[n_axis]);
576       maxRange[n_axis] = axis_node->getDoubleValue("max-range", maxRange[n_axis]);
577       center[n_axis] = axis_node->getDoubleValue("center", center[n_axis]);
578
579       _read_bindings(axis_node, a.bindings, KEYMOD_NONE);
580
581       // Initialize the virtual axis buttons.
582       _init_button(axis_node->getChild("low"), a.low, "low");
583       a.low_threshold = axis_node->getDoubleValue("low-threshold", -0.9);
584
585       _init_button(axis_node->getChild("high"), a.high, "high");
586       a.high_threshold = axis_node->getDoubleValue("high-threshold", 0.9);
587       a.interval_sec = axis_node->getDoubleValue("interval-sec",0.0);
588       a.last_dt = 0.0;
589     }
590
591     //
592     // Initialize the buttons.
593     //
594     vector<SGPropertyNode_ptr> buttons = js_node->getChildren("button");
595     char buf[32];
596     for (j = 0; j < buttons.size() && j < nbuttons; j++) {
597       const SGPropertyNode * button_node = buttons[j];
598       const SGPropertyNode * num_node = button_node->getChild("number");
599       size_t n_but = button_node->getIndex();
600       if (num_node != 0) {
601           n_but = num_node->getIntValue(TGT_PLATFORM,n_but);
602       }
603
604       if (n_but >= nbuttons) {
605           SG_LOG(SG_INPUT, SG_DEBUG, "Dropping bindings for button " << n_but);
606           continue;
607       }
608
609       sprintf(buf, "%d", n_but);
610       SG_LOG(SG_INPUT, SG_DEBUG, "Initializing button " << n_but);
611       _init_button(button_node,
612                    _joystick_bindings[i].buttons[n_but],
613                    buf);
614
615       // get interval-sec property
616       button &b = _joystick_bindings[i].buttons[n_but];
617       if (button_node != 0) {
618         b.interval_sec = button_node->getDoubleValue("interval-sec",0.0);
619         b.last_dt = 0.0;
620       }
621     }
622
623     js->setMinRange(minRange);
624     js->setMaxRange(maxRange);
625     js->setCenter(center);
626   }
627 }
628
629
630 // 
631 // Map of all known cursor names
632 // This used to contain all the Glut cursors, but those are
633 // not defined by other toolkits.  It now supports only the cursor
634 // images we actually use, in the interest of portability.  Someday,
635 // it would be cool to write an OpenGL cursor renderer, with the
636 // cursors defined as textures referenced in the property tree.  This
637 // list could then be eliminated. -Andy
638 //
639 static struct {
640   const char * name;
641   int cursor;
642 } mouse_cursor_map[] = {
643   { "none", MOUSE_CURSOR_NONE },
644   { "inherit", MOUSE_CURSOR_POINTER },
645   { "wait", MOUSE_CURSOR_WAIT },
646   { "crosshair", MOUSE_CURSOR_CROSSHAIR },
647   { "left-right", MOUSE_CURSOR_LEFTRIGHT },
648   { 0, 0 }
649 };
650
651 void
652 FGInput::_init_mouse ()
653 {
654   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse bindings");
655   _module[0] = 0;
656
657   SGPropertyNode * mouse_nodes = fgGetNode("/input/mice");
658   if (mouse_nodes == 0) {
659     SG_LOG(SG_INPUT, SG_WARN, "No mouse bindings (/input/mice)!!");
660     mouse_nodes = fgGetNode("/input/mice", true);
661   }
662
663   int j;
664   for (int i = 0; i < MAX_MICE; i++) {
665     SGPropertyNode * mouse_node = mouse_nodes->getChild("mouse", i, true);
666     mouse &m = _mouse_bindings[i];
667
668                                 // Grab node pointers
669     char buf[64];
670     sprintf(buf, "/devices/status/mice/mouse[%d]/mode", i);
671     m.mode_node = fgGetNode(buf);
672     if (m.mode_node == NULL) {
673       m.mode_node = fgGetNode(buf, true);
674       m.mode_node->setIntValue(0);
675     }
676     for (j = 0; j < MAX_MOUSE_BUTTONS; j++) {
677       sprintf(buf, "/devices/status/mice/mouse[%d]/button[%d]", i, j);
678       m.mouse_button_nodes[j] = fgGetNode(buf, true);
679       m.mouse_button_nodes[j]->setBoolValue(false);
680     }
681
682                                 // Read all the modes
683     m.nModes = mouse_node->getIntValue("mode-count", 1);
684     m.modes = new mouse_mode[m.nModes];
685
686     for (int j = 0; j < m.nModes; j++) {
687       int k;
688
689                                 // Read the mouse cursor for this mode
690       SGPropertyNode * mode_node = mouse_node->getChild("mode", j, true);
691       const char * cursor_name =
692         mode_node->getStringValue("cursor", "inherit");
693       m.modes[j].cursor = MOUSE_CURSOR_POINTER;
694       for (k = 0; mouse_cursor_map[k].name != 0; k++) {
695         if (!strcmp(mouse_cursor_map[k].name, cursor_name)) {
696           m.modes[j].cursor = mouse_cursor_map[k].cursor;
697           break;
698         }
699       }
700
701                                 // Read other properties for this mode
702       m.modes[j].constrained = mode_node->getBoolValue("constrained", false);
703       m.modes[j].pass_through = mode_node->getBoolValue("pass-through", false);
704
705                                 // Read the button bindings for this mode
706       m.modes[j].buttons = new button[MAX_MOUSE_BUTTONS];
707       char buf[32];
708       for (k = 0; k < MAX_MOUSE_BUTTONS; k++) {
709         sprintf(buf, "mouse button %d", k);
710         SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse button " << k);
711         _init_button(mode_node->getChild("button", k),
712                      m.modes[j].buttons[k],
713                      buf);
714       }
715
716                                 // Read the axis bindings for this mode
717       _read_bindings(mode_node->getChild("x-axis", 0, true),
718                      m.modes[j].x_bindings,
719                      KEYMOD_NONE);
720       _read_bindings(mode_node->getChild("y-axis", 0, true),
721                      m.modes[j].y_bindings,
722                      KEYMOD_NONE);
723     }
724   }
725 }
726
727
728 void
729 FGInput::_init_button (const SGPropertyNode * node,
730                        button &b,
731                        const string name)
732 {       
733   if (node == 0) {
734     SG_LOG(SG_INPUT, SG_DEBUG, "No bindings for button " << name);
735   } else {
736     b.is_repeatable = node->getBoolValue("repeatable", b.is_repeatable);
737     
738                 // Get the bindings for the button
739     _read_bindings(node, b.bindings, KEYMOD_NONE);
740   }
741 }
742
743
744 void
745 FGInput::_update_keyboard ()
746 {
747   // no-op
748 }
749
750
751 void
752 FGInput::_update_joystick (double dt)
753 {
754   int modifiers = KEYMOD_NONE;  // FIXME: any way to get the real ones?
755   int buttons;
756   // float js_val, diff;
757   float axis_values[MAX_JOYSTICK_AXES];
758
759   int i;
760   int j;
761
762   for ( i = 0; i < MAX_JOYSTICKS; i++) {
763
764     jsJoystick * js = _joystick_bindings[i].js;
765     if (js == 0 || js->notWorking())
766       continue;
767
768     js->read(&buttons, axis_values);
769
770                                 // Fire bindings for the axes.
771     for ( j = 0; j < _joystick_bindings[i].naxes; j++) {
772       axis &a = _joystick_bindings[i].axes[j];
773       
774                                 // Do nothing if the axis position
775                                 // is unchanged; only a change in
776                                 // position fires the bindings.
777       if (fabs(axis_values[j] - a.last_value) > a.tolerance) {
778 //      SG_LOG(SG_INPUT, SG_DEBUG, "Axis " << j << " has moved");
779         a.last_value = axis_values[j];
780 //      SG_LOG(SG_INPUT, SG_DEBUG, "There are "
781 //             << a.bindings[modifiers].size() << " bindings");
782         for (unsigned int k = 0; k < a.bindings[modifiers].size(); k++)
783           a.bindings[modifiers][k]->fire(axis_values[j]);
784       }
785      
786                                 // do we have to emulate axis buttons?
787       a.last_dt += dt;
788       if(a.last_dt >= a.interval_sec) {
789         if (a.low.bindings[modifiers].size())
790           _update_button(_joystick_bindings[i].axes[j].low,
791                          modifiers,
792                          axis_values[j] < a.low_threshold,
793                          -1, -1);
794       
795         if (a.high.bindings[modifiers].size())
796           _update_button(_joystick_bindings[i].axes[j].high,
797                          modifiers,
798                          axis_values[j] > a.high_threshold,
799                          -1, -1);
800          a.last_dt -= a.interval_sec;
801       }
802     }
803
804                                 // Fire bindings for the buttons.
805     for (j = 0; j < _joystick_bindings[i].nbuttons; j++) {
806       button &b = _joystick_bindings[i].buttons[j];
807       b.last_dt += dt;
808       if(b.last_dt >= b.interval_sec) {
809         _update_button(_joystick_bindings[i].buttons[j],
810                        modifiers,
811                        (buttons & (1 << j)) > 0,
812                        -1, -1);
813         b.last_dt -= b.interval_sec;
814       }
815     }
816   }
817 }
818
819 void
820 FGInput::_update_mouse ( double dt )
821 {
822   mouse &m = _mouse_bindings[0];
823   int mode =  m.mode_node->getIntValue();
824   if (mode != m.current_mode) {
825     m.current_mode = mode;
826     m.timeout = fgGetDouble( "/sim/mouse/cursor-timeout-sec", 10.0 );
827     if (mode >= 0 && mode < m.nModes) {
828       fgSetMouseCursor(m.modes[mode].cursor);
829       m.x = fgGetInt("/sim/startup/xsize", 800) / 2;
830       m.y = fgGetInt("/sim/startup/ysize", 600) / 2;
831       fgWarpMouse(m.x, m.y);
832     } else {
833       SG_LOG(SG_INPUT, SG_DEBUG, "Mouse mode " << mode << " out of range");
834       fgSetMouseCursor(MOUSE_CURSOR_POINTER);
835     }
836   }
837
838   if ( fgGetBool( "/sim/mouse/hide-cursor", true ) ) {
839       if ( m.x != m.save_x || m.y != m.save_y ) {
840           m.timeout = fgGetDouble( "/sim/mouse/cursor-timeout-sec", 10.0 );
841           fgSetMouseCursor(m.modes[mode].cursor);
842       } else {
843           m.timeout -= dt;
844           if ( m.timeout <= 0.0 ) {
845               fgSetMouseCursor(MOUSE_CURSOR_NONE);
846               m.timeout = 0.0;
847           }
848       }
849       m.save_x = m.x;
850       m.save_y = m.y;
851   }
852 }
853
854 void
855 FGInput::_update_button (button &b, int modifiers, bool pressed,
856                          int x, int y)
857 {
858   if (pressed) {
859                                 // The press event may be repeated.
860     if (!b.last_state || b.is_repeatable) {
861       SG_LOG( SG_INPUT, SG_DEBUG, "Button has been pressed" );
862       for (unsigned int k = 0; k < b.bindings[modifiers].size(); k++)
863         b.bindings[modifiers][k]->fire(x, y);
864     }
865   } else {
866                                 // The release event is never repeated.
867     if (b.last_state) {
868       SG_LOG( SG_INPUT, SG_DEBUG, "Button has been released" );
869       for (unsigned int k = 0; k < b.bindings[modifiers|KEYMOD_RELEASED].size(); k++)
870         b.bindings[modifiers|KEYMOD_RELEASED][k]->fire(x, y);
871     }
872   }
873           
874   b.last_state = pressed;
875 }  
876
877
878 void
879 FGInput::_read_bindings (const SGPropertyNode * node, 
880                          binding_list_t * binding_list,
881                          int modifiers)
882 {
883   SG_LOG(SG_INPUT, SG_DEBUG, "Reading all bindings");
884   vector<SGPropertyNode_ptr> bindings = node->getChildren("binding");
885   for (unsigned int i = 0; i < bindings.size(); i++) {
886     const char *cmd = bindings[i]->getStringValue("command");
887     SG_LOG(SG_INPUT, SG_DEBUG, "Reading binding " << cmd);
888
889     if (!strcmp(cmd, "nasal") && _module[0])
890       bindings[i]->setStringValue("module", _module);
891     binding_list[modifiers].push_back(new FGBinding(bindings[i]));
892   }
893
894                                 // Read nested bindings for modifiers
895   if (node->getChild("mod-up") != 0)
896     _read_bindings(node->getChild("mod-up"), binding_list,
897                    modifiers|KEYMOD_RELEASED);
898
899   if (node->getChild("mod-shift") != 0)
900     _read_bindings(node->getChild("mod-shift"), binding_list,
901                    modifiers|KEYMOD_SHIFT);
902
903   if (node->getChild("mod-ctrl") != 0)
904     _read_bindings(node->getChild("mod-ctrl"), binding_list,
905                    modifiers|KEYMOD_CTRL);
906
907   if (node->getChild("mod-alt") != 0)
908     _read_bindings(node->getChild("mod-alt"), binding_list,
909                    modifiers|KEYMOD_ALT);
910 }
911
912
913 const vector<FGBinding *> &
914 FGInput::_find_key_bindings (unsigned int k, int modifiers)
915 {
916   unsigned char kc = (unsigned char)k;
917   button &b = _key_bindings[k];
918
919                                 // Try it straight, first.
920   if (b.bindings[modifiers].size() > 0)
921     return b.bindings[modifiers];
922
923                                 // Alt-Gr is CTRL+ALT
924   else if (modifiers&(KEYMOD_CTRL|KEYMOD_ALT))
925     return _find_key_bindings(k, modifiers&~(KEYMOD_CTRL|KEYMOD_ALT));
926
927                                 // Try removing the control modifier
928                                 // for control keys.
929   else if ((modifiers&KEYMOD_CTRL) && iscntrl(kc))
930     return _find_key_bindings(k, modifiers&~KEYMOD_CTRL);
931
932                                 // Try removing shift modifier 
933                                 // for upper case or any punctuation
934                                 // (since different keyboards will
935                                 // shift different punctuation types)
936   else if ((modifiers&KEYMOD_SHIFT) && (isupper(kc) || ispunct(kc)))
937     return _find_key_bindings(k, modifiers&~KEYMOD_SHIFT);
938
939                                 // Try removing alt modifier for
940                                 // high-bit characters.
941   else if ((modifiers&KEYMOD_ALT) && k >= 128 && k < 256)
942     return _find_key_bindings(k, modifiers&~KEYMOD_ALT);
943
944                                 // Give up and return the empty vector.
945   else
946     return b.bindings[modifiers];
947 }
948
949
950 \f
951 ////////////////////////////////////////////////////////////////////////
952 // Implementation of FGInput::button.
953 ////////////////////////////////////////////////////////////////////////
954
955 FGInput::button::button ()
956   : is_repeatable(false),
957     last_state(-1)
958 {
959 }
960
961 FGInput::button::~button ()
962 {
963                                 // FIXME: memory leak
964 //   for (int i = 0; i < KEYMOD_MAX; i++)
965 //     for (int j = 0; i < bindings[i].size(); j++)
966 //       delete bindings[i][j];
967 }
968
969
970 \f
971 ////////////////////////////////////////////////////////////////////////
972 // Implementation of FGInput::axis.
973 ////////////////////////////////////////////////////////////////////////
974
975 FGInput::axis::axis ()
976   : last_value(9999999),
977     tolerance(0.002),
978     low_threshold(-0.9),
979     high_threshold(0.9)
980 {
981 }
982
983 FGInput::axis::~axis ()
984 {
985 //   for (int i = 0; i < KEYMOD_MAX; i++)
986 //     for (int j = 0; i < bindings[i].size(); j++)
987 //       delete bindings[i][j];
988 }
989
990
991 \f
992 ////////////////////////////////////////////////////////////////////////
993 // Implementation of FGInput::joystick.
994 ////////////////////////////////////////////////////////////////////////
995
996 FGInput::joystick::joystick ()
997 {
998 }
999
1000 FGInput::joystick::~joystick ()
1001 {
1002 //   delete js;
1003   delete[] axes;
1004   delete[] buttons;
1005 }
1006
1007
1008 \f
1009 ////////////////////////////////////////////////////////////////////////
1010 // Implementation of FGInput::mouse_mode
1011 ////////////////////////////////////////////////////////////////////////
1012
1013 FGInput::mouse_mode::mouse_mode ()
1014   : cursor(MOUSE_CURSOR_POINTER),
1015     constrained(false),
1016     pass_through(false),
1017     buttons(0)
1018 {
1019 }
1020
1021 FGInput::mouse_mode::~mouse_mode ()
1022 {
1023                                 // FIXME: memory leak
1024 //   for (int i = 0; i < KEYMOD_MAX; i++) {
1025 //     int j;
1026 //     for (j = 0; i < x_bindings[i].size(); j++)
1027 //       delete bindings[i][j];
1028 //     for (j = 0; j < y_bindings[i].size(); j++)
1029 //       delete bindings[i][j];
1030 //   }
1031   delete [] buttons;
1032 }
1033
1034
1035 \f
1036 ////////////////////////////////////////////////////////////////////////
1037 // Implementation of FGInput::mouse
1038 ////////////////////////////////////////////////////////////////////////
1039
1040 FGInput::mouse::mouse ()
1041   : x(-1),
1042     y(-1),
1043     nModes(1),
1044     current_mode(0),
1045     modes(0)
1046 {
1047 }
1048
1049 FGInput::mouse::~mouse ()
1050 {
1051   delete [] modes;
1052 }
1053
1054 ////////////////////////////////////////////////////////////////////////
1055 // Implementation of OS callbacks.
1056 ////////////////////////////////////////////////////////////////////////
1057
1058 void keyHandler(int key, int keymod, int mousex, int mousey)
1059 {
1060     if((keymod & KEYMOD_RELEASED) == 0)
1061         if(puKeyboard(key, PU_DOWN))
1062             return;
1063
1064     if(default_input)
1065         default_input->doKey(key, keymod, mousex, mousey);
1066 }
1067
1068 void mouseClickHandler(int button, int updown, int x, int y)
1069 {
1070     if(default_input)
1071         default_input->doMouseClick(button, updown, x, y);
1072 }
1073
1074 void mouseMotionHandler(int x, int y)
1075 {
1076     if (default_input != 0)
1077         default_input->doMouseMotion(x, y);
1078 }