input-remapper/keymapper/dev/injector.py

432 lines
15 KiB
Python
Raw Normal View History

2020-11-02 20:57:28 +00:00
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# key-mapper - GUI for device specific keyboard mappings
# Copyright (C) 2020 sezanzeb <proxima@hip70890b.de>
#
# This file is part of key-mapper.
#
# key-mapper is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# key-mapper is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with key-mapper. If not, see <https://www.gnu.org/licenses/>.
2020-11-22 12:58:56 +00:00
"""Keeps injecting keycodes in the background based on the mapping."""
2020-11-02 20:57:28 +00:00
import re
import asyncio
import time
import subprocess
2020-11-18 12:17:49 +00:00
import multiprocessing
2020-11-02 20:57:28 +00:00
2020-11-05 00:24:56 +00:00
import evdev
2020-12-03 20:36:15 +00:00
from evdev.ecodes import EV_KEY, EV_ABS, EV_REL
2020-11-05 00:24:56 +00:00
2020-11-02 20:57:28 +00:00
from keymapper.logger import logger
2020-11-22 20:41:29 +00:00
from keymapper.getdevices import get_devices
from keymapper.state import system_mapping
2020-12-02 19:48:23 +00:00
from keymapper.dev.keycode_mapper import handle_keycode, \
should_map_event_as_btn
from keymapper.dev.ev_abs_mapper import ev_abs_mapper, JOYSTICK
2020-12-04 13:38:41 +00:00
from keymapper.dev.macros import parse, is_this_a_macro
2020-11-18 19:03:37 +00:00
DEV_NAME = 'key-mapper'
CLOSE = 0
def is_numlock_on():
"""Get the current state of the numlock."""
xset_q = subprocess.check_output(['xset', 'q']).decode()
num_lock_status = re.search(
r'Num Lock:\s+(.+?)\s',
xset_q
)
2020-11-22 20:41:29 +00:00
if num_lock_status is not None:
return num_lock_status[1] == 'on'
2020-11-22 20:41:29 +00:00
return False
2020-12-16 11:57:09 +00:00
def set_numlock(state):
"""Set the numlock to a given state of True or False."""
value = {
True: 'on',
False: 'off'
}[state]
try:
2020-12-16 11:57:09 +00:00
subprocess.check_output(['numlockx', value])
except FileNotFoundError:
# doesn't seem to be installed everywhere
2020-12-03 19:37:36 +00:00
logger.debug('numlockx not found')
def ensure_numlock(func):
2020-11-22 20:41:29 +00:00
"""Decorator to reset the numlock to its initial state afterwards."""
def wrapped(*args, **kwargs):
# for some reason, grabbing a device can modify the num lock state.
# remember it and apply back later
numlock_before = is_numlock_on()
result = func(*args, **kwargs)
2020-12-16 11:57:09 +00:00
set_numlock(numlock_before)
return result
return wrapped
2020-11-18 12:17:49 +00:00
class KeycodeInjector:
2020-11-28 14:43:24 +00:00
"""Keeps injecting keycodes in the background based on the mapping.
Is a process to make it non-blocking for the rest of the code and to
make running multiple injector easier. There is one procss per
hardware-device that is being mapped.
"""
2020-12-06 18:54:02 +00:00
regrab_timeout = 0.5
2020-11-28 14:43:24 +00:00
def __init__(self, device, mapping):
"""Start injecting keycodes based on custom_mapping.
Parameters
----------
device : string
the name of the device as available in get_device
"""
self.device = device
2020-11-28 14:43:24 +00:00
self.mapping = mapping
self._process = None
self._msg_pipe = multiprocessing.Pipe()
self._key_to_code = self._map_keys_to_codes()
2020-12-04 13:38:41 +00:00
self.stopped = False
2020-12-04 13:38:41 +00:00
# when moving the joystick and then staying at a position, no
# events will be written anymore. Remember the last value the
# joystick reported, because it is still remaining at that
# position.
2020-12-03 20:36:15 +00:00
self.abs_state = [0, 0, 0, 0]
2020-12-01 23:02:41 +00:00
def _map_keys_to_codes(self):
2020-12-04 13:38:41 +00:00
"""To quickly get target keycodes during operation."""
key_to_code = {}
for key, output in self.mapping:
2020-12-04 13:38:41 +00:00
if is_this_a_macro(output):
continue
target_code = system_mapping.get(output)
if target_code is None:
2020-12-04 13:38:41 +00:00
logger.error('Don\'t know what %s is', output)
continue
key_to_code[key] = target_code
return key_to_code
2020-12-04 13:38:41 +00:00
2020-11-28 14:43:24 +00:00
def start_injecting(self):
"""Start injecting keycodes."""
2020-12-04 13:38:41 +00:00
if self.stopped or self._process is not None:
# So that there is less concern about integrity when putting
# stuff into self. Each injector object can only be
# started once.
raise Exception('Please construct a new injector instead')
if self.device not in get_devices():
logger.error('Cannot inject for unknown device "%s"', self.device)
return
2020-11-28 14:43:24 +00:00
self._process = multiprocessing.Process(target=self._start_injecting)
self._process.start()
2020-12-02 19:48:23 +00:00
def map_abs_to_rel(self, capabilities):
2020-12-02 18:33:31 +00:00
"""Check if joystick movements can and should be mapped."""
# mapping buttons only works without ABS events in the capabilities,
# possibly due to some intentional constraints in the os. So always
# do this without the option to configure, if it is possible.
return evdev.ecodes.ABS_X in capabilities.get(EV_ABS, [])
2020-11-28 14:43:24 +00:00
def _prepare_device(self, path):
"""Try to grab the device, return if not needed/possible.
Also return if ABS events are changed to REL mouse movements,
because the capabilities of the returned device are changed
so this cannot be checked later anymore.
"""
2020-12-03 19:37:36 +00:00
try:
device = evdev.InputDevice(path)
except FileNotFoundError:
return None, False
2020-11-28 14:43:24 +00:00
capabilities = device.capabilities(absinfo=False)
2020-11-28 14:43:24 +00:00
needed = False
for (ev_type, code, _), _ in self.mapping:
if code in capabilities.get(ev_type, []):
2020-12-02 19:48:23 +00:00
needed = True
break
2020-11-30 21:42:53 +00:00
2020-12-02 19:48:23 +00:00
abs_to_rel = self.map_abs_to_rel(capabilities)
2020-12-02 19:48:23 +00:00
if abs_to_rel:
needed = True
2020-11-28 14:43:24 +00:00
if not needed:
# skipping reading and checking on events from those devices
# may be beneficial for performance.
2020-11-29 19:18:00 +00:00
logger.debug('No need to grab %s', path)
return None, False
2020-11-28 14:43:24 +00:00
attempts = 0
while True:
try:
# grab to avoid e.g. the disabled keycode of 10 to confuse
# X, especially when one of the buttons of your mouse also
# uses 10. This also avoids having to load an empty xkb
# symbols file to prevent writing any unwanted keys.
device.grab()
2020-12-03 19:03:53 +00:00
logger.debug('Grab %s', path)
2020-11-28 14:43:24 +00:00
break
except IOError:
attempts += 1
2020-11-30 21:42:53 +00:00
# it might take a little time until the device is free if
# it was previously grabbed.
2020-11-30 17:59:34 +00:00
logger.debug('Failed attemts to grab %s: %d', path, attempts)
2020-11-28 14:43:24 +00:00
if attempts >= 4:
logger.error('Cannot grab %s, it is possibly in use', path)
return None, False
2020-11-28 14:43:24 +00:00
2020-12-06 18:54:02 +00:00
time.sleep(self.regrab_timeout)
2020-11-28 14:43:24 +00:00
2020-12-02 19:48:23 +00:00
return device, abs_to_rel
2020-11-28 14:43:24 +00:00
2020-12-04 13:38:41 +00:00
def _modify_capabilities(self, macros, input_device, abs_to_rel):
"""Adds all used keycodes into a copy of a devices capabilities.
A device with those capabilities can do exactly the stuff it needs
to perform all mappings and macros.
2020-11-28 14:43:24 +00:00
Prameters
---------
2020-12-04 13:38:41 +00:00
macros : dict
maping of int to _Macro
2020-11-28 14:43:24 +00:00
input_device : evdev.InputDevice
2020-12-02 19:48:23 +00:00
abs_to_rel : bool
if ABS capabilities should be removed in favor of REL
2020-11-28 14:43:24 +00:00
"""
ecodes = evdev.ecodes
# copy the capabilities because the uinput is going
2020-11-28 14:43:24 +00:00
# to act like the device.
capabilities = input_device.capabilities(absinfo=False)
2020-11-30 17:59:34 +00:00
if len(self._key_to_code) > 0 or len(macros) > 0:
2020-12-04 13:38:41 +00:00
if capabilities.get(EV_KEY) is None:
capabilities[EV_KEY] = []
2020-11-30 17:59:34 +00:00
2020-12-04 13:38:41 +00:00
# Furthermore, support all injected keycodes
for code in self._key_to_code.values():
if code not in capabilities[EV_KEY]:
capabilities[EV_KEY].append(code)
2020-12-04 13:38:41 +00:00
# and all keycodes that are injected by macros
for macro in macros.values():
capabilities[EV_KEY] += list(macro.get_capabilities())
2020-12-02 19:48:23 +00:00
if abs_to_rel:
2020-12-04 13:38:41 +00:00
del capabilities[EV_ABS]
2020-12-02 20:20:18 +00:00
# those are the requirements to recognize it as mouse
# on my system. REL_X and REL_Y are of course required to
# accept the events that the mouse-movement-mapper writes.
2020-12-03 20:36:15 +00:00
capabilities[EV_REL] = [
evdev.ecodes.REL_X,
evdev.ecodes.REL_Y,
evdev.ecodes.REL_WHEEL,
]
2020-12-04 13:38:41 +00:00
if capabilities.get(EV_KEY) is None:
capabilities[EV_KEY] = []
2020-12-02 20:20:18 +00:00
# for reasons I don't know, it is also required to have
# any keyboard button in capabilities.
2020-12-04 13:38:41 +00:00
capabilities[EV_KEY].append(ecodes.KEY_0)
2020-11-28 14:43:24 +00:00
# just like what python-evdev does in from_device
if ecodes.EV_SYN in capabilities:
del capabilities[ecodes.EV_SYN]
if ecodes.EV_FF in capabilities:
del capabilities[ecodes.EV_FF]
2020-11-28 14:43:24 +00:00
return capabilities
async def _msg_listener(self, loop):
"""Wait for messages from the main process to do special stuff."""
while True:
frame_available = asyncio.Event()
loop.add_reader(self._msg_pipe[0].fileno(), frame_available.set)
await frame_available.wait()
frame_available.clear()
msg = self._msg_pipe[0].recv()
if msg == CLOSE:
logger.debug('Received close signal')
# stop the event loop and cause the process to reach its end
# cleanly. Using .terminate prevents coverage from working.
loop.stop()
return
2020-11-28 14:43:24 +00:00
def _start_injecting(self):
"""The injection worker that keeps injecting until terminated.
Stuff is non-blocking by using asyncio in order to do multiple things
somewhat concurrently.
"""
2020-12-16 11:57:09 +00:00
numlock_state = is_numlock_on()
2020-11-28 14:43:24 +00:00
loop = asyncio.get_event_loop()
coroutines = []
2020-11-18 19:03:37 +00:00
logger.info('Starting injecting the mapping for "%s"', self.device)
2020-11-18 19:03:37 +00:00
paths = get_devices()[self.device]['paths']
2020-11-18 19:03:37 +00:00
# Watch over each one of the potentially multiple devices per hardware
for path in paths:
2020-12-04 13:38:41 +00:00
source, abs_to_rel = self._prepare_device(path)
if source is None:
2020-11-28 14:43:24 +00:00
continue
2020-12-04 13:38:41 +00:00
# each device parses the macros with a different handler
logger.debug('Parsing macros for %s', path)
macros = {}
for key, output in self.mapping:
2020-12-04 13:38:41 +00:00
if is_this_a_macro(output):
macro = parse(output, self.mapping)
2020-12-04 13:52:08 +00:00
if macro is None:
continue
macros[key] = macro
2020-12-04 13:38:41 +00:00
# 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.
2020-11-28 14:43:24 +00:00
uinput = evdev.UInput(
name=f'{DEV_NAME} {self.device}',
phys=DEV_NAME,
2020-12-04 13:38:41 +00:00
events=self._modify_capabilities(macros, source, abs_to_rel)
2020-11-18 19:03:37 +00:00
)
2020-12-06 18:08:09 +00:00
logger.spam(
'Injected capabilities for "%s": %s',
path, uinput.capabilities(verbose=True)
)
2020-12-04 13:38:41 +00:00
def handler(*args, uinput=uinput):
# this ensures that the right uinput is used for macro_write,
# because this is within a loop
self._macro_write(*args, uinput)
for macro in macros.values():
macro.set_handler(handler)
2020-11-30 21:42:53 +00:00
# keycode injection
2020-12-04 13:38:41 +00:00
coroutine = self._keycode_loop(macros, source, uinput, abs_to_rel)
2020-11-28 14:43:24 +00:00
coroutines.append(coroutine)
2020-11-30 21:42:53 +00:00
# mouse movement injection
2020-12-02 19:48:23 +00:00
if abs_to_rel:
self.abs_state[0] = 0
self.abs_state[1] = 0
coroutine = ev_abs_mapper(
self.abs_state,
source,
uinput,
self.mapping
)
2020-11-30 21:42:53 +00:00
coroutines.append(coroutine)
2020-11-28 14:43:24 +00:00
if len(coroutines) == 0:
2020-11-30 21:42:53 +00:00
logger.error('Did not grab any device')
return
2020-11-18 19:03:37 +00:00
coroutines.append(self._msg_listener(loop))
2020-12-16 11:57:09 +00:00
# set the numlock state to what it was before injecting, because
# grabbing devices screws this up
set_numlock(numlock_state)
try:
loop.run_until_complete(asyncio.gather(*coroutines))
except RuntimeError:
# stopped event loop most likely
pass
except OSError as error:
logger.error(str(error))
2020-11-28 14:43:24 +00:00
2020-11-30 21:42:53 +00:00
if len(coroutines) > 0:
logger.debug('asyncio coroutines ended')
2020-12-04 13:38:41 +00:00
def _macro_write(self, code, value, uinput):
"""Handler for macros."""
2020-12-04 13:38:41 +00:00
logger.spam('macro writes code:%s value:%d', code, value)
uinput.write(EV_KEY, code, value)
uinput.syn()
2020-11-30 19:57:09 +00:00
2020-12-04 13:38:41 +00:00
async def _keycode_loop(self, macros, source, uinput, abs_to_rel):
2020-11-28 14:43:24 +00:00
"""Inject keycodes for one of the virtual devices.
2020-12-02 15:17:52 +00:00
Can be stopped by stopping the asyncio loop.
2020-11-28 14:43:24 +00:00
Parameters
----------
2020-12-04 13:38:41 +00:00
macros : int -> _Macro
macro with a handler that writes to the provided uinput
source : evdev.InputDevice
2020-11-28 14:43:24 +00:00
where to read keycodes from
uinput : evdev.UInput
2020-11-28 14:43:24 +00:00
where to write keycodes to
2020-12-02 19:48:23 +00:00
abs_to_rel : bool
if joystick events should be mapped to mouse movements
2020-11-28 14:43:24 +00:00
"""
logger.debug(
'Started injecting into %s, fd %s',
uinput.device.path, uinput.fd
2020-11-28 14:43:24 +00:00
)
2020-12-04 13:38:41 +00:00
async for event in source.async_read_loop():
2020-12-02 19:48:23 +00:00
if abs_to_rel and event.type == EV_ABS and event.code in JOYSTICK:
2020-11-30 18:40:17 +00:00
if event.code == evdev.ecodes.ABS_X:
self.abs_state[0] = event.value
2020-12-03 20:36:15 +00:00
elif event.code == evdev.ecodes.ABS_Y:
self.abs_state[1] = event.value
2020-12-03 20:36:15 +00:00
elif event.code == evdev.ecodes.ABS_RX:
self.abs_state[2] = event.value
elif event.code == evdev.ecodes.ABS_RY:
self.abs_state[3] = event.value
continue
2020-12-02 20:03:59 +00:00
if should_map_event_as_btn(event.type, event.code):
handle_keycode(self._key_to_code, macros, event, uinput)
2020-11-28 14:43:24 +00:00
continue
2020-12-02 19:48:23 +00:00
# forward the rest
uinput.write(event.type, event.code, event.value)
# this already includes SYN events, so need to syn here again
continue
2020-11-28 14:43:24 +00:00
2020-11-28 16:49:32 +00:00
logger.error(
'The injector for "%s" stopped early',
uinput.device.path
2020-11-28 16:49:32 +00:00
)
@ensure_numlock
2020-11-18 19:03:37 +00:00
def stop_injecting(self):
"""Stop injecting keycodes."""
2020-11-30 21:42:53 +00:00
logger.info('Stopping injecting keycodes for device "%s"', self.device)
self._msg_pipe[1].send(CLOSE)
2020-12-04 13:38:41 +00:00
self.stopped = True