]> git.mxchange.org Git - flightgear.git/blob - src/Input/input.cxx
fa5552c883b59f74d1a075d6acefd79380cd1295
[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., 675 Mass Ave, Cambridge, MA 02139, 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.  This should eventually get written into a set
320       // of properties so that some other [future] subsystems can do
321       // something useful with the information.
322       FGScenery* scenery = globals->get_scenery();
323       sgdVec3 start, dir, hit;
324       if (FGRenderer::getPickInfo(start, dir, x, y) &&
325           scenery->get_cart_ground_intersection(start, dir, hit)) {
326         
327         Point3D geod = sgCartToGeod(Point3D(hit[0], hit[1], hit[2]));
328         
329         std::cout << "lon = " << geod.lon()*SGD_RADIANS_TO_DEGREES
330                   << " deg, lat = " << geod.lat()*SGD_RADIANS_TO_DEGREES
331                   << " deg, elev = " << geod.elev()
332                   << " m" << std::endl;
333       } else {
334         std::cout << "Cannot find intersection point" << std::endl;
335       }
336     }
337   }
338
339                                 // OK, PUI and the panel didn't want the click
340   if (b >= MAX_MOUSE_BUTTONS) {
341     SG_LOG(SG_INPUT, SG_ALERT, "Mouse button " << b
342            << " where only " << MAX_MOUSE_BUTTONS << " expected");
343     return;
344   }
345
346   _update_button(m.modes[m.current_mode].buttons[b], modifiers, 0 != updown, x, y);
347 }
348
349 void
350 FGInput::doMouseMotion (int x, int y)
351 {
352   // Don't call fgGetKeyModifiers() here, until we are using a
353   // toolkit that supports getting the mods from outside a key
354   // callback.  Glut doesn't.
355   int modifiers = KEYMOD_NONE;
356
357   int xsize = fgGetInt("/sim/startup/xsize", 800);
358   int ysize = fgGetInt("/sim/startup/ysize", 600);
359
360   mouse &m = _mouse_bindings[0];
361
362   if (m.current_mode < 0 || m.current_mode >= m.nModes) {
363       m.x = x;
364       m.y = y;
365       return;
366   }
367   mouse_mode &mode = m.modes[m.current_mode];
368
369                                 // Pass on to PUI if requested, and return
370                                 // if PUI consumed the event.
371   if (mode.pass_through && puMouse(x, y)) {
372       m.x = x;
373       m.y = y;
374       return;
375   }
376
377                                 // OK, PUI didn't want the event,
378                                 // so we can play with it.
379   if (x != m.x) {
380     int delta = x - m.x;
381     for (unsigned int i = 0; i < mode.x_bindings[modifiers].size(); i++)
382       mode.x_bindings[modifiers][i]->fire(double(delta), double(xsize));
383   }
384   if (y != m.y) {
385     int delta = y - m.y;
386     for (unsigned int i = 0; i < mode.y_bindings[modifiers].size(); i++)
387       mode.y_bindings[modifiers][i]->fire(double(delta), double(ysize));
388   }
389
390                                 // Constrain the mouse if requested
391   if (mode.constrained) {
392     bool need_warp = false;
393     if (x <= 0) {
394       x = xsize - 2;
395       need_warp = true;
396     } else if (x >= (xsize-1)) {
397       x = 1;
398       need_warp = true;
399     }
400
401     if (y <= 0) {
402       y = ysize - 2;
403       need_warp = true;
404     } else if (y >= (ysize-1)) {
405       y = 1;
406       need_warp = true;
407     }
408
409     if (need_warp)
410       fgWarpMouse(x, y);
411   }
412   m.x = x;
413   m.y = y;
414 }
415
416 void
417 FGInput::_init_keyboard ()
418 {
419   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing key bindings");
420   _module[0] = 0;
421   SGPropertyNode * key_nodes = fgGetNode("/input/keyboard");
422   if (key_nodes == 0) {
423     SG_LOG(SG_INPUT, SG_WARN, "No key bindings (/input/keyboard)!!");
424     key_nodes = fgGetNode("/input/keyboard", true);
425   }
426   
427   vector<SGPropertyNode_ptr> keys = key_nodes->getChildren("key");
428   for (unsigned int i = 0; i < keys.size(); i++) {
429     int index = keys[i]->getIndex();
430     SG_LOG(SG_INPUT, SG_DEBUG, "Binding key " << index);
431
432     _key_bindings[index].bindings->clear();
433     _key_bindings[index].is_repeatable = keys[i]->getBoolValue("repeatable");
434     _key_bindings[index].last_state = 0;
435     _read_bindings(keys[i], _key_bindings[index].bindings, KEYMOD_NONE);
436   }
437 }
438
439
440 void
441 FGInput::_scan_joystick_dir(SGPath *path, SGPropertyNode* node, int *index)
442 {
443   ulDir *dir = ulOpenDir(path->c_str());
444   if (dir) {
445     ulDirEnt* dent;
446     while ((dent = ulReadDir(dir)) != 0) {
447       if (dent->d_name[0] == '.')
448         continue;
449
450       SGPath p(path->str());
451       p.append(dent->d_name);
452       _scan_joystick_dir(&p, node, index);
453     }
454     ulCloseDir(dir);
455
456   } else if (path->extension() == "xml") {
457     SG_LOG(SG_INPUT, SG_DEBUG, "Reading joystick file " << path->str());
458     SGPropertyNode *n = node->getChild("js-named", (*index)++, true);
459     readProperties(path->str(), n);
460     n->setStringValue("source", path->c_str());
461   }
462 }
463
464
465 void
466 FGInput::_init_joystick ()
467 {
468   jsInit();
469                                 // TODO: zero the old bindings first.
470   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing joystick bindings");
471   SGPropertyNode * js_nodes = fgGetNode("/input/joysticks", true);
472
473   // read all joystick xml files into /input/joysticks/js_named[1000++]
474   SGPath path(globals->get_fg_root());
475   path.append("Input/Joysticks");
476   int js_named_index = 1000;
477   _scan_joystick_dir(&path, js_nodes, &js_named_index);
478
479   // build name->node map with each <name> (reverse order)
480   map<string, SGPropertyNode_ptr> jsmap;
481   vector<SGPropertyNode_ptr> js_named = js_nodes->getChildren("js-named");
482
483   for (int k = (int)js_named.size() - 1; k >= 0; k--) {
484     SGPropertyNode *n = js_named[k];
485     vector<SGPropertyNode_ptr> names = n->getChildren("name");
486     if (names.size() && (n->getChildren("axis").size() || n->getChildren("button").size()))
487       for (unsigned int j = 0; j < names.size(); j++)
488         jsmap[names[j]->getStringValue()] = n;
489   }
490
491   // set up js[] nodes
492   for (int i = 0; i < MAX_JOYSTICKS; i++) {
493     jsJoystick * js = new jsJoystick(i);
494     _joystick_bindings[i].js = js;
495
496     if (js->notWorking()) {
497       SG_LOG(SG_INPUT, SG_DEBUG, "Joystick " << i << " not found");
498       continue;
499     }
500
501     const char * name = js->getName();
502     SGPropertyNode_ptr js_node = js_nodes->getChild("js", i);
503
504     if (js_node) {
505       SG_LOG(SG_INPUT, SG_INFO, "Using existing bindings for joystick " << i);
506
507     } else {
508       SG_LOG(SG_INPUT, SG_INFO, "Looking for bindings for joystick \"" << name << '"');
509       SGPropertyNode_ptr named;
510
511       if ((named = jsmap[name])) {
512         string source = named->getStringValue("source", "user defined");
513         SG_LOG(SG_INPUT, SG_INFO, "... found joystick: " << source);
514
515       } else if ((named = jsmap["default"])) {
516         string source = named->getStringValue("source", "user defined");
517         SG_LOG(SG_INPUT, SG_INFO, "No config found for joystick \"" << name
518             << "\"\nUsing default: \"" << source << '"');
519
520       } else {
521         throw sg_throwable(string("No joystick configuration file with "
522             "<name>default</name> entry found!"));
523       }
524
525       js_node = js_nodes->getChild("js", i, true);
526       copyProperties(named, js_node);
527       js_node->setStringValue("id", name);
528     }
529   }
530
531   // get rid of unused config nodes
532   js_nodes->removeChildren("js-named", false);
533 }
534
535
536 void
537 FGInput::_postinit_joystick()
538 {
539   FGNasalSys *nasalsys = (FGNasalSys *)globals->get_subsystem("nasal");
540   SGPropertyNode *js_nodes = fgGetNode("/input/joysticks");
541
542   for (int i = 0; i < MAX_JOYSTICKS; i++) {
543     SGPropertyNode_ptr js_node = js_nodes->getChild("js", i);
544     jsJoystick *js = _joystick_bindings[i].js;
545     if (!js_node || js->notWorking())
546       continue;
547
548 #ifdef WIN32
549     JOYCAPS jsCaps ;
550     joyGetDevCaps( i, &jsCaps, sizeof(jsCaps) );
551     unsigned int nbuttons = jsCaps.wNumButtons;
552     if (nbuttons > MAX_JOYSTICK_BUTTONS) nbuttons = MAX_JOYSTICK_BUTTONS;
553 #else
554     unsigned int nbuttons = MAX_JOYSTICK_BUTTONS;
555 #endif
556
557     int naxes = js->getNumAxes();
558     if (naxes > MAX_JOYSTICK_AXES) naxes = MAX_JOYSTICK_AXES;
559     _joystick_bindings[i].naxes = naxes;
560     _joystick_bindings[i].nbuttons = nbuttons;
561
562     SG_LOG(SG_INPUT, SG_DEBUG, "Initializing joystick " << i);
563
564                                 // Set up range arrays
565     float minRange[MAX_JOYSTICK_AXES];
566     float maxRange[MAX_JOYSTICK_AXES];
567     float center[MAX_JOYSTICK_AXES];
568
569                                 // Initialize with default values
570     js->getMinRange(minRange);
571     js->getMaxRange(maxRange);
572     js->getCenter(center);
573
574                                 // Allocate axes and buttons
575     _joystick_bindings[i].axes = new axis[naxes];
576     _joystick_bindings[i].buttons = new button[nbuttons];
577
578     //
579     // Initialize nasal groups.
580     //
581     string init;
582     init = "this=\"" + string(js_node->getPath()) + "\"";
583     sprintf(_module, "__js%d", i);
584     nasalsys->createModule(_module, _module, init.c_str(), init.size());
585
586     vector<SGPropertyNode_ptr> nasal = js_node->getChildren("nasal");
587     unsigned int j;
588     for (j = 0; j < nasal.size(); j++) {
589       nasal[j]->setStringValue("module", _module);
590       nasalsys->handleCommand(nasal[j]);
591     }
592
593     //
594     // Initialize the axes.
595     //
596     vector<SGPropertyNode_ptr> axes = js_node->getChildren("axis");
597     size_t nb_axes = axes.size();
598     for (j = 0; j < nb_axes; j++ ) {
599       const SGPropertyNode * axis_node = axes[j];
600       const SGPropertyNode * num_node = axis_node->getChild("number");
601       int n_axis = axis_node->getIndex();
602       if (num_node != 0) {
603           n_axis = num_node->getIntValue(TGT_PLATFORM, -1);
604
605           // Silently ignore platforms that are not specified within the
606           // <number></number> section
607           if (n_axis < 0)
608              continue;
609       }
610
611       if (n_axis >= naxes) {
612           SG_LOG(SG_INPUT, SG_DEBUG, "Dropping bindings for axis " << n_axis);
613           continue;
614       }
615       axis &a = _joystick_bindings[i].axes[n_axis];
616
617       js->setDeadBand(n_axis, axis_node->getDoubleValue("dead-band", 0.0));
618
619       a.tolerance = axis_node->getDoubleValue("tolerance", 0.002);
620       minRange[n_axis] = axis_node->getDoubleValue("min-range", minRange[n_axis]);
621       maxRange[n_axis] = axis_node->getDoubleValue("max-range", maxRange[n_axis]);
622       center[n_axis] = axis_node->getDoubleValue("center", center[n_axis]);
623
624       _read_bindings(axis_node, a.bindings, KEYMOD_NONE);
625
626       // Initialize the virtual axis buttons.
627       _init_button(axis_node->getChild("low"), a.low, "low");
628       a.low_threshold = axis_node->getDoubleValue("low-threshold", -0.9);
629
630       _init_button(axis_node->getChild("high"), a.high, "high");
631       a.high_threshold = axis_node->getDoubleValue("high-threshold", 0.9);
632       a.interval_sec = axis_node->getDoubleValue("interval-sec",0.0);
633       a.last_dt = 0.0;
634     }
635
636     //
637     // Initialize the buttons.
638     //
639     vector<SGPropertyNode_ptr> buttons = js_node->getChildren("button");
640     char buf[32];
641     for (j = 0; j < buttons.size() && j < nbuttons; j++) {
642       const SGPropertyNode * button_node = buttons[j];
643       const SGPropertyNode * num_node = button_node->getChild("number");
644       size_t n_but = button_node->getIndex();
645       if (num_node != 0) {
646           n_but = num_node->getIntValue(TGT_PLATFORM,n_but);
647       }
648
649       if (n_but >= nbuttons) {
650           SG_LOG(SG_INPUT, SG_DEBUG, "Dropping bindings for button " << n_but);
651           continue;
652       }
653
654       sprintf(buf, "%d", n_but);
655       SG_LOG(SG_INPUT, SG_DEBUG, "Initializing button " << n_but);
656       _init_button(button_node,
657                    _joystick_bindings[i].buttons[n_but],
658                    buf);
659
660       // get interval-sec property
661       button &b = _joystick_bindings[i].buttons[n_but];
662       if (button_node != 0) {
663         b.interval_sec = button_node->getDoubleValue("interval-sec",0.0);
664         b.last_dt = 0.0;
665       }
666     }
667
668     js->setMinRange(minRange);
669     js->setMaxRange(maxRange);
670     js->setCenter(center);
671   }
672 }
673
674
675 // 
676 // Map of all known cursor names
677 // This used to contain all the Glut cursors, but those are
678 // not defined by other toolkits.  It now supports only the cursor
679 // images we actually use, in the interest of portability.  Someday,
680 // it would be cool to write an OpenGL cursor renderer, with the
681 // cursors defined as textures referenced in the property tree.  This
682 // list could then be eliminated. -Andy
683 //
684 static struct {
685   const char * name;
686   int cursor;
687 } mouse_cursor_map[] = {
688   { "none", MOUSE_CURSOR_NONE },
689   { "inherit", MOUSE_CURSOR_POINTER },
690   { "wait", MOUSE_CURSOR_WAIT },
691   { "crosshair", MOUSE_CURSOR_CROSSHAIR },
692   { "left-right", MOUSE_CURSOR_LEFTRIGHT },
693   { 0, 0 }
694 };
695
696 void
697 FGInput::_init_mouse ()
698 {
699   SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse bindings");
700   _module[0] = 0;
701
702   SGPropertyNode * mouse_nodes = fgGetNode("/input/mice");
703   if (mouse_nodes == 0) {
704     SG_LOG(SG_INPUT, SG_WARN, "No mouse bindings (/input/mice)!!");
705     mouse_nodes = fgGetNode("/input/mice", true);
706   }
707
708   int j;
709   for (int i = 0; i < MAX_MICE; i++) {
710     SGPropertyNode * mouse_node = mouse_nodes->getChild("mouse", i, true);
711     mouse &m = _mouse_bindings[i];
712
713                                 // Grab node pointers
714     char buf[64];
715     sprintf(buf, "/devices/status/mice/mouse[%d]/mode", i);
716     m.mode_node = fgGetNode(buf);
717     if (m.mode_node == NULL) {
718       m.mode_node = fgGetNode(buf, true);
719       m.mode_node->setIntValue(0);
720     }
721     for (j = 0; j < MAX_MOUSE_BUTTONS; j++) {
722       sprintf(buf, "/devices/status/mice/mouse[%d]/button[%d]", i, j);
723       m.mouse_button_nodes[j] = fgGetNode(buf, true);
724       m.mouse_button_nodes[j]->setBoolValue(false);
725     }
726
727                                 // Read all the modes
728     m.nModes = mouse_node->getIntValue("mode-count", 1);
729     m.modes = new mouse_mode[m.nModes];
730
731     for (int j = 0; j < m.nModes; j++) {
732       int k;
733
734                                 // Read the mouse cursor for this mode
735       SGPropertyNode * mode_node = mouse_node->getChild("mode", j, true);
736       const char * cursor_name =
737         mode_node->getStringValue("cursor", "inherit");
738       m.modes[j].cursor = MOUSE_CURSOR_POINTER;
739       for (k = 0; mouse_cursor_map[k].name != 0; k++) {
740         if (!strcmp(mouse_cursor_map[k].name, cursor_name)) {
741           m.modes[j].cursor = mouse_cursor_map[k].cursor;
742           break;
743         }
744       }
745
746                                 // Read other properties for this mode
747       m.modes[j].constrained = mode_node->getBoolValue("constrained", false);
748       m.modes[j].pass_through = mode_node->getBoolValue("pass-through", false);
749
750                                 // Read the button bindings for this mode
751       m.modes[j].buttons = new button[MAX_MOUSE_BUTTONS];
752       char buf[32];
753       for (k = 0; k < MAX_MOUSE_BUTTONS; k++) {
754         sprintf(buf, "mouse button %d", k);
755         SG_LOG(SG_INPUT, SG_DEBUG, "Initializing mouse button " << k);
756         _init_button(mode_node->getChild("button", k),
757                      m.modes[j].buttons[k],
758                      buf);
759       }
760
761                                 // Read the axis bindings for this mode
762       _read_bindings(mode_node->getChild("x-axis", 0, true),
763                      m.modes[j].x_bindings,
764                      KEYMOD_NONE);
765       _read_bindings(mode_node->getChild("y-axis", 0, true),
766                      m.modes[j].y_bindings,
767                      KEYMOD_NONE);
768     }
769   }
770 }
771
772
773 void
774 FGInput::_init_button (const SGPropertyNode * node,
775                        button &b,
776                        const string name)
777 {       
778   if (node == 0) {
779     SG_LOG(SG_INPUT, SG_DEBUG, "No bindings for button " << name);
780   } else {
781     b.is_repeatable = node->getBoolValue("repeatable", b.is_repeatable);
782     
783                 // Get the bindings for the button
784     _read_bindings(node, b.bindings, KEYMOD_NONE);
785   }
786 }
787
788
789 void
790 FGInput::_update_keyboard ()
791 {
792   // no-op
793 }
794
795
796 void
797 FGInput::_update_joystick (double dt)
798 {
799   int modifiers = KEYMOD_NONE;  // FIXME: any way to get the real ones?
800   int buttons;
801   // float js_val, diff;
802   float axis_values[MAX_JOYSTICK_AXES];
803
804   int i;
805   int j;
806
807   for ( i = 0; i < MAX_JOYSTICKS; i++) {
808
809     jsJoystick * js = _joystick_bindings[i].js;
810     if (js == 0 || js->notWorking())
811       continue;
812
813     js->read(&buttons, axis_values);
814
815                                 // Fire bindings for the axes.
816     for ( j = 0; j < _joystick_bindings[i].naxes; j++) {
817       axis &a = _joystick_bindings[i].axes[j];
818       
819                                 // Do nothing if the axis position
820                                 // is unchanged; only a change in
821                                 // position fires the bindings.
822       if (fabs(axis_values[j] - a.last_value) > a.tolerance) {
823 //      SG_LOG(SG_INPUT, SG_DEBUG, "Axis " << j << " has moved");
824         a.last_value = axis_values[j];
825 //      SG_LOG(SG_INPUT, SG_DEBUG, "There are "
826 //             << a.bindings[modifiers].size() << " bindings");
827         for (unsigned int k = 0; k < a.bindings[modifiers].size(); k++)
828           a.bindings[modifiers][k]->fire(axis_values[j]);
829       }
830      
831                                 // do we have to emulate axis buttons?
832       a.last_dt += dt;
833       if(a.last_dt >= a.interval_sec) {
834         if (a.low.bindings[modifiers].size())
835           _update_button(_joystick_bindings[i].axes[j].low,
836                          modifiers,
837                          axis_values[j] < a.low_threshold,
838                          -1, -1);
839       
840         if (a.high.bindings[modifiers].size())
841           _update_button(_joystick_bindings[i].axes[j].high,
842                          modifiers,
843                          axis_values[j] > a.high_threshold,
844                          -1, -1);
845          a.last_dt -= a.interval_sec;
846       }
847     }
848
849                                 // Fire bindings for the buttons.
850     for (j = 0; j < _joystick_bindings[i].nbuttons; j++) {
851       button &b = _joystick_bindings[i].buttons[j];
852       b.last_dt += dt;
853       if(b.last_dt >= b.interval_sec) {
854         _update_button(_joystick_bindings[i].buttons[j],
855                        modifiers,
856                        (buttons & (1 << j)) > 0,
857                        -1, -1);
858         b.last_dt -= b.interval_sec;
859       }
860     }
861   }
862 }
863
864 void
865 FGInput::_update_mouse ( double dt )
866 {
867   mouse &m = _mouse_bindings[0];
868   int mode =  m.mode_node->getIntValue();
869   if (mode != m.current_mode) {
870     m.current_mode = mode;
871     m.timeout = fgGetDouble( "/sim/mouse/cursor-timeout-sec", 10.0 );
872     if (mode >= 0 && mode < m.nModes) {
873       fgSetMouseCursor(m.modes[mode].cursor);
874       m.x = fgGetInt("/sim/startup/xsize", 800) / 2;
875       m.y = fgGetInt("/sim/startup/ysize", 600) / 2;
876       fgWarpMouse(m.x, m.y);
877     } else {
878       SG_LOG(SG_INPUT, SG_DEBUG, "Mouse mode " << mode << " out of range");
879       fgSetMouseCursor(MOUSE_CURSOR_POINTER);
880     }
881   }
882
883   if ( fgGetBool( "/sim/mouse/hide-cursor", true ) ) {
884       if ( m.x != m.save_x || m.y != m.save_y ) {
885           m.timeout = fgGetDouble( "/sim/mouse/cursor-timeout-sec", 10.0 );
886           fgSetMouseCursor(m.modes[mode].cursor);
887       } else {
888           m.timeout -= dt;
889           if ( m.timeout <= 0.0 ) {
890               fgSetMouseCursor(MOUSE_CURSOR_NONE);
891               m.timeout = 0.0;
892           }
893       }
894       m.save_x = m.x;
895       m.save_y = m.y;
896   }
897 }
898
899 void
900 FGInput::_update_button (button &b, int modifiers, bool pressed,
901                          int x, int y)
902 {
903   if (pressed) {
904                                 // The press event may be repeated.
905     if (!b.last_state || b.is_repeatable) {
906       SG_LOG( SG_INPUT, SG_DEBUG, "Button has been pressed" );
907       for (unsigned int k = 0; k < b.bindings[modifiers].size(); k++)
908         b.bindings[modifiers][k]->fire(x, y);
909     }
910   } else {
911                                 // The release event is never repeated.
912     if (b.last_state) {
913       SG_LOG( SG_INPUT, SG_DEBUG, "Button has been released" );
914       for (unsigned int k = 0; k < b.bindings[modifiers|KEYMOD_RELEASED].size(); k++)
915         b.bindings[modifiers|KEYMOD_RELEASED][k]->fire(x, y);
916     }
917   }
918           
919   b.last_state = pressed;
920 }  
921
922
923 void
924 FGInput::_read_bindings (const SGPropertyNode * node, 
925                          binding_list_t * binding_list,
926                          int modifiers)
927 {
928   SG_LOG(SG_INPUT, SG_DEBUG, "Reading all bindings");
929   vector<SGPropertyNode_ptr> bindings = node->getChildren("binding");
930   for (unsigned int i = 0; i < bindings.size(); i++) {
931     const char *cmd = bindings[i]->getStringValue("command");
932     SG_LOG(SG_INPUT, SG_DEBUG, "Reading binding " << cmd);
933
934     if (!strcmp(cmd, "nasal") && _module[0])
935       bindings[i]->setStringValue("module", _module);
936     binding_list[modifiers].push_back(new FGBinding(bindings[i]));
937   }
938
939                                 // Read nested bindings for modifiers
940   if (node->getChild("mod-up") != 0)
941     _read_bindings(node->getChild("mod-up"), binding_list,
942                    modifiers|KEYMOD_RELEASED);
943
944   if (node->getChild("mod-shift") != 0)
945     _read_bindings(node->getChild("mod-shift"), binding_list,
946                    modifiers|KEYMOD_SHIFT);
947
948   if (node->getChild("mod-ctrl") != 0)
949     _read_bindings(node->getChild("mod-ctrl"), binding_list,
950                    modifiers|KEYMOD_CTRL);
951
952   if (node->getChild("mod-alt") != 0)
953     _read_bindings(node->getChild("mod-alt"), binding_list,
954                    modifiers|KEYMOD_ALT);
955 }
956
957
958 const vector<FGBinding *> &
959 FGInput::_find_key_bindings (unsigned int k, int modifiers)
960 {
961   unsigned char kc = (unsigned char)k;
962   button &b = _key_bindings[k];
963
964                                 // Try it straight, first.
965   if (b.bindings[modifiers].size() > 0)
966     return b.bindings[modifiers];
967
968                                 // Alt-Gr is CTRL+ALT
969   else if (modifiers&(KEYMOD_CTRL|KEYMOD_ALT))
970     return _find_key_bindings(k, modifiers&~(KEYMOD_CTRL|KEYMOD_ALT));
971
972                                 // Try removing the control modifier
973                                 // for control keys.
974   else if ((modifiers&KEYMOD_CTRL) && iscntrl(kc))
975     return _find_key_bindings(k, modifiers&~KEYMOD_CTRL);
976
977                                 // Try removing shift modifier 
978                                 // for upper case or any punctuation
979                                 // (since different keyboards will
980                                 // shift different punctuation types)
981   else if ((modifiers&KEYMOD_SHIFT) && (isupper(kc) || ispunct(kc)))
982     return _find_key_bindings(k, modifiers&~KEYMOD_SHIFT);
983
984                                 // Try removing alt modifier for
985                                 // high-bit characters.
986   else if ((modifiers&KEYMOD_ALT) && k >= 128 && k < 256)
987     return _find_key_bindings(k, modifiers&~KEYMOD_ALT);
988
989                                 // Give up and return the empty vector.
990   else
991     return b.bindings[modifiers];
992 }
993
994
995 \f
996 ////////////////////////////////////////////////////////////////////////
997 // Implementation of FGInput::button.
998 ////////////////////////////////////////////////////////////////////////
999
1000 FGInput::button::button ()
1001   : is_repeatable(false),
1002     interval_sec(0),
1003     last_dt(0),
1004     last_state(0)
1005 {
1006 }
1007
1008 FGInput::button::~button ()
1009 {
1010                                 // FIXME: memory leak
1011 //   for (int i = 0; i < KEYMOD_MAX; i++)
1012 //     for (int j = 0; i < bindings[i].size(); j++)
1013 //       delete bindings[i][j];
1014 }
1015
1016
1017 \f
1018 ////////////////////////////////////////////////////////////////////////
1019 // Implementation of FGInput::axis.
1020 ////////////////////////////////////////////////////////////////////////
1021
1022 FGInput::axis::axis ()
1023   : last_value(9999999),
1024     tolerance(0.002),
1025     low_threshold(-0.9),
1026     high_threshold(0.9),
1027     interval_sec(0),
1028     last_dt(0)
1029 {
1030 }
1031
1032 FGInput::axis::~axis ()
1033 {
1034 //   for (int i = 0; i < KEYMOD_MAX; i++)
1035 //     for (int j = 0; i < bindings[i].size(); j++)
1036 //       delete bindings[i][j];
1037 }
1038
1039
1040 \f
1041 ////////////////////////////////////////////////////////////////////////
1042 // Implementation of FGInput::joystick.
1043 ////////////////////////////////////////////////////////////////////////
1044
1045 FGInput::joystick::joystick ()
1046   : jsnum(0),
1047     js(0),
1048     naxes(0),
1049     nbuttons(0),
1050     axes(0),
1051     buttons(0)
1052 {
1053 }
1054
1055 FGInput::joystick::~joystick ()
1056 {
1057 //   delete js;
1058   delete[] axes;
1059   delete[] buttons;
1060 }
1061
1062
1063 \f
1064 ////////////////////////////////////////////////////////////////////////
1065 // Implementation of FGInput::mouse_mode
1066 ////////////////////////////////////////////////////////////////////////
1067
1068 FGInput::mouse_mode::mouse_mode ()
1069   : cursor(MOUSE_CURSOR_POINTER),
1070     constrained(false),
1071     pass_through(false),
1072     buttons(0)
1073 {
1074 }
1075
1076 FGInput::mouse_mode::~mouse_mode ()
1077 {
1078                                 // FIXME: memory leak
1079 //   for (int i = 0; i < KEYMOD_MAX; i++) {
1080 //     int j;
1081 //     for (j = 0; i < x_bindings[i].size(); j++)
1082 //       delete bindings[i][j];
1083 //     for (j = 0; j < y_bindings[i].size(); j++)
1084 //       delete bindings[i][j];
1085 //   }
1086   delete [] buttons;
1087 }
1088
1089
1090 \f
1091 ////////////////////////////////////////////////////////////////////////
1092 // Implementation of FGInput::mouse
1093 ////////////////////////////////////////////////////////////////////////
1094
1095 FGInput::mouse::mouse ()
1096   : x(-1),
1097     y(-1),
1098     nModes(1),
1099     current_mode(0),
1100     modes(0)
1101 {
1102 }
1103
1104 FGInput::mouse::~mouse ()
1105 {
1106   delete [] modes;
1107 }
1108
1109 ////////////////////////////////////////////////////////////////////////
1110 // Implementation of OS callbacks.
1111 ////////////////////////////////////////////////////////////////////////
1112
1113 void keyHandler(int key, int keymod, int mousex, int mousey)
1114 {
1115     if((keymod & KEYMOD_RELEASED) == 0)
1116         if(puKeyboard(key, PU_DOWN))
1117             return;
1118
1119     if(default_input)
1120         default_input->doKey(key, keymod, mousex, mousey);
1121 }
1122
1123 void mouseClickHandler(int button, int updown, int x, int y)
1124 {
1125     if(default_input)
1126         default_input->doMouseClick(button, updown, x, y);
1127 }
1128
1129 void mouseMotionHandler(int x, int y)
1130 {
1131     if (default_input != 0)
1132         default_input->doMouseMotion(x, y);
1133 }