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