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