def test_gamepad_purpose_none_2(self): # forward abs joystick events for the left joystick only custom_mapping.set('gamepad.joystick.left_purpose', NONE) config.set('gamepad.joystick.right_purpose', MOUSE) self.injector = Injector(groups.find(name='gamepad'), custom_mapping) self.injector.context = Context(custom_mapping) path = '/dev/input/event30' device = self.injector._grab_device(path) # the right joystick maps as mouse, so it is grabbed # even with an empty mapping self.assertIsNotNone(device) gamepad = classify(device) == GAMEPAD self.assertTrue(gamepad) capabilities = self.injector._construct_capabilities(gamepad) self.assertNotIn(EV_ABS, capabilities) self.assertIn(EV_REL, capabilities) custom_mapping.change(Key(EV_KEY, BTN_A, 1), 'a') device = self.injector._grab_device(path) gamepad = classify(device) == GAMEPAD self.assertIsNotNone(device) self.assertTrue(gamepad) capabilities = self.injector._construct_capabilities(gamepad) self.assertNotIn(EV_ABS, capabilities) self.assertIn(EV_REL, capabilities) self.assertIn(EV_KEY, capabilities)
def test_adds_ev_key(self): # for some reason, having any EV_KEY capability is needed to # be able to control the mouse. it probably wants the mouse click. custom_mapping.change(Key(EV_KEY, BTN_A, 1), 'a') self.injector = Injector(groups.find(name='gamepad'), custom_mapping) custom_mapping.set('gamepad.joystick.left_purpose', MOUSE) self.injector.context = Context(custom_mapping) """ABS device without any key capability""" path = self.new_gamepad_path gamepad_template = copy.deepcopy(fixtures['/dev/input/event30']) fixtures[path] = { 'name': 'qux 2', 'phys': 'abcd', 'info': '1234', 'capabilities': gamepad_template['capabilities'] } del fixtures[path]['capabilities'][EV_KEY] device = self.injector._grab_device(path) # no reason to grab, BTN_A capability is missing in the device self.assertIsNone(device) """ABS device with a btn_mouse capability""" path = self.new_gamepad_path gamepad_template = copy.deepcopy(fixtures['/dev/input/event30']) fixtures[path] = { 'name': 'qux 3', 'phys': 'abcd', 'info': '1234', 'capabilities': gamepad_template['capabilities'] } fixtures[path]['capabilities'][EV_KEY].append(BTN_LEFT) fixtures[path]['capabilities'][EV_KEY].append(KEY_A) device = self.injector._grab_device(path) gamepad = classify(device) == GAMEPAD capabilities = self.injector._construct_capabilities(gamepad) self.assertIn(EV_KEY, capabilities) self.assertIn(evdev.ecodes.BTN_MOUSE, capabilities[EV_KEY]) self.assertIn(evdev.ecodes.KEY_A, capabilities[EV_KEY]) """a gamepad""" path = '/dev/input/event30' device = self.injector._grab_device(path) gamepad = classify(device) == GAMEPAD self.assertIn(EV_KEY, device.capabilities()) self.assertNotIn(evdev.ecodes.BTN_MOUSE, device.capabilities()[EV_KEY]) capabilities = self.injector._construct_capabilities(gamepad) self.assertIn(EV_KEY, capabilities) self.assertGreater(len(capabilities), 1) self.assertIn(evdev.ecodes.BTN_MOUSE, capabilities[EV_KEY])
async def _event_consumer(self, source, forward_to): """Reads input events to inject keycodes or talk to the event_producer. Can be stopped by stopping the asyncio loop. This loop reads events from a single device only. Other devnodes may be present for the hardware device, in which case this needs to be started multiple times. Parameters ---------- source : evdev.InputDevice where to read keycodes from forward_to : evdev.UInput where to write keycodes to that were not mapped to anything. Should be an UInput with capabilities that work for all forwarded events, so ideally they should be copied from source. """ logger.debug('Started consumer to inject for %s, fd %s', source.path, source.fd) gamepad = classify(source) == GAMEPAD keycode_handler = KeycodeMapper(self.context, source, forward_to) async for event in source.async_read_loop(): if self._event_producer.is_handled(event): # the event_producer will take care of it self._event_producer.notify(event) continue # for mapped stuff if utils.should_map_as_btn(event, self.context.mapping, gamepad): will_report_key_up = utils.will_report_key_up(event) keycode_handler.handle_keycode(event) if not will_report_key_up: # simulate a key-up event if no down event arrives anymore. # this may release macros, combinations or keycodes. release = evdev.InputEvent(0, 0, event.type, event.code, 0) self._event_producer.debounce( debounce_id=(event.type, event.code, event.value), func=keycode_handler.handle_keycode, args=(release, False), ticks=3, ) continue # forward the rest forward_to.write(event.type, event.code, event.value) # this already includes SYN events, so need to syn here again # This happens all the time in tests because the async_read_loop # stops when there is nothing to read anymore. Otherwise tests # would block. logger.error('The consumer for "%s" stopped early', source.path)
def _grab_device(self, path): """Try to grab the device, return None if not needed/possible. Without grab, original events from it would reach the display server even though they are mapped. """ try: device = evdev.InputDevice(path) except (FileNotFoundError, OSError): logger.error('Could not find "%s"', path) return None capabilities = device.capabilities(absinfo=False) needed = False for key, _ in self.context.mapping: if is_in_capabilities(key, capabilities): logger.debug('Grabbing "%s" because of "%s"', path, key) needed = True break gamepad = classify(device) == GAMEPAD if gamepad and self.context.maps_joystick(): logger.debug('Grabbing "%s" because of maps_joystick', path) needed = True if not needed: # skipping reading and checking on events from those devices # may be beneficial for performance. logger.debug('No need to grab %s', path) return None attempts = 0 while True: try: device.grab() logger.debug('Grab %s', path) break except IOError as error: attempts += 1 # it might take a little time until the device is free if # it was previously grabbed. logger.debug('Failed attempts to grab %s: %d', path, attempts) if attempts >= 10: logger.error('Cannot grab %s, it is possibly in use', path) logger.error(str(error)) return None time.sleep(self.regrab_timeout) return device
def test_grab(self): # path is from the fixtures path = '/dev/input/event10' custom_mapping.change(Key(EV_KEY, 10, 1), 'a') self.injector = Injector(groups.find(key='Foo Device 2'), custom_mapping) # this test needs to pass around all other constraints of # _grab_device self.injector.context = Context(custom_mapping) device = self.injector._grab_device(path) gamepad = classify(device) == GAMEPAD self.assertFalse(gamepad) self.assertEqual(self.failed, 2) # success on the third try self.assertEqual(device.name, fixtures[path]['name'])
def test_gamepad_purpose_none(self): # forward abs joystick events custom_mapping.set('gamepad.joystick.left_purpose', NONE) config.set('gamepad.joystick.right_purpose', NONE) self.injector = Injector(groups.find(name='gamepad'), custom_mapping) self.injector.context = Context(custom_mapping) path = '/dev/input/event30' device = self.injector._grab_device(path) self.assertIsNone(device) # no capability is used, so it won't grab custom_mapping.change(Key(EV_KEY, BTN_A, 1), 'a') device = self.injector._grab_device(path) self.assertIsNotNone(device) gamepad = classify(device) == GAMEPAD self.assertTrue(gamepad) capabilities = self.injector._construct_capabilities(gamepad) self.assertNotIn(EV_ABS, capabilities)
def test_gamepad_capabilities(self): self.injector = Injector(groups.find(name='gamepad'), custom_mapping) # give the injector a reason to grab the device custom_mapping.set('gamepad.joystick.left_purpose', MOUSE) self.injector.context = Context(custom_mapping) path = '/dev/input/event30' device = self.injector._grab_device(path) gamepad = classify(device) == GAMEPAD self.assertIsNotNone(device) self.assertTrue(gamepad) capabilities = self.injector._construct_capabilities(gamepad) self.assertNotIn(EV_ABS, capabilities) self.assertIn(EV_REL, capabilities) self.assertIn(evdev.ecodes.REL_X, capabilities.get(EV_REL)) self.assertIn(evdev.ecodes.REL_Y, capabilities.get(EV_REL)) self.assertIn(evdev.ecodes.REL_WHEEL, capabilities.get(EV_REL)) self.assertIn(evdev.ecodes.REL_HWHEEL, capabilities.get(EV_REL)) self.assertIn(EV_KEY, capabilities) self.assertIn(evdev.ecodes.BTN_LEFT, capabilities[EV_KEY])
def run(self): """The injection worker that keeps injecting until terminated. Stuff is non-blocking by using asyncio in order to do multiple things somewhat concurrently. Use this function as starting point in a process. It creates the loops needed to read and map events and keeps running them. """ logger.info('Starting injecting the mapping for "%s"', self.group.key) # create a new event loop, because somehow running an infinite loop # that sleeps on iterations (event_producer) in one process causes # another injection process to screw up reading from the grabbed # device. loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) # create this within the process after the event loop creation, # so that the macros use the correct loop self.context = Context(self.mapping) # grab devices as early as possible. If events appear that won't get # released anymore before the grab they appear to be held down # forever sources = self._grab_devices() self._event_producer = EventProducer(self.context) numlock_state = is_numlock_on() coroutines = [] # where mapped events go to. # See the Context docstring on why this is needed. self.context.uinput = evdev.UInput( name=self.get_udev_name(self.group.key, 'mapped'), phys=DEV_NAME, events=self._construct_capabilities(GAMEPAD in self.group.types)) for source in sources: # certain capabilities can have side effects apparently. with an # EV_ABS capability, EV_REL won't move the mouse pointer anymore. # so don't merge all InputDevices into one UInput device. gamepad = classify(source) == GAMEPAD forward_to = evdev.UInput(name=self.get_udev_name( source.name, 'forwarded'), phys=DEV_NAME, events=self._copy_capabilities(source)) # actual reading of events coroutines.append(self._event_consumer(source, forward_to)) # The event source of the current iteration will deliver events # that are needed for this. It is that one that will be mapped # to a mouse-like devnode. if gamepad and self.context.joystick_as_mouse(): self._event_producer.set_abs_range_from(source) if len(coroutines) == 0: logger.error('Did not grab any device') self._msg_pipe[0].send(NO_GRAB) return coroutines.append(self._msg_listener()) # run besides this stuff coroutines.append(self._event_producer.run()) # set the numlock state to what it was before injecting, because # grabbing devices screws this up set_numlock(numlock_state) self._msg_pipe[0].send(OK) try: loop.run_until_complete(asyncio.gather(*coroutines)) except RuntimeError: # stopped event loop most likely pass except OSError as error: logger.error(str(error)) if len(coroutines) > 0: # expected when stop_injecting is called, # during normal operation as well as tests this point is not # reached otherwise. logger.debug('asyncio coroutines ended') for source in sources: # ungrab at the end to make the next injection process not fail # its grabs source.ungrab()
def test_classify(self): # properly detects if the device is a gamepad EV_ABS = evdev.ecodes.EV_ABS EV_KEY = evdev.ecodes.EV_KEY EV_REL = evdev.ecodes.EV_REL class FakeDevice: def __init__(self, capabilities): self.c = capabilities def capabilities(self, absinfo): assert not absinfo return self.c """gamepads""" self.assertEqual( classify( FakeDevice({ EV_ABS: [evdev.ecodes.ABS_X, evdev.ecodes.ABS_Y], EV_KEY: [evdev.ecodes.BTN_A] })), GAMEPAD) """mice""" self.assertEqual( classify( FakeDevice({ EV_REL: [ evdev.ecodes.REL_X, evdev.ecodes.REL_Y, evdev.ecodes.REL_WHEEL ], EV_KEY: [evdev.ecodes.BTN_LEFT] })), MOUSE) """keyboard""" self.assertEqual(classify(FakeDevice({EV_KEY: [evdev.ecodes.KEY_A]})), KEYBOARD) """touchpads""" self.assertEqual( classify( FakeDevice({ EV_KEY: [evdev.ecodes.KEY_A], EV_ABS: [evdev.ecodes.ABS_MT_POSITION_X] })), TOUCHPAD) """graphics tablets""" self.assertEqual( classify( FakeDevice({ EV_ABS: [evdev.ecodes.ABS_X, evdev.ecodes.ABS_Y], EV_KEY: [evdev.ecodes.BTN_STYLUS] })), GRAPHICS_TABLET) """weird combos""" self.assertEqual( classify( FakeDevice({ EV_ABS: [evdev.ecodes.ABS_X, evdev.ecodes.ABS_Y], EV_KEY: [evdev.ecodes.KEY_1] })), UNKNOWN) self.assertEqual( classify( FakeDevice({ EV_ABS: [evdev.ecodes.ABS_X], EV_KEY: [evdev.ecodes.BTN_A] })), UNKNOWN) self.assertEqual(classify(FakeDevice({EV_KEY: [evdev.ecodes.BTN_A]})), UNKNOWN) self.assertEqual(classify(FakeDevice({EV_ABS: [evdev.ecodes.ABS_X]})), UNKNOWN)