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