]> git.mxchange.org Git - flightgear.git/blob - src/Input/FGLinuxEventInput.cxx
03e7e05817ee7629d742810516ce84a6bfabd211
[flightgear.git] / src / Input / FGLinuxEventInput.cxx
1 // FGEventInput.cxx -- handle event driven input devices for the Linux O/S
2 //
3 // Written by Torsten Dreyer, started July 2009.
4 //
5 // Copyright (C) 2009 Torsten Dreyer, Torsten (at) t3r _dot_ de
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 #include <cstring>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <poll.h>
31 #include <linux/input.h>
32 #include <dbus/dbus.h>
33 #include <fcntl.h>
34 #include "FGLinuxEventInput.hxx"
35
36
37 struct TypeCode {
38   unsigned type;
39   unsigned code;
40
41   inline unsigned long hashCode() const {
42     return (unsigned long)type << 16 | (unsigned long)code;
43   }
44
45   bool operator < ( const TypeCode other) const {
46     return hashCode() < other.hashCode();
47   }
48 };
49
50 // event to name translation table
51 // events are from include <linux/input.h>
52
53 static struct EventTypes {
54   struct TypeCode typeCode;
55   const char * name;
56 } EVENT_TYPES[] = {
57   { { EV_SYN, SYN_REPORT },     "syn-report" },
58   { { EV_SYN, SYN_CONFIG },     "syn-config" },
59
60   // misc
61   { { EV_KEY, BTN_0 }, "button-0" },
62   { { EV_KEY, BTN_1 }, "button-1" },
63   { { EV_KEY, BTN_2 }, "button-2" },
64   { { EV_KEY, BTN_3 }, "button-3" },
65   { { EV_KEY, BTN_4 }, "button-4" },
66   { { EV_KEY, BTN_5 }, "button-5" },
67   { { EV_KEY, BTN_6 }, "button-6" },
68   { { EV_KEY, BTN_7 }, "button-7" },
69   { { EV_KEY, BTN_8 }, "button-8" },
70   { { EV_KEY, BTN_9 }, "button-9" },
71
72   // mouse
73   { { EV_KEY, BTN_LEFT },    "button-left" },
74   { { EV_KEY, BTN_RIGHT },   "button-right" },
75   { { EV_KEY, BTN_MIDDLE },  "button-middle" },
76   { { EV_KEY, BTN_SIDE },    "button-side" },
77   { { EV_KEY, BTN_EXTRA },   "button-extra" },
78   { { EV_KEY, BTN_FORWARD }, "button-forward" },
79   { { EV_KEY, BTN_BACK },    "button-back" },
80   { { EV_KEY, BTN_TASK },    "button-task" },
81
82   // joystick
83   { { EV_KEY, BTN_TRIGGER }, "button-trigger" },
84   { { EV_KEY, BTN_THUMB },   "button-thumb" },
85   { { EV_KEY, BTN_THUMB2 },  "button-thumb2" },
86   { { EV_KEY, BTN_TOP },     "button-top" },
87   { { EV_KEY, BTN_TOP2 },    "button-top2" },
88   { { EV_KEY, BTN_PINKIE },  "button-pinkie" },
89   { { EV_KEY, BTN_BASE },    "button-base" },
90   { { EV_KEY, BTN_BASE2 },   "button-base2" },
91   { { EV_KEY, BTN_BASE3 },   "button-base3" },
92   { { EV_KEY, BTN_BASE4 },   "button-base4" },
93   { { EV_KEY, BTN_BASE5 },   "button-base5" },
94   { { EV_KEY, BTN_BASE6 },   "button-base6" },
95   { { EV_KEY, BTN_DEAD },    "button-dead" },
96
97   // gamepad
98   { { EV_KEY, BTN_A },      "button-a" },
99   { { EV_KEY, BTN_B },      "button-b" },
100   { { EV_KEY, BTN_C },      "button-c" },
101   { { EV_KEY, BTN_X },      "button-x" },
102   { { EV_KEY, BTN_Y },      "button-y" },
103   { { EV_KEY, BTN_Z },      "button-z" },
104   { { EV_KEY, BTN_TL },     "button-tl" },
105   { { EV_KEY, BTN_TR },     "button-tr" },
106   { { EV_KEY, BTN_TL2 },    "button-tl2" },
107   { { EV_KEY, BTN_TR2 },    "button-tr2" },
108   { { EV_KEY, BTN_SELECT }, "button-select" },
109   { { EV_KEY, BTN_START },  "button-start" },
110   { { EV_KEY, BTN_MODE },   "button-mode" },
111   { { EV_KEY, BTN_THUMBL }, "button-thumbl" },
112   { { EV_KEY, BTN_THUMBR }, "button-thumbr" },
113
114   // digitizer
115   { { EV_KEY, BTN_TOOL_PEN },       "button-pen" },
116   { { EV_KEY, BTN_TOOL_RUBBER },    "button-rubber" },
117   { { EV_KEY, BTN_TOOL_BRUSH },     "button-brush" },
118   { { EV_KEY, BTN_TOOL_PENCIL },    "button-pencil" },
119   { { EV_KEY, BTN_TOOL_AIRBRUSH },  "button-airbrush" },
120   { { EV_KEY, BTN_TOOL_FINGER },    "button-finger" },
121   { { EV_KEY, BTN_TOOL_MOUSE },     "button-mouse" },
122   { { EV_KEY, BTN_TOOL_LENS },      "button-lens" },
123   { { EV_KEY, BTN_TOUCH },          "button-touch" },
124   { { EV_KEY, BTN_STYLUS },         "button-stylus" },
125   { { EV_KEY, BTN_STYLUS2 },        "button-stylus2" },
126   { { EV_KEY, BTN_TOOL_DOUBLETAP }, "button-doubletap" },
127   { { EV_KEY, BTN_TOOL_TRIPLETAP }, "button-trippletap" },
128
129   { { EV_KEY, BTN_WHEEL },          "button-wheel" },
130   { { EV_KEY, BTN_GEAR_DOWN },      "button-gear-down" },
131   { { EV_KEY, BTN_GEAR_UP },        "button-gear-up" },
132
133   { { EV_REL, REL_X },     "rel-x-translate" },
134   { { EV_REL, REL_Y},      "rel-y-translate" },
135   { { EV_REL, REL_Z},      "rel-z-translate" },
136   { { EV_REL, REL_RX},     "rel-x-rotate" },
137   { { EV_REL, REL_RY},     "rel-y-rotate" },
138   { { EV_REL, REL_RZ},     "rel-z-rotate" },
139   { { EV_REL, REL_HWHEEL}, "rel-hwheel" },
140   { { EV_REL, REL_DIAL},   "rel-dial" },
141   { { EV_REL, REL_WHEEL},  "rel-wheel" },
142   { { EV_REL, REL_MISC},   "rel-misc" },
143
144   { { EV_ABS, ABS_X },          "abs-x-translate" },
145   { { EV_ABS, ABS_Y },          "abs-y-translate" },
146   { { EV_ABS, ABS_Z },          "abs-z-translate" },
147   { { EV_ABS, ABS_RX },         "abs-x-rotate" },
148   { { EV_ABS, ABS_RY },         "abs-y-rotate" },
149   { { EV_ABS, ABS_RZ },         "abs-z-rotate" },
150   { { EV_ABS, ABS_THROTTLE },   "abs-throttle" },
151   { { EV_ABS, ABS_RUDDER },     "abs-rudder" },
152   { { EV_ABS, ABS_WHEEL },      "abs-wheel" },
153   { { EV_ABS, ABS_GAS },        "abs-gas" },
154   { { EV_ABS, ABS_BRAKE },      "abs-brake" },
155   { { EV_ABS, ABS_HAT0X },      "abs-hat0-x" },
156   { { EV_ABS, ABS_HAT0Y },      "abs-hat0-y" },
157   { { EV_ABS, ABS_HAT1X },      "abs-hat1-x" },
158   { { EV_ABS, ABS_HAT1Y },      "abs-hat1-y" },
159   { { EV_ABS, ABS_HAT2X },      "abs-hat2-x" },
160   { { EV_ABS, ABS_HAT2Y },      "abs-hat2-y" },
161   { { EV_ABS, ABS_HAT3X },      "abs-hat3-x" },
162   { { EV_ABS, ABS_HAT3Y },      "abs-hat3-y" },
163   { { EV_ABS, ABS_PRESSURE },   "abs-pressure" },
164   { { EV_ABS, ABS_DISTANCE },   "abs-distance" },
165   { { EV_ABS, ABS_TILT_X },     "abs-tilt-x" },
166   { { EV_ABS, ABS_TILT_Y },     "abs-tilt-y" },
167   { { EV_ABS, ABS_TOOL_WIDTH }, "abs-toold-width" },
168   { { EV_ABS, ABS_VOLUME },     "abs-volume" },
169   { { EV_ABS, ABS_MISC },       "abs-misc" },
170
171   { { EV_MSC,  MSC_SERIAL },    "misc-serial" },
172   { { EV_MSC,  MSC_PULSELED },  "misc-pulseled" },
173   { { EV_MSC,  MSC_GESTURE },   "misc-gesture" },
174   { { EV_MSC,  MSC_RAW },       "misc-raw" },
175   { { EV_MSC,  MSC_SCAN },      "misc-scan" },
176
177   // switch
178   { { EV_SW, SW_LID },               "switch-lid" },
179   { { EV_SW, SW_TABLET_MODE },       "switch-tablet-mode" },
180   { { EV_SW, SW_HEADPHONE_INSERT },  "switch-headphone-insert" },
181 #ifdef SW_RFKILL_ALL 
182   { { EV_SW, SW_RFKILL_ALL },        "switch-rfkill" },
183 #endif
184 #ifdef SW_MICROPHONE_INSERT 
185   { { EV_SW, SW_MICROPHONE_INSERT }, "switch-microphone-insert" },
186 #endif
187 #ifdef SW_DOCK
188   { { EV_SW, SW_DOCK },              "switch-dock" },
189 #endif
190
191   { { EV_LED, LED_NUML},     "led-numlock" },
192   { { EV_LED, LED_CAPSL},    "led-capslock" },
193   { { EV_LED, LED_SCROLLL},  "led-scrolllock" },
194   { { EV_LED, LED_COMPOSE},  "led-compose" },
195   { { EV_LED, LED_KANA},     "led-kana" },
196   { { EV_LED, LED_SLEEP},    "led-sleep" },
197   { { EV_LED, LED_SUSPEND},  "led-suspend" },
198   { { EV_LED, LED_MUTE},     "led-mute" },
199   { { EV_LED, LED_MISC},     "led-misc" },
200   { { EV_LED, LED_MAIL},     "led-mail" },
201   { { EV_LED, LED_CHARGING}, "led-charging" }
202
203 };
204
205 static struct enbet {
206   unsigned type;
207   const char * name;
208 } EVENT_NAMES_BY_EVENT_TYPE[] = {
209   { EV_SYN, "syn" },
210   { EV_KEY, "button" },
211   { EV_REL, "rel" },
212   { EV_ABS, "abs" },
213   { EV_MSC, "msc" },
214   { EV_SW, "button" },
215   { EV_LED, "led" },
216   { EV_SND, "snd" },
217   { EV_REP, "rep" },
218   { EV_FF, "ff" },
219   { EV_PWR, "pwr" },
220   { EV_FF_STATUS, "ff-status" }
221 };
222
223
224 class EventNameByEventType : public map<unsigned,const char*> {
225 public:
226   EventNameByEventType() {
227     for( unsigned i = 0; i < sizeof(EVENT_NAMES_BY_EVENT_TYPE)/sizeof(EVENT_NAMES_BY_EVENT_TYPE[0]); i++ )
228       (*this)[EVENT_NAMES_BY_EVENT_TYPE[i].type] = EVENT_NAMES_BY_EVENT_TYPE[i].name;
229   }
230 };
231 static EventNameByEventType EVENT_NAME_BY_EVENT_TYPE;
232
233 class EventNameByType : public map<TypeCode,const char*> {
234 public:
235   EventNameByType() {
236     for( unsigned i = 0; i < sizeof(EVENT_TYPES)/sizeof(EVENT_TYPES[0]); i++ )
237       (*this)[EVENT_TYPES[i].typeCode] = EVENT_TYPES[i].name;
238   }
239 };
240 static EventNameByType EVENT_NAME_BY_TYPE;
241
242
243 struct ltstr {
244   bool operator()(const char * s1, const char * s2 ) const {
245     return string(s1).compare( s2 ) < 0;
246   }
247 };
248
249 class EventTypeByName : public map<const char *,TypeCode,ltstr> {
250 public:
251   EventTypeByName() {
252     for( unsigned i = 0; i < sizeof(EVENT_TYPES)/sizeof(EVENT_TYPES[0]); i++ )
253       (*this)[EVENT_TYPES[i].name] = EVENT_TYPES[i].typeCode;
254   }
255 };
256 static EventTypeByName EVENT_TYPE_BY_NAME;
257
258
259 FGLinuxInputDevice::FGLinuxInputDevice( string aName, string aDevname ) :
260   FGInputDevice(aName),
261   devname( aDevname ),
262   fd(-1)
263 {
264 }
265
266 FGLinuxInputDevice::~FGLinuxInputDevice()
267 {
268   try {
269     Close();
270   } 
271   catch(...) {
272   }
273 }
274
275 FGLinuxInputDevice::FGLinuxInputDevice() :
276   fd(-1)
277 {
278 }
279
280 static inline bool bitSet( unsigned char * buf, unsigned char bit )
281 {
282   return (buf[bit/sizeof(bit)/8] >> (bit%(sizeof(bit)*8))) & 1;
283 }
284
285 void FGLinuxInputDevice::Open()
286 {
287   if( fd != -1 ) return;
288   if( (fd = ::open( devname.c_str(), O_RDWR )) == -1 ) { 
289     throw exception();
290   }
291
292   if( GetGrab() && ioctl( fd, EVIOCGRAB, 2 ) == -1 ) {
293     SG_LOG( SG_INPUT, SG_WARN, "Can't grab " << devname << " for exclusive access" );
294   }
295
296   unsigned char buf[ABS_CNT/sizeof(unsigned char)/8];
297   // get axes maximums
298   if( ioctl( fd, EVIOCGBIT(EV_ABS,ABS_MAX), buf ) == -1 ) {
299     SG_LOG( SG_INPUT, SG_WARN, "Can't get abs-axes for " << devname );
300   } else {
301     for( unsigned i = 0; i < ABS_MAX; i++ ) {
302       if( bitSet( buf, i ) ) {
303         struct input_absinfo ai;
304         if( ioctl(fd, EVIOCGABS(i), &ai) == -1 ) {
305           SG_LOG( SG_INPUT, SG_WARN, "Can't get abs-axes maximums for " << devname );
306           continue;
307         }
308         absinfo[i] = ai;
309       }
310     }
311   }
312 }
313
314 double FGLinuxInputDevice::Normalize( struct input_event & event ) 
315 {
316   if( absinfo.count(event.code) > 0 ) {
317      const struct input_absinfo & ai = absinfo[(unsigned int)event.code];
318      if( ai.maximum == ai.minimum )
319        return 0.0;
320      return ((double)event.value-(double)ai.minimum)/((double)ai.maximum-(double)ai.minimum);
321   } else {
322     return (double)event.value;
323   }
324 }
325
326 void FGLinuxInputDevice::Close()
327 {
328   if( fd != -1 ) {
329     if( GetGrab() && ioctl( fd, EVIOCGRAB, 0 ) != 0 ) {
330       SG_LOG( SG_INPUT, SG_WARN, "Can't ungrab " << devname );
331     }
332     ::close(fd);
333   }
334   fd = -1;
335 }
336
337 void FGLinuxInputDevice::Send( const char * eventName, double value )
338 {
339   if( EVENT_TYPE_BY_NAME.count( eventName ) <= 0 ) {
340     SG_LOG( SG_INPUT, SG_ALERT, "Can't send unknown event " << eventName );
341     return;
342   }
343
344   TypeCode & typeCode = EVENT_TYPE_BY_NAME[ eventName ];
345
346   if( fd == -1 )
347     return;
348
349   input_event evt;
350   evt.type=typeCode.type;
351   evt.code = typeCode.code;
352   evt.value = (long)value;
353   evt.time.tv_sec = 0;
354   evt.time.tv_usec = 0;
355   write( fd, &evt, sizeof(evt) );
356   SG_LOG( SG_INPUT, SG_DEBUG, "Written event " << eventName 
357           << " as type=" << evt.type << ", code=" << evt.code << " value=" << evt.value );
358 }
359
360 static char ugly_buffer[128];
361 const char * FGLinuxInputDevice::TranslateEventName( FGEventData & eventData ) 
362 {
363   FGLinuxEventData & linuxEventData = (FGLinuxEventData&)eventData;
364   TypeCode typeCode;
365   typeCode.type = linuxEventData.type;
366   typeCode.code = linuxEventData.code;
367   if( EVENT_NAME_BY_TYPE.count(typeCode) == 0 ) {
368     // event not known in translation tables
369     if( EVENT_NAME_BY_EVENT_TYPE.count(linuxEventData.type) == 0 ) {
370       // event type not known in translation tables
371       sprintf( ugly_buffer, "unknown-%u-%u", (unsigned)linuxEventData.type, (unsigned)linuxEventData.code );
372       return ugly_buffer;
373     }
374     sprintf( ugly_buffer, "%s-%u", EVENT_NAME_BY_EVENT_TYPE[linuxEventData.type], (unsigned)linuxEventData.code );
375     return ugly_buffer;
376   }
377
378   return EVENT_NAME_BY_TYPE[typeCode];
379 }
380
381 void FGLinuxInputDevice::SetDevname( string name )
382 {
383   this->devname = name; 
384 }
385
386 FGLinuxEventInput::FGLinuxEventInput() : 
387   halcontext(NULL)
388 {
389 }
390
391 FGLinuxEventInput::~FGLinuxEventInput()
392 {
393   if( halcontext != NULL ) {
394     libhal_ctx_shutdown( halcontext, NULL);
395     libhal_ctx_free( halcontext );
396     halcontext = NULL;
397   }
398 }
399
400 #if 0
401 //TODO: enable hotplug support
402 static void DeviceAddedCallback (LibHalContext *ctx, const char *udi)
403 {
404   FGLinuxEventInput * linuxEventInput = (FGLinuxEventInput*)libhal_ctx_get_user_data (ctx);
405   linuxEventInput->AddHalDevice( udi );
406 }
407
408 static void DeviceRemovedCallback (LibHalContext *ctx, const char *udi)
409 {
410 }
411 #endif
412
413 void FGLinuxEventInput::postinit()
414 {
415   FGEventInput::postinit();
416
417   DBusConnection * connection;
418   DBusError dbus_error;
419
420   dbus_error_init(&dbus_error);
421   connection = dbus_bus_get (DBUS_BUS_SYSTEM, &dbus_error);
422   if (dbus_error_is_set(&dbus_error)) {
423     SG_LOG( SG_INPUT, SG_ALERT, "Can't connect to system bus " << dbus_error.message);
424     dbus_error_free (&dbus_error);
425     return;
426   }
427
428   halcontext = libhal_ctx_new();
429
430   libhal_ctx_set_dbus_connection (halcontext, connection );
431   dbus_error_init (&dbus_error);
432
433   if( libhal_ctx_init( halcontext,  &dbus_error )) {
434
435       int num_devices = 0;
436       char ** devices = libhal_find_device_by_capability(halcontext, "input", &num_devices, NULL);
437
438       for ( int i = 0; i < num_devices; i++)
439         AddHalDevice( devices[i] );
440
441       libhal_free_string_array (devices);
442
443 //TODO: enable hotplug support
444 //      libhal_ctx_set_user_data( halcontext, this );
445 //      libhal_ctx_set_device_added( halcontext, DeviceAddedCallback );
446 //      libhal_ctx_set_device_removed( halcontext, DeviceRemovedCallback );
447     } else {
448       if(dbus_error_is_set (&dbus_error) ) {
449         SG_LOG( SG_INPUT, SG_ALERT, "Can't connect to hald: " << dbus_error.message);
450         dbus_error_free (&dbus_error);
451       } else {
452         SG_LOG( SG_INPUT, SG_ALERT, "Can't connect to hald." );
453       }
454
455       libhal_ctx_free (halcontext);
456       halcontext = NULL;
457     }
458 }
459
460 void FGLinuxEventInput::AddHalDevice( const char * udi )
461 {
462   char * device = libhal_device_get_property_string( halcontext, udi, "input.device", NULL);
463   char * product = libhal_device_get_property_string( halcontext, udi, "input.product", NULL);
464
465   if( product != NULL && device != NULL ) 
466     AddDevice( new FGLinuxInputDevice(product, device) );
467   else
468     SG_LOG( SG_INPUT, SG_ALERT, "Can't get device or product property of " << udi );
469
470   if( device != NULL ) libhal_free_string( device );
471   if( product != NULL ) libhal_free_string( product );
472
473 }
474
475 void FGLinuxEventInput::update( double dt )
476 {
477   FGEventInput::update( dt );
478   // index the input devices by the associated fd and prepare
479   // the pollfd array by filling in the file descriptor
480   struct pollfd fds[input_devices.size()];
481   map<int,FGLinuxInputDevice*> devicesByFd;
482   map<int,FGInputDevice*>::const_iterator it;
483   int i;
484   for( i=0, it = input_devices.begin(); it != input_devices.end(); ++it, i++ ) {
485     FGInputDevice* p = (*it).second;
486     int fd = ((FGLinuxInputDevice*)p)->GetFd();
487     fds[i].fd = fd;
488     fds[i].events = POLLIN;
489     devicesByFd[fd] = (FGLinuxInputDevice*)p;
490   }
491
492   int modifiers = fgGetKeyModifiers();
493   // poll all devices until no more events are in the queue
494   // do no more than maxpolls in a single loop to prevent locking
495   int maxpolls = 100;
496   while( maxpolls-- > 0 && ::poll( fds, i, 0 ) > 0 ) {
497     for( unsigned i = 0; i < sizeof(fds)/sizeof(fds[0]); i++ ) {
498       if( fds[i].revents & POLLIN ) {
499
500         // if this device reports data ready, it should be a input_event struct
501         struct input_event event;
502
503         if( read( fds[i].fd, &event, sizeof(event) ) != sizeof(event) )
504           continue;
505
506         FGLinuxEventData eventData( event, dt, modifiers );
507
508         if( event.type == EV_ABS )
509           eventData.value = devicesByFd[fds[i].fd]->Normalize( event );
510
511         // let the FGInputDevice handle the data
512         devicesByFd[fds[i].fd]->HandleEvent( eventData );
513       }
514     }
515   }
516 }