]> git.mxchange.org Git - flightgear.git/blob - src/Input/FGLinuxEventInput.cxx
Stop the property tree from keeping a shadow of the deleted input properties, as...
[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 #include <libudev.h>
31 #include <poll.h>
32 #include <linux/input.h>
33 #include <fcntl.h>
34
35 #include <string.h>
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 std::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 std::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 std::string(s1).compare( s2 ) < 0;
246   }
247 };
248
249 class EventTypeByName : public std::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( std::string aName, std::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 bit )
281 {
282   return (buf[bit/sizeof(unsigned char)/8] >> (bit%(sizeof(unsigned char)*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 std::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   {
297     unsigned char buf[ABS_CNT/sizeof(unsigned char)/8];
298     // get axes maximums
299     if( ioctl( fd, EVIOCGBIT(EV_ABS,ABS_MAX), buf ) == -1 ) {
300       SG_LOG( SG_INPUT, SG_WARN, "Can't get abs-axes for " << devname );
301     } else {
302       for( unsigned i = 0; i < ABS_MAX; i++ ) {
303         if( bitSet( buf, i ) ) {
304           struct input_absinfo ai;
305           if( ioctl(fd, EVIOCGABS(i), &ai) == -1 ) {
306             SG_LOG( SG_INPUT, SG_WARN, "Can't get abs-axes maximums for " << devname );
307             continue;
308           }
309           absinfo[i] = ai;
310 /*
311           SG_LOG( SG_INPUT, SG_INFO, "Axis #" << i <<
312             ": value=" << ai.value << 
313             ": minimum=" << ai.minimum << 
314             ": maximum=" << ai.maximum << 
315             ": fuzz=" << ai.fuzz << 
316             ": flat=" << ai.flat << 
317             ": resolution=" << ai.resolution );
318 */
319
320           // kick an initial event
321           struct input_event event;
322           event.type = EV_ABS;
323           event.code = i;
324           event.value = ai.value;
325           FGLinuxEventData eventData( event, 0, 0 );
326           eventData.value = Normalize( event );
327           HandleEvent(eventData);
328         }
329       }
330     }
331   }
332   {
333     unsigned char mask[KEY_CNT/sizeof(unsigned char)/8];
334     unsigned char flag[KEY_CNT/sizeof(unsigned char)/8];
335     memset(mask,0,sizeof(mask));
336     memset(flag,0,sizeof(flag));
337     if( ioctl( fd, EVIOCGKEY(sizeof(flag)), flag ) == -1 ||
338         ioctl( fd, EVIOCGBIT(EV_KEY, sizeof(mask)), mask ) == -1 ) {
339       SG_LOG( SG_INPUT, SG_WARN, "Can't get keys for " << devname );
340     } else {
341       for( unsigned i = 0; i < KEY_MAX; i++ ) {
342         if( bitSet( mask, i ) ) {
343           struct input_event event;
344           event.type = EV_KEY;
345           event.code = i;
346           event.value = bitSet(flag,i);
347           FGLinuxEventData eventData( event, 0, 0 );
348           HandleEvent(eventData);
349         }
350       }
351     }
352   }
353   {
354     unsigned char buf[SW_CNT/sizeof(unsigned char)/8];
355     if( ioctl( fd, EVIOCGSW(sizeof(buf)), buf ) == -1 ) {
356       SG_LOG( SG_INPUT, SG_WARN, "Can't get switches for " << devname );
357     } else {
358       for( unsigned i = 0; i < SW_MAX; i++ ) {
359         if( bitSet( buf, i ) ) {
360           struct input_event event;
361           event.type = EV_SW;
362           event.code = i;
363           event.value = 1;
364           FGLinuxEventData eventData( event, 0, 0 );
365           HandleEvent(eventData);
366         }
367       }
368     }
369   }
370 }
371
372 double FGLinuxInputDevice::Normalize( struct input_event & event ) 
373 {
374   if( absinfo.count(event.code) > 0 ) {
375      const struct input_absinfo & ai = absinfo[(unsigned int)event.code];
376      if( ai.maximum == ai.minimum )
377        return 0.0;
378      return ((double)event.value-(double)ai.minimum)/((double)ai.maximum-(double)ai.minimum);
379   } else {
380     return (double)event.value;
381   }
382 }
383
384 void FGLinuxInputDevice::Close()
385 {
386   if( fd != -1 ) {
387     if( GetGrab() && ioctl( fd, EVIOCGRAB, 0 ) != 0 ) {
388       SG_LOG( SG_INPUT, SG_WARN, "Can't ungrab " << devname );
389     }
390     ::close(fd);
391   }
392   fd = -1;
393 }
394
395 void FGLinuxInputDevice::Send( const char * eventName, double value )
396 {
397   if( EVENT_TYPE_BY_NAME.count( eventName ) <= 0 ) {
398     SG_LOG( SG_INPUT, SG_ALERT, "Can't send unknown event " << eventName );
399     return;
400   }
401
402   TypeCode & typeCode = EVENT_TYPE_BY_NAME[ eventName ];
403
404   if( fd == -1 )
405     return;
406
407   input_event evt;
408   evt.type=typeCode.type;
409   evt.code = typeCode.code;
410   evt.value = (long)value;
411   evt.time.tv_sec = 0;
412   evt.time.tv_usec = 0;
413   write( fd, &evt, sizeof(evt) );
414   SG_LOG( SG_INPUT, SG_DEBUG, "Written event " << eventName 
415           << " as type=" << evt.type << ", code=" << evt.code << " value=" << evt.value );
416 }
417
418 static char ugly_buffer[128];
419 const char * FGLinuxInputDevice::TranslateEventName( FGEventData & eventData ) 
420 {
421   FGLinuxEventData & linuxEventData = (FGLinuxEventData&)eventData;
422   TypeCode typeCode;
423   typeCode.type = linuxEventData.type;
424   typeCode.code = linuxEventData.code;
425   if( EVENT_NAME_BY_TYPE.count(typeCode) == 0 ) {
426     // event not known in translation tables
427     if( EVENT_NAME_BY_EVENT_TYPE.count(linuxEventData.type) == 0 ) {
428       // event type not known in translation tables
429       sprintf( ugly_buffer, "unknown-%u-%u", (unsigned)linuxEventData.type, (unsigned)linuxEventData.code );
430       return ugly_buffer;
431     }
432     sprintf( ugly_buffer, "%s-%u", EVENT_NAME_BY_EVENT_TYPE[linuxEventData.type], (unsigned)linuxEventData.code );
433     return ugly_buffer;
434   }
435
436   return EVENT_NAME_BY_TYPE[typeCode];
437 }
438
439 void FGLinuxInputDevice::SetDevname( const std::string & name )
440 {
441   this->devname = name; 
442 }
443
444 FGLinuxEventInput::FGLinuxEventInput()
445 {
446 }
447
448 FGLinuxEventInput::~FGLinuxEventInput()
449 {
450 }
451
452 void FGLinuxEventInput::postinit()
453 {
454   FGEventInput::postinit();
455
456   struct udev * udev = udev_new();
457
458   struct udev_enumerate *enumerate = udev_enumerate_new(udev);
459   udev_enumerate_add_match_subsystem(enumerate, "input");
460   udev_enumerate_scan_devices(enumerate);
461   struct udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate);
462   struct udev_list_entry *dev_list_entry;
463
464   udev_list_entry_foreach(dev_list_entry, devices) {
465     const char * path = udev_list_entry_get_name(dev_list_entry);
466     struct udev_device *dev = udev_device_new_from_syspath(udev, path);
467     const char * node = udev_device_get_devnode(dev);
468  
469     dev = udev_device_get_parent( dev );
470     const char * name = udev_device_get_sysattr_value(dev,"name");
471
472     SG_LOG(SG_INPUT,SG_DEBUG, "name=" << (name?name:"<null>") << ", node=" << (node?node:"<null>"));
473     if( name && node )
474       AddDevice( new FGLinuxInputDevice(name, node) );
475
476     udev_device_unref(dev);
477   }
478
479   udev_unref(udev);
480
481 }
482
483 void FGLinuxEventInput::update( double dt )
484 {
485   FGEventInput::update( dt );
486   // index the input devices by the associated fd and prepare
487   // the pollfd array by filling in the file descriptor
488   struct pollfd fds[input_devices.size()];
489   std::map<int,FGLinuxInputDevice*> devicesByFd;
490   std::map<int,FGInputDevice*>::const_iterator it;
491   int i;
492   for( i=0, it = input_devices.begin(); it != input_devices.end(); ++it, i++ ) {
493     FGInputDevice* p = (*it).second;
494     int fd = ((FGLinuxInputDevice*)p)->GetFd();
495     fds[i].fd = fd;
496     fds[i].events = POLLIN;
497     devicesByFd[fd] = (FGLinuxInputDevice*)p;
498   }
499
500   int modifiers = fgGetKeyModifiers();
501   // poll all devices until no more events are in the queue
502   // do no more than maxpolls in a single loop to prevent locking
503   int maxpolls = 100;
504   while( maxpolls-- > 0 && ::poll( fds, i, 0 ) > 0 ) {
505     for( unsigned i = 0; i < sizeof(fds)/sizeof(fds[0]); i++ ) {
506       if( fds[i].revents & POLLIN ) {
507
508         // if this device reports data ready, it should be a input_event struct
509         struct input_event event;
510
511         if( read( fds[i].fd, &event, sizeof(event) ) != sizeof(event) )
512           continue;
513
514         FGLinuxEventData eventData( event, dt, modifiers );
515
516         if( event.type == EV_ABS )
517           eventData.value = devicesByFd[fds[i].fd]->Normalize( event );
518
519         // let the FGInputDevice handle the data
520         devicesByFd[fds[i].fd]->HandleEvent( eventData );
521       }
522     }
523   }
524 }
525