input-remapper/inputremapper/injection/injector.py

403 lines
14 KiB
Python
Raw Normal View History

2020-11-02 20:57:28 +00:00
#!/usr/bin/python3
# -*- coding: utf-8 -*-
2022-01-01 12:00:49 +00:00
# input-remapper - GUI for device specific keyboard mappings
2022-01-01 12:52:33 +00:00
# Copyright (C) 2022 sezanzeb <proxima@sezanzeb.de>
2020-11-02 20:57:28 +00:00
#
2022-01-01 12:00:49 +00:00
# This file is part of input-remapper.
2020-11-02 20:57:28 +00:00
#
2022-01-01 12:00:49 +00:00
# input-remapper is free software: you can redistribute it and/or modify
2020-11-02 20:57:28 +00:00
# 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.
#
2022-01-01 12:00:49 +00:00
# input-remapper is distributed in the hope that it will be useful,
2020-11-02 20:57:28 +00:00
# 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
2022-01-01 12:00:49 +00:00
# along with input-remapper. If not, see <https://www.gnu.org/licenses/>.
2020-11-02 20:57:28 +00:00
2022-01-31 19:58:37 +00:00
"""Keeps injecting keycodes in the background based on the preset."""
2020-11-02 20:57:28 +00:00
2022-01-31 19:58:37 +00:00
import os
import sys
import asyncio
import time
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
2022-01-31 19:58:37 +00:00
from typing import Dict, List, Optional
from inputremapper.configs.preset import Preset
2022-01-01 12:00:49 +00:00
from inputremapper.logger import logger
2022-01-31 19:58:37 +00:00
from inputremapper.groups import classify, GAMEPAD, _Group
2022-01-01 12:00:49 +00:00
from inputremapper.injection.context import Context
from inputremapper.injection.numlock import set_numlock, is_numlock_on, ensure_numlock
2022-04-17 10:19:23 +00:00
from inputremapper.injection.event_reader import EventReader
2022-01-31 19:58:37 +00:00
from inputremapper.event_combination import EventCombination
2020-11-18 19:03:37 +00:00
2022-01-31 19:58:37 +00:00
CapabilitiesDict = Dict[int, List[int]]
GroupSources = List[evdev.InputDevice]
2020-11-18 19:03:37 +00:00
2022-01-01 12:00:49 +00:00
DEV_NAME = "input-remapper"
2021-01-07 16:15:12 +00:00
# messages
CLOSE = 0
UPGRADE_EVDEV = 7
2021-01-07 16:15:12 +00:00
# states
UNKNOWN = -1
STARTING = 2
FAILED = 3
RUNNING = 4
STOPPED = 5
# for both states and messages
NO_GRAB = 6
2022-01-31 19:58:37 +00:00
def is_in_capabilities(
combination: EventCombination, capabilities: CapabilitiesDict
) -> bool:
"""Are this combination or one of its sub keys in the capabilities?"""
for event in combination:
if event.code in capabilities.get(event.type, []):
2020-12-31 20:46:57 +00:00
return True
return False
2022-01-31 19:58:37 +00:00
def get_udev_name(name: str, suffix: str) -> str:
"""Make sure the generated name is not longer than 80 chars."""
max_len = 80 # based on error messages
remaining_len = max_len - len(DEV_NAME) - len(suffix) - 2
middle = name[:remaining_len]
name = f"{DEV_NAME} {middle} {suffix}"
return name
class Injector(multiprocessing.Process):
2021-09-29 18:17:45 +00:00
"""Initializes, starts and stops injections.
2020-11-28 14:43:24 +00:00
Is a process to make it non-blocking for the rest of the code and to
make running multiple injector easier. There is one process per
2020-11-28 14:43:24 +00:00
hardware-device that is being mapped.
"""
2021-09-26 10:44:56 +00:00
2022-01-31 19:58:37 +00:00
group: _Group
preset: Preset
context: Optional[Context]
_state: int
_msg_pipe: multiprocessing.Pipe
2022-04-17 10:19:23 +00:00
_consumer_controls: List[EventReader]
_stop_event: asyncio.Event
2022-01-31 19:58:37 +00:00
2021-04-26 21:21:52 +00:00
regrab_timeout = 0.2
2020-12-06 18:54:02 +00:00
2022-01-31 19:58:37 +00:00
def __init__(self, group: _Group, preset: Preset) -> None:
"""
2020-11-28 14:43:24 +00:00
Parameters
----------
group : _Group
the device group
2022-01-31 19:58:37 +00:00
preset : Preset
2020-11-28 14:43:24 +00:00
"""
self.group = group
self._state = UNKNOWN
2021-09-29 18:17:45 +00:00
# used to interact with the parts of this class that are running within
# the new process
self._msg_pipe = multiprocessing.Pipe()
2021-09-29 18:17:45 +00:00
2022-01-31 19:58:37 +00:00
self.preset = preset
self.context = None # only needed inside the injection process
2021-09-29 18:17:45 +00:00
self._consumer_controls = []
2022-04-17 10:19:23 +00:00
self._stop_event = None
2021-09-29 18:17:45 +00:00
2022-01-14 17:50:57 +00:00
super().__init__(name=group)
2021-02-14 11:34:56 +00:00
"""Functions to interact with the running process"""
2022-01-31 19:58:37 +00:00
def get_state(self) -> int:
"""Get the state of the injection.
Can be safely called from the main process.
"""
# figure out what is going on step by step
alive = self.is_alive()
if self._state == UNKNOWN and not alive:
# `self.start()` has not been called yet
return self._state
if self._state == UNKNOWN and alive:
# if it is alive, it is definitely at least starting up.
self._state = STARTING
if self._state == STARTING and self._msg_pipe[1].poll():
# if there is a message available, it might have finished starting up
# and the injector has the real status for us
msg = self._msg_pipe[1].recv()
self._state = msg
if self._state in [STARTING, RUNNING] and not alive:
# we thought it is running (maybe it was when get_state was previously),
# but the process is not alive. It probably crashed
self._state = FAILED
2021-09-26 10:44:56 +00:00
logger.error("Injector was unexpectedly found stopped")
return self._state
@ensure_numlock
2022-01-31 19:58:37 +00:00
def stop_injecting(self) -> None:
"""Stop injecting keycodes.
Can be safely called from the main procss.
"""
2021-09-26 10:44:56 +00:00
logger.info('Stopping injecting keycodes for group "%s"', self.group.key)
self._msg_pipe[1].send(CLOSE)
self._state = STOPPED
2021-02-14 11:34:56 +00:00
"""Process internal stuff"""
2020-12-01 23:02:41 +00:00
2022-01-31 19:58:37 +00:00
def _grab_devices(self) -> GroupSources:
2021-04-26 21:21:52 +00:00
"""Grab all devices that are needed for the injection."""
sources = []
for path in self.group.paths:
source = self._grab_device(path)
if source is None:
# this path doesn't need to be grabbed for injection, because
2022-01-31 19:58:37 +00:00
# it doesn't provide the events needed to execute the preset
2021-04-26 21:21:52 +00:00
continue
sources.append(source)
return sources
2022-01-31 19:58:37 +00:00
def _grab_device(self, path: os.PathLike) -> Optional[evdev.InputDevice]:
2021-04-26 21:21:52 +00:00
"""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.
"""
2020-12-03 19:37:36 +00:00
try:
device = evdev.InputDevice(path)
2021-02-07 14:00:36 +00:00
except (FileNotFoundError, OSError):
2021-01-17 14:09:47 +00:00
logger.error('Could not find "%s"', path)
return None
2020-11-28 14:43:24 +00:00
capabilities = device.capabilities(absinfo=False)
2020-11-28 14:43:24 +00:00
needed = False
2022-04-17 10:19:23 +00:00
for mapping in self.context.preset:
if is_in_capabilities(mapping.event_combination, capabilities):
logger.debug(
'Grabbing "%s" because of "%s"',
path,
mapping.event_combination,
2022-04-17 10:19:23 +00:00
)
2020-12-02 19:48:23 +00:00
needed = True
break
2020-11-30 21:42:53 +00:00
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.
2021-09-26 10:44:56 +00:00
logger.debug("No need to grab %s", path)
2021-01-17 14:09:47 +00:00
return None
2020-11-28 14:43:24 +00:00
attempts = 0
while True:
try:
device.grab()
2021-09-26 10:44:56 +00:00
logger.debug("Grab %s", path)
2020-11-28 14:43:24 +00:00
break
2021-01-07 16:15:12 +00:00
except IOError as error:
2020-11-28 14:43:24 +00:00
attempts += 1
2021-01-07 16:15:12 +00:00
2020-11-30 21:42:53 +00:00
# it might take a little time until the device is free if
# it was previously grabbed.
2021-09-26 10:44:56 +00:00
logger.debug("Failed attempts to grab %s: %d", path, attempts)
2020-11-28 14:43:24 +00:00
2021-04-26 21:21:52 +00:00
if attempts >= 10:
2021-09-26 10:44:56 +00:00
logger.error("Cannot grab %s, it is possibly in use", path)
2021-01-07 16:15:12 +00:00
logger.error(str(error))
2021-01-17 14:09:47 +00:00
return None
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
2021-01-17 14:09:47 +00:00
return device
2020-11-28 14:43:24 +00:00
2022-01-31 19:58:37 +00:00
def _copy_capabilities(self, input_device: evdev.InputDevice) -> CapabilitiesDict:
"""Copy capabilities for a new device."""
ecodes = evdev.ecodes
# copy the capabilities because the uinput is going
# to act like the device.
capabilities = input_device.capabilities(absinfo=True)
# 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]
if ecodes.ABS_VOLUME in capabilities.get(ecodes.EV_ABS, []):
# For some reason an ABS_VOLUME capability likes to appear
# for some users. It prevents mice from moving around and
# keyboards from writing symbols
capabilities[ecodes.EV_ABS].remove(ecodes.ABS_VOLUME)
return capabilities
2022-01-31 19:58:37 +00:00
async def _msg_listener(self) -> None:
"""Wait for messages from the main process to do special stuff."""
2021-01-17 14:09:47 +00:00
loop = asyncio.get_event_loop()
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:
2021-09-26 10:44:56 +00:00
logger.debug("Received close signal")
2022-04-17 10:19:23 +00:00
self._stop_event.set()
# give the event pipeline some time to reset devices
# before shutting the loop down
await asyncio.sleep(0.1)
# stop the event loop and cause the process to reach its end
# cleanly. Using .terminate prevents coverage from working.
loop.stop()
return
2022-01-31 19:58:37 +00:00
def run(self) -> None:
2020-11-28 14:43:24 +00:00
"""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.
2020-11-28 14:43:24 +00:00
"""
2021-09-29 18:17:45 +00:00
# TODO run all injections in a single process via asyncio
# - Make sure that closing asyncio fds won't lag the service
# - SharedDict becomes obsolete
# - quick_cleanup needs to be able to reliably stop the injection
# - I think I want an event listener architecture so that macros,
# joystick_to_mouse, keycode_mapper and possibly other modules can get
2021-09-29 18:17:45 +00:00
# what they filter for whenever they want, without having to wire
# things through multiple other objects all the time
# - _new_event_arrived moves to the place where events are emitted. injector?
# - active macros and unreleased need to be per injection. it probably
# should move into the keycode_mapper class, but that only works if there
# is only one keycode_mapper per injection, and not per source. Problem was
# that I had to excessively pass around to which device to forward to...
# I also need to have information somewhere which source is a gamepad, I
# probably don't want to evaluate that from scratch each time `notify` is
# called.
# - benefit: writing macros that listen for events from other devices
2022-01-31 19:58:37 +00:00
logger.info('Starting injecting the preset for "%s"', self.group.key)
# create a new event loop, because somehow running an infinite loop
# that sleeps on iterations (joystick_to_mouse) 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
2022-01-31 19:58:37 +00:00
self.context = Context(self.preset)
2022-04-17 10:19:23 +00:00
self._stop_event = asyncio.Event()
2021-04-26 21:21:52 +00:00
# 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()
2021-09-29 18:17:45 +00:00
if len(sources) == 0:
logger.error("Did not grab any device")
self._msg_pipe[0].send(NO_GRAB)
return
2020-12-16 11:57:09 +00:00
numlock_state = is_numlock_on()
2020-11-28 14:43:24 +00:00
coroutines = []
2020-11-18 19:03:37 +00:00
2021-04-26 21:21:52 +00:00
for source in sources:
# copy as much information as possible, because libinput uses the extra
# information to enable certain features like "Disable touchpad while
# typing"
try:
forward_to = evdev.UInput(
name=get_udev_name(source.name, "forwarded"),
events=self._copy_capabilities(source),
# phys=source.phys, # this leads to confusion. the appearance of
# an uinput with this "phys" property causes the udev rule to
# autoload for the original device, overwriting our previous
# attempts at starting an injection.
vendor=source.info.vendor,
product=source.info.product,
version=source.info.version,
bustype=source.info.bustype,
input_props=source.input_props(),
)
except TypeError as e:
if "input_props" in str(e):
# UInput constructor doesn't support input_props and
# source.input_props doesn't exist with old python-evdev versions.
logger.error("Please upgrade your python-evdev version. Exiting")
self._msg_pipe[0].send(UPGRADE_EVDEV)
sys.exit(12)
raise e
2020-12-06 18:08:09 +00:00
2021-09-29 18:17:45 +00:00
# actually doing things
2022-04-17 10:19:23 +00:00
event_reader = EventReader(
self.context,
source,
forward_to,
self._stop_event,
2022-04-17 10:19:23 +00:00
)
coroutines.append(event_reader.run())
self._consumer_controls.append(event_reader)
2020-11-18 19:03:37 +00:00
2021-01-17 14:09:47 +00:00
coroutines.append(self._msg_listener())
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)
self._msg_pipe[0].send(RUNNING)
2021-01-05 18:33:47 +00:00
try:
loop.run_until_complete(asyncio.gather(*coroutines))
2022-01-31 19:58:37 +00:00
except RuntimeError as error:
# the loop might have been stopped via a `CLOSE` message,
# which causes the error message below. This is expected behavior
if str(error) != "Event loop stopped before Future completed.":
raise error
except OSError as error:
logger.error("Failed to run injector coroutines: %s", str(error))
2020-11-28 14:43:24 +00:00
2020-11-30 21:42:53 +00:00
if len(coroutines) > 0:
2021-01-07 16:15:12 +00:00
# expected when stop_injecting is called,
# during normal operation as well as tests this point is not
# reached otherwise.
logger.debug("Injector coroutines ended")
2020-11-30 21:42:53 +00:00
2021-04-26 21:21:52 +00:00
for source in sources:
# ungrab at the end to make the next injection process not fail
# its grabs
try:
source.ungrab()
except OSError as error:
# it might have disappeared
logger.debug("OSError for ungrab on %s: %s", source.path, str(error))