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