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