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