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