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