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