2020-11-02 20:57:28 +00:00
|
|
|
# -*- 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."""
|
2022-07-23 08:53:41 +00:00
|
|
|
from __future__ import annotations
|
2022-12-15 13:43:03 +00:00
|
|
|
|
2020-11-19 00:02:27 +00:00
|
|
|
import asyncio
|
2022-11-01 11:07:12 +00:00
|
|
|
import enum
|
2020-11-18 12:17:49 +00:00
|
|
|
import multiprocessing
|
2022-07-23 08:53:41 +00:00
|
|
|
import sys
|
|
|
|
import time
|
2022-12-15 13:43:03 +00:00
|
|
|
from collections import defaultdict
|
2022-07-23 08:53:41 +00:00
|
|
|
from dataclasses import dataclass
|
|
|
|
from multiprocessing.connection import Connection
|
2022-11-01 11:07:12 +00:00
|
|
|
from typing import Dict, List, Optional, Tuple, Union
|
2020-11-02 20:57:28 +00:00
|
|
|
|
2020-11-05 00:24:56 +00:00
|
|
|
import evdev
|
|
|
|
|
2022-12-15 13:43:03 +00:00
|
|
|
from inputremapper.configs.input_config import InputCombination, InputConfig
|
2022-01-31 19:58:37 +00:00
|
|
|
from inputremapper.configs.preset import Preset
|
2022-07-23 08:53:41 +00:00
|
|
|
from inputremapper.groups import (
|
|
|
|
_Group,
|
|
|
|
classify,
|
|
|
|
DeviceType,
|
|
|
|
)
|
2022-10-16 12:56:21 +00:00
|
|
|
from inputremapper.gui.messages.message_broker import MessageType
|
2022-01-01 12:00:49 +00:00
|
|
|
from inputremapper.injection.context import Context
|
2022-04-17 10:19:23 +00:00
|
|
|
from inputremapper.injection.event_reader import EventReader
|
2022-07-23 08:53:41 +00:00
|
|
|
from inputremapper.injection.numlock import set_numlock, is_numlock_on, ensure_numlock
|
|
|
|
from inputremapper.logger import logger
|
2022-12-15 13:43:03 +00:00
|
|
|
from inputremapper.utils import get_device_hash
|
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
|
|
|
|
|
|
|
|
2022-11-01 11:07:12 +00:00
|
|
|
# messages sent to the injector process
|
|
|
|
class InjectorCommand(str, enum.Enum):
|
|
|
|
CLOSE = "CLOSE"
|
2021-01-07 16:15:12 +00:00
|
|
|
|
2022-11-01 11:07:12 +00:00
|
|
|
|
|
|
|
# messages the injector process reports back to the service
|
|
|
|
class InjectorState(str, enum.Enum):
|
|
|
|
UNKNOWN = "UNKNOWN"
|
|
|
|
STARTING = "STARTING"
|
|
|
|
FAILED = "FAILED"
|
|
|
|
RUNNING = "RUNNING"
|
|
|
|
STOPPED = "STOPPED"
|
|
|
|
NO_GRAB = "NO_GRAB"
|
|
|
|
UPGRADE_EVDEV = "UPGRADE_EVDEV"
|
2020-11-19 00:02:27 +00:00
|
|
|
|
|
|
|
|
2022-01-31 19:58:37 +00:00
|
|
|
def is_in_capabilities(
|
2022-12-15 13:43:03 +00:00
|
|
|
combination: InputCombination, capabilities: CapabilitiesDict
|
2022-01-31 19:58:37 +00:00
|
|
|
) -> 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:
|
2021-10-01 22:55:10 +00:00
|
|
|
"""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
|
|
|
|
|
|
|
|
|
2022-07-23 08:53:41 +00:00
|
|
|
@dataclass(frozen=True)
|
2022-11-01 11:07:12 +00:00
|
|
|
class InjectorStateMessage:
|
2022-07-23 08:53:41 +00:00
|
|
|
message_type = MessageType.injector_state
|
2022-11-01 11:07:12 +00:00
|
|
|
state: Union[InjectorState]
|
2022-07-23 08:53:41 +00:00
|
|
|
|
|
|
|
def active(self) -> bool:
|
2022-11-01 11:07:12 +00:00
|
|
|
return self.state in [InjectorState.RUNNING, InjectorState.STARTING]
|
|
|
|
|
|
|
|
def inactive(self) -> bool:
|
|
|
|
return self.state in [InjectorState.STOPPED, InjectorState.NO_GRAB]
|
2022-07-23 08:53:41 +00:00
|
|
|
|
|
|
|
|
2021-02-13 20:17:08 +00:00
|
|
|
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
|
2021-01-04 19:50:05 +00:00
|
|
|
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]
|
2022-12-15 13:43:03 +00:00
|
|
|
_devices: List[evdev.InputDevice]
|
2022-11-01 11:07:12 +00:00
|
|
|
_state: InjectorState
|
2022-07-23 08:53:41 +00:00
|
|
|
_msg_pipe: Tuple[Connection, Connection]
|
2022-11-20 19:36:33 +00:00
|
|
|
_event_readers: List[EventReader]
|
2022-04-17 10:19:23 +00:00
|
|
|
_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:
|
2021-11-21 20:45:02 +00:00
|
|
|
"""
|
2020-11-28 14:43:24 +00:00
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2022-11-12 16:45:32 +00:00
|
|
|
group
|
2021-04-23 09:51:21 +00:00
|
|
|
the device group
|
2020-11-28 14:43:24 +00:00
|
|
|
"""
|
2021-04-23 09:51:21 +00:00
|
|
|
self.group = group
|
2022-11-01 11:07:12 +00:00
|
|
|
self._state = InjectorState.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
|
2021-02-13 20:17:08 +00:00
|
|
|
self._msg_pipe = multiprocessing.Pipe()
|
2021-09-29 18:17:45 +00:00
|
|
|
|
2022-01-31 19:58:37 +00:00
|
|
|
self.preset = preset
|
2021-02-22 22:09:55 +00:00
|
|
|
self.context = None # only needed inside the injection process
|
2021-09-29 18:17:45 +00:00
|
|
|
|
2022-11-20 19:36:33 +00:00
|
|
|
self._event_readers = []
|
2021-09-29 18:17:45 +00:00
|
|
|
|
2022-07-23 08:53:41 +00:00
|
|
|
super().__init__(name=group.key)
|
2021-02-13 20:17:08 +00:00
|
|
|
|
2022-11-12 16:45:32 +00:00
|
|
|
"""Functions to interact with the running process."""
|
2021-02-13 20:17:08 +00:00
|
|
|
|
2022-11-01 11:07:12 +00:00
|
|
|
def get_state(self) -> InjectorState:
|
2021-02-13 20:17:08 +00:00
|
|
|
"""Get the state of the injection.
|
|
|
|
|
|
|
|
Can be safely called from the main process.
|
|
|
|
"""
|
2022-07-23 08:53:41 +00:00
|
|
|
# before we try to we try to guess anything lets check if there is a message
|
|
|
|
state = self._state
|
|
|
|
while self._msg_pipe[1].poll():
|
|
|
|
state = self._msg_pipe[1].recv()
|
|
|
|
|
2022-03-18 19:03:38 +00:00
|
|
|
# figure out what is going on step by step
|
2021-02-13 20:17:08 +00:00
|
|
|
alive = self.is_alive()
|
|
|
|
|
2022-11-01 11:07:12 +00:00
|
|
|
# if `self.start()` has been called
|
|
|
|
started = state != InjectorState.UNKNOWN or alive
|
|
|
|
|
|
|
|
if started:
|
|
|
|
if state == InjectorState.UNKNOWN and alive:
|
|
|
|
# if it is alive, it is definitely at least starting up.
|
|
|
|
state = InjectorState.STARTING
|
|
|
|
|
|
|
|
if state in (InjectorState.STARTING, InjectorState.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
|
|
|
|
state = InjectorState.FAILED
|
|
|
|
logger.error("Injector was unexpectedly found stopped")
|
|
|
|
|
|
|
|
logger.debug(
|
|
|
|
'Injector state of "%s", "%s": %s',
|
|
|
|
self.group.key,
|
|
|
|
self.preset.name,
|
|
|
|
state,
|
|
|
|
)
|
2022-07-23 08:53:41 +00:00
|
|
|
self._state = state
|
2021-02-13 20:17:08 +00:00
|
|
|
return self._state
|
|
|
|
|
|
|
|
@ensure_numlock
|
2022-01-31 19:58:37 +00:00
|
|
|
def stop_injecting(self) -> None:
|
2021-02-13 20:17:08 +00:00
|
|
|
"""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)
|
2022-11-01 11:07:12 +00:00
|
|
|
self._msg_pipe[1].send(InjectorCommand.CLOSE)
|
2021-02-13 20:17:08 +00:00
|
|
|
|
2022-11-12 16:45:32 +00:00
|
|
|
"""Process internal stuff."""
|
2020-12-01 23:02:41 +00:00
|
|
|
|
2022-12-15 13:43:03 +00:00
|
|
|
def _find_input_device(
|
|
|
|
self, input_config: InputConfig
|
|
|
|
) -> Optional[evdev.InputDevice]:
|
|
|
|
"""find the InputDevice specified by the InputConfig
|
|
|
|
|
|
|
|
ensures the devices supports the type and code specified by the InputConfig"""
|
|
|
|
devices_by_hash = {get_device_hash(device): device for device in self._devices}
|
|
|
|
|
|
|
|
# mypy thinks None is the wrong type for dict.get()
|
|
|
|
if device := devices_by_hash.get(input_config.origin_hash): # type: ignore
|
|
|
|
if input_config.code in device.capabilities(absinfo=False).get(
|
|
|
|
input_config.type, []
|
|
|
|
):
|
|
|
|
return device
|
|
|
|
return None
|
|
|
|
|
|
|
|
def _find_input_device_fallback(
|
|
|
|
self, input_config: InputConfig
|
|
|
|
) -> Optional[evdev.InputDevice]:
|
|
|
|
"""find the InputDevice specified by the InputConfig fallback logic"""
|
2022-07-23 08:53:41 +00:00
|
|
|
ranking = [
|
|
|
|
DeviceType.KEYBOARD,
|
|
|
|
DeviceType.GAMEPAD,
|
|
|
|
DeviceType.MOUSE,
|
|
|
|
DeviceType.TOUCHPAD,
|
|
|
|
DeviceType.GRAPHICS_TABLET,
|
|
|
|
DeviceType.CAMERA,
|
|
|
|
DeviceType.UNKNOWN,
|
|
|
|
]
|
2022-12-15 13:43:03 +00:00
|
|
|
candidates: List[evdev.InputDevice] = [
|
|
|
|
device
|
|
|
|
for device in self._devices
|
|
|
|
if input_config.code
|
|
|
|
in device.capabilities(absinfo=False).get(input_config.type, [])
|
|
|
|
]
|
2022-07-23 08:53:41 +00:00
|
|
|
|
2022-12-15 13:43:03 +00:00
|
|
|
if len(candidates) > 1:
|
|
|
|
# there is more than on input device which can be used for this
|
|
|
|
# event we choose only one determined by the ranking
|
|
|
|
return sorted(candidates, key=lambda d: ranking.index(classify(d)))[0]
|
|
|
|
if len(candidates) == 1:
|
|
|
|
return candidates.pop()
|
|
|
|
|
|
|
|
logger.error(f"Could not find input for {input_config}")
|
|
|
|
return None
|
2022-07-23 08:53:41 +00:00
|
|
|
|
2022-12-15 13:43:03 +00:00
|
|
|
def _grab_devices(self) -> GroupSources:
|
2022-07-23 08:53:41 +00:00
|
|
|
# find all devices which have an associated mapping
|
2022-11-12 16:45:32 +00:00
|
|
|
# use a dict because the InputDevice is not directly hashable
|
|
|
|
needed_devices = {}
|
2022-12-15 13:43:03 +00:00
|
|
|
input_configs = set()
|
2022-10-23 17:25:39 +00:00
|
|
|
|
2022-12-15 13:43:03 +00:00
|
|
|
# find all unique input_config's
|
2022-07-23 08:53:41 +00:00
|
|
|
for mapping in self.preset:
|
2022-12-15 13:43:03 +00:00
|
|
|
for input_config in mapping.input_combination:
|
|
|
|
input_configs.add(input_config)
|
|
|
|
|
|
|
|
# find all unique input_device's
|
|
|
|
for input_config in input_configs:
|
|
|
|
if not (device := self._find_input_device(input_config)):
|
|
|
|
# there is no point in trying the fallback because
|
|
|
|
# self._update_preset already did that.
|
|
|
|
continue
|
|
|
|
needed_devices[device.path] = device
|
2021-04-26 21:21:52 +00:00
|
|
|
|
2022-07-23 08:53:41 +00:00
|
|
|
grabbed_devices = []
|
|
|
|
for device in needed_devices.values():
|
|
|
|
if device := self._grab_device(device):
|
|
|
|
grabbed_devices.append(device)
|
|
|
|
return grabbed_devices
|
2021-04-26 21:21:52 +00:00
|
|
|
|
2022-12-15 13:43:03 +00:00
|
|
|
def _update_preset(self):
|
|
|
|
"""Update all InputConfigs in the preset to include correct origin_hash
|
|
|
|
information."""
|
|
|
|
mappings_by_input = defaultdict(list)
|
|
|
|
for mapping in self.preset:
|
|
|
|
for input_config in mapping.input_combination:
|
|
|
|
mappings_by_input[input_config].append(mapping)
|
|
|
|
|
|
|
|
for input_config in mappings_by_input:
|
|
|
|
if self._find_input_device(input_config):
|
|
|
|
continue
|
|
|
|
|
|
|
|
if not (device := self._find_input_device_fallback(input_config)):
|
|
|
|
# fallback failed, this mapping will be ignored
|
|
|
|
continue
|
|
|
|
|
|
|
|
for mapping in mappings_by_input[input_config]:
|
|
|
|
combination: List[InputConfig] = list(mapping.input_combination)
|
|
|
|
device_hash = get_device_hash(device)
|
|
|
|
idx = combination.index(input_config)
|
|
|
|
combination[idx] = combination[idx].modify(origin_hash=device_hash)
|
|
|
|
mapping.input_combination = combination
|
|
|
|
|
2022-07-23 08:53:41 +00:00
|
|
|
def _grab_device(self, device: evdev.InputDevice) -> Optional[evdev.InputDevice]:
|
|
|
|
"""Try to grab the device, return None if not possible.
|
2021-04-26 21:21:52 +00:00
|
|
|
|
|
|
|
Without grab, original events from it would reach the display server
|
|
|
|
even though they are mapped.
|
|
|
|
"""
|
2022-07-23 08:53:41 +00:00
|
|
|
error = None
|
|
|
|
for attempt in range(10):
|
2020-11-28 14:43:24 +00:00
|
|
|
try:
|
|
|
|
device.grab()
|
2022-07-23 08:53:41 +00:00
|
|
|
logger.debug("Grab %s", device.path)
|
|
|
|
return device
|
|
|
|
except IOError as err:
|
2020-11-30 21:42:53 +00:00
|
|
|
# it might take a little time until the device is free if
|
|
|
|
# it was previously grabbed.
|
2022-07-23 08:53:41 +00:00
|
|
|
error = err
|
|
|
|
logger.debug("Failed attempts to grab %s: %d", device.path, attempt + 1)
|
|
|
|
time.sleep(self.regrab_timeout)
|
2020-11-28 14:43:24 +00:00
|
|
|
|
2022-07-23 08:53:41 +00:00
|
|
|
logger.error("Cannot grab %s, it is possibly in use", device.path)
|
|
|
|
logger.error(str(error))
|
|
|
|
return None
|
2020-11-28 14:43:24 +00:00
|
|
|
|
2022-12-15 13:43:03 +00:00
|
|
|
@staticmethod
|
|
|
|
def _copy_capabilities(input_device: evdev.InputDevice) -> CapabilitiesDict:
|
2021-02-18 19:38:14 +00:00
|
|
|
"""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
|
2021-04-23 09:51:21 +00:00
|
|
|
# keyboards from writing symbols
|
2021-02-18 19:38:14 +00:00
|
|
|
capabilities[ecodes.EV_ABS].remove(ecodes.ABS_VOLUME)
|
|
|
|
|
|
|
|
return capabilities
|
|
|
|
|
2022-01-31 19:58:37 +00:00
|
|
|
async def _msg_listener(self) -> None:
|
2020-12-01 22:53:32 +00:00
|
|
|
"""Wait for messages from the main process to do special stuff."""
|
2021-01-17 14:09:47 +00:00
|
|
|
loop = asyncio.get_event_loop()
|
2020-12-01 22:53:32 +00:00
|
|
|
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()
|
2022-11-01 11:07:12 +00:00
|
|
|
if msg == InjectorCommand.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)
|
|
|
|
|
2020-12-01 22:53:32 +00:00
|
|
|
# stop the event loop and cause the process to reach its end
|
|
|
|
# cleanly. Using .terminate prevents coverage from working.
|
|
|
|
loop.stop()
|
2022-11-01 11:07:12 +00:00
|
|
|
self._msg_pipe[0].send(InjectorState.STOPPED)
|
2020-12-01 22:53:32 +00:00
|
|
|
return
|
|
|
|
|
2022-12-15 13:43:03 +00:00
|
|
|
def _create_forwarding_device(self, source: evdev.InputDevice) -> evdev.UInput:
|
|
|
|
# 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
|
|
|
|
# a 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(InjectorState.UPGRADE_EVDEV)
|
|
|
|
sys.exit(12)
|
|
|
|
|
|
|
|
raise e
|
|
|
|
return forward_to
|
|
|
|
|
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.
|
2021-01-02 01:26:44 +00:00
|
|
|
|
|
|
|
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
|
|
|
"""
|
2022-01-31 19:58:37 +00:00
|
|
|
logger.info('Starting injecting the preset for "%s"', self.group.key)
|
2021-02-13 21:34:12 +00:00
|
|
|
|
2020-12-27 12:09:28 +00:00
|
|
|
# create a new event loop, because somehow running an infinite loop
|
2021-11-21 13:58:16 +00:00
|
|
|
# that sleeps on iterations (joystick_to_mouse) in one process causes
|
2020-12-27 12:09:28 +00:00
|
|
|
# another injection process to screw up reading from the grabbed
|
|
|
|
# device.
|
|
|
|
loop = asyncio.new_event_loop()
|
|
|
|
asyncio.set_event_loop(loop)
|
|
|
|
|
2022-12-15 13:43:03 +00:00
|
|
|
self._devices = self.group.get_devices()
|
|
|
|
|
|
|
|
# InputConfigs may not contain the origin_hash information, this will try to make a
|
|
|
|
# good guess if the origin_hash information is missing or invalid.
|
|
|
|
self._update_preset()
|
|
|
|
|
|
|
|
# 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-02-22 22:09:55 +00:00
|
|
|
# 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-02-22 22:09:55 +00:00
|
|
|
|
2021-09-29 18:17:45 +00:00
|
|
|
if len(sources) == 0:
|
2022-11-01 11:07:12 +00:00
|
|
|
# maybe the preset was empty or something
|
2021-09-29 18:17:45 +00:00
|
|
|
logger.error("Did not grab any device")
|
2022-11-01 11:07:12 +00:00
|
|
|
self._msg_pipe[0].send(InjectorState.NO_GRAB)
|
2021-09-29 18:17:45 +00:00
|
|
|
return
|
2020-12-16 11:57:09 +00:00
|
|
|
|
2021-02-13 21:34:12 +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:
|
2022-12-15 13:43:03 +00:00
|
|
|
forward_to = self._create_forwarding_device(source)
|
2021-09-29 18:17:45 +00:00
|
|
|
# actually doing things
|
2022-04-17 10:19:23 +00:00
|
|
|
event_reader = EventReader(
|
2022-04-18 11:52:59 +00:00
|
|
|
self.context,
|
|
|
|
source,
|
|
|
|
forward_to,
|
|
|
|
self._stop_event,
|
2022-04-17 10:19:23 +00:00
|
|
|
)
|
|
|
|
coroutines.append(event_reader.run())
|
2022-11-20 19:36:33 +00:00
|
|
|
self._event_readers.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-01 22:53:32 +00:00
|
|
|
|
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)
|
|
|
|
|
2022-11-01 11:07:12 +00:00
|
|
|
self._msg_pipe[0].send(InjectorState.RUNNING)
|
2021-01-05 18:33:47 +00:00
|
|
|
|
2020-12-01 22:53:32 +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
|
2020-12-19 15:04:07 +00:00
|
|
|
except OSError as error:
|
2021-11-04 10:41:13 +00:00
|
|
|
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.
|
2021-11-04 10:41:13 +00:00
|
|
|
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
|
2021-11-04 10:41:13 +00:00
|
|
|
try:
|
|
|
|
source.ungrab()
|
|
|
|
except OSError as error:
|
|
|
|
# it might have disappeared
|
|
|
|
logger.debug("OSError for ungrab on %s: %s", source.path, str(error))
|