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