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