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