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