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