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