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
|
|
|
|
|
|
|
|
2020-11-19 10:12:28 +00:00
|
|
|
import re
|
2020-11-19 00:02:27 +00:00
|
|
|
import asyncio
|
|
|
|
import time
|
2020-11-19 10:12:28 +00:00
|
|
|
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-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
|
2020-11-30 15:22:17 +00:00
|
|
|
from keymapper.state import system_mapping, KEYCODE_OFFSET
|
2020-11-28 17:39:55 +00:00
|
|
|
from keymapper.dev.macros import parse
|
2020-11-18 19:03:37 +00:00
|
|
|
|
|
|
|
|
|
|
|
DEV_NAME = 'key-mapper'
|
2020-11-18 21:06:54 +00:00
|
|
|
DEVICE_CREATED = 1
|
2020-11-19 00:02:27 +00:00
|
|
|
FAILED = 2
|
2020-11-22 15:54:40 +00:00
|
|
|
DEVICE_SKIPPED = 3
|
2020-11-19 00:02:27 +00:00
|
|
|
|
|
|
|
|
2020-11-19 10:12:28 +00:00
|
|
|
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
|
|
|
|
2020-11-19 10:12:28 +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-11-19 10:12:28 +00:00
|
|
|
|
|
|
|
def toggle_numlock():
|
|
|
|
"""Turn the numlock on or off."""
|
|
|
|
try:
|
|
|
|
subprocess.check_output(['numlockx', 'toggle'])
|
|
|
|
except FileNotFoundError:
|
|
|
|
# doesn't seem to be installed everywhere
|
|
|
|
logger.debug('numlockx not found, trying to inject a keycode')
|
|
|
|
# and this doesn't always work.
|
|
|
|
device = evdev.UInput(
|
|
|
|
name=f'key-mapper numlock-control',
|
|
|
|
phys='key-mapper',
|
|
|
|
)
|
|
|
|
device.write(evdev.ecodes.EV_KEY, evdev.ecodes.KEY_NUMLOCK, 1)
|
|
|
|
device.syn()
|
|
|
|
device.write(evdev.ecodes.EV_KEY, evdev.ecodes.KEY_NUMLOCK, 0)
|
|
|
|
device.syn()
|
|
|
|
|
|
|
|
|
|
|
|
def ensure_numlock(func):
|
2020-11-22 20:41:29 +00:00
|
|
|
"""Decorator to reset the numlock to its initial state afterwards."""
|
2020-11-19 10:12:28 +00:00
|
|
|
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)
|
|
|
|
numlock_after = is_numlock_on()
|
|
|
|
if numlock_after != numlock_before:
|
|
|
|
logger.debug('Reverting numlock status to %s', numlock_before)
|
|
|
|
toggle_numlock()
|
|
|
|
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-11-19 10:12:28 +00:00
|
|
|
@ensure_numlock
|
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
|
|
|
|
"""
|
2020-11-17 13:35:36 +00:00
|
|
|
self.device = device
|
2020-11-28 14:43:24 +00:00
|
|
|
self.mapping = mapping
|
|
|
|
self._process = None
|
|
|
|
|
2020-11-30 15:22:17 +00:00
|
|
|
def __del__(self):
|
|
|
|
if self._process is not None:
|
|
|
|
self._process.terminate()
|
|
|
|
|
2020-11-28 14:43:24 +00:00
|
|
|
def start_injecting(self):
|
|
|
|
"""Start injecting keycodes."""
|
|
|
|
self._process = multiprocessing.Process(target=self._start_injecting)
|
|
|
|
self._process.start()
|
|
|
|
|
|
|
|
def _prepare_device(self, path):
|
|
|
|
"""Try to grab the device, return if not needed/possible."""
|
|
|
|
device = evdev.InputDevice(path)
|
|
|
|
|
|
|
|
if device is None:
|
|
|
|
return None
|
|
|
|
|
2020-11-30 15:22:17 +00:00
|
|
|
capabilities = device.capabilities(absinfo=False)
|
2020-11-28 14:43:24 +00:00
|
|
|
|
|
|
|
needed = False
|
|
|
|
for keycode, _ in self.mapping:
|
2020-11-30 15:22:17 +00:00
|
|
|
if keycode - KEYCODE_OFFSET in capabilities[evdev.ecodes.EV_KEY]:
|
2020-11-28 14:43:24 +00:00
|
|
|
needed = True
|
|
|
|
break
|
2020-11-30 15:22:17 +00:00
|
|
|
# TODO only if map ABS to REL keep ABS devics
|
|
|
|
if capabilities.get(evdev.ecodes.EV_REL) is not None:
|
|
|
|
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)
|
2020-11-28 14:43:24 +00:00
|
|
|
return None
|
|
|
|
|
|
|
|
attempts = 0
|
|
|
|
while True:
|
|
|
|
device = evdev.InputDevice(path)
|
|
|
|
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()
|
|
|
|
break
|
|
|
|
except IOError:
|
|
|
|
attempts += 1
|
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
|
|
|
|
|
|
|
|
# it might take a little time until the device is free if
|
|
|
|
# it was previously grabbed.
|
|
|
|
time.sleep(0.15)
|
|
|
|
|
|
|
|
return device
|
|
|
|
|
2020-11-30 15:22:17 +00:00
|
|
|
def map_abs_to_rel(self):
|
|
|
|
# TODO offer configuration via the UI if a gamepad is elected
|
|
|
|
return True
|
|
|
|
|
2020-11-28 14:43:24 +00:00
|
|
|
def _modify_capabilities(self, input_device):
|
|
|
|
"""Adds all keycode into a copy of a devices capabilities.
|
|
|
|
|
|
|
|
Prameters
|
|
|
|
---------
|
|
|
|
input_device : evdev.InputDevice
|
|
|
|
"""
|
2020-11-30 15:22:17 +00:00
|
|
|
ecodes = evdev.ecodes
|
|
|
|
|
2020-11-28 14:43:24 +00:00
|
|
|
# copy the capabilities because the keymapper_device is going
|
|
|
|
# to act like the device.
|
|
|
|
capabilities = input_device.capabilities(absinfo=False)
|
2020-11-30 17:59:34 +00:00
|
|
|
|
2020-11-30 15:22:17 +00:00
|
|
|
# Furthermore, support all injected keycodes
|
2020-11-30 17:59:34 +00:00
|
|
|
if len(self.mapping) > 0 and capabilities.get(ecodes.EV_KEY) is None:
|
|
|
|
capabilities[ecodes.EV_KEY] = []
|
|
|
|
|
2020-11-30 15:22:17 +00:00
|
|
|
for _, character in self.mapping:
|
|
|
|
keycode = system_mapping.get(character)
|
|
|
|
if keycode is not None:
|
|
|
|
capabilities[ecodes.EV_KEY].append(keycode - KEYCODE_OFFSET)
|
|
|
|
|
|
|
|
if self.map_abs_to_rel():
|
|
|
|
if capabilities.get(ecodes.EV_ABS):
|
|
|
|
del capabilities[ecodes.EV_ABS]
|
|
|
|
capabilities[ecodes.EV_REL] = [
|
|
|
|
evdev.ecodes.REL_X,
|
|
|
|
evdev.ecodes.REL_Y,
|
|
|
|
# for my system to recognize it as mouse, WHEEL is also needed:
|
|
|
|
evdev.ecodes.REL_WHEEL,
|
|
|
|
]
|
2020-11-28 14:43:24 +00:00
|
|
|
|
|
|
|
# just like what python-evdev does in from_device
|
2020-11-30 15:22:17 +00:00
|
|
|
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
|
|
|
|
|
|
|
|
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-11-30 15:22:17 +00:00
|
|
|
# TODO do select.select insted of async_read_loop
|
2020-11-28 14:43:24 +00:00
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
coroutines = []
|
2020-11-18 19:03:37 +00:00
|
|
|
|
2020-11-22 15:54:40 +00:00
|
|
|
logger.info('Starting injecting the mapping for %s', self.device)
|
2020-11-18 19:03:37 +00:00
|
|
|
|
2020-11-30 15:22:17 +00:00
|
|
|
paths = get_devices()[self.device]['paths']
|
|
|
|
devices = [self._prepare_device(path) for path in paths]
|
|
|
|
|
2020-11-18 19:03:37 +00:00
|
|
|
# Watch over each one of the potentially multiple devices per hardware
|
2020-11-30 15:22:17 +00:00
|
|
|
for input_device in devices:
|
2020-11-28 14:43:24 +00:00
|
|
|
if input_device is None:
|
|
|
|
continue
|
|
|
|
|
2020-11-30 15:22:17 +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(
|
2020-11-30 15:22:17 +00:00
|
|
|
name=f'key-mapper {self.device}',
|
2020-11-28 14:43:24 +00:00
|
|
|
phys='key-mapper',
|
|
|
|
events=self._modify_capabilities(input_device)
|
2020-11-18 19:03:37 +00:00
|
|
|
)
|
2020-11-30 15:22:17 +00:00
|
|
|
|
2020-11-28 14:43:24 +00:00
|
|
|
coroutine = self._injection_loop(input_device, uinput)
|
|
|
|
coroutines.append(coroutine)
|
2020-11-19 00:40:47 +00:00
|
|
|
|
2020-11-28 14:43:24 +00:00
|
|
|
if len(coroutines) == 0:
|
2020-11-19 00:40:47 +00:00
|
|
|
raise OSError('Could not grab any device')
|
2020-11-18 19:03:37 +00:00
|
|
|
|
2020-11-28 14:43:24 +00:00
|
|
|
loop.run_until_complete(asyncio.gather(*coroutines))
|
|
|
|
|
2020-11-30 15:22:17 +00:00
|
|
|
def _write(self, device, type, keycode, value):
|
2020-11-28 17:39:55 +00:00
|
|
|
"""Actually inject."""
|
2020-11-30 15:22:17 +00:00
|
|
|
device.write(type, keycode, value)
|
2020-11-28 17:39:55 +00:00
|
|
|
device.syn()
|
|
|
|
|
2020-11-28 23:13:13 +00:00
|
|
|
def _macro_write(self, character, value, keymapper_device):
|
|
|
|
"""Handler for macros."""
|
2020-11-30 15:22:17 +00:00
|
|
|
keycode = system_mapping[character]
|
2020-11-28 23:28:46 +00:00
|
|
|
logger.spam(
|
|
|
|
'macro writes code:%s value:%d char:%s',
|
|
|
|
keycode, value, character
|
|
|
|
)
|
2020-11-30 15:22:17 +00:00
|
|
|
self._write(
|
|
|
|
keymapper_device,
|
2020-11-30 17:59:34 +00:00
|
|
|
evdev.ecodes.EV_KEY,
|
|
|
|
keycode - KEYCODE_OFFSET,
|
2020-11-30 15:22:17 +00:00
|
|
|
value
|
|
|
|
)
|
2020-11-28 23:13:13 +00:00
|
|
|
|
2020-11-28 14:43:24 +00:00
|
|
|
async def _injection_loop(self, device, keymapper_device):
|
|
|
|
"""Inject keycodes for one of the virtual devices.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
device : evdev.InputDevice
|
|
|
|
where to read keycodes from
|
|
|
|
keymapper_device : evdev.UInput
|
|
|
|
where to write keycodes to
|
|
|
|
"""
|
2020-11-30 15:22:17 +00:00
|
|
|
# TODO this function is too long
|
2020-11-28 21:54:22 +00:00
|
|
|
# Parse all macros beforehand
|
|
|
|
logger.debug('Parsing macros')
|
|
|
|
macros = {}
|
|
|
|
for keycode, output in self.mapping:
|
2020-11-29 09:42:20 +00:00
|
|
|
if '(' in output and ')' in output and len(output) >= 4:
|
2020-11-28 21:54:22 +00:00
|
|
|
# probably a macro
|
|
|
|
macros[keycode] = parse(
|
|
|
|
output,
|
2020-11-28 23:13:13 +00:00
|
|
|
lambda *args: self._macro_write(*args, keymapper_device)
|
2020-11-28 21:54:22 +00:00
|
|
|
)
|
|
|
|
|
2020-11-28 14:43:24 +00:00
|
|
|
logger.debug(
|
|
|
|
'Started injecting into %s, fd %s',
|
|
|
|
keymapper_device.device.path, keymapper_device.fd
|
|
|
|
)
|
|
|
|
|
2020-11-30 18:40:17 +00:00
|
|
|
newest_abs_event = None
|
|
|
|
abs_x = None
|
|
|
|
abs_y = None
|
|
|
|
|
|
|
|
# events only take ints, so a movement of 0.3 needs to add up to
|
|
|
|
# 1.2 to affect the cursor.
|
|
|
|
pending_x_rel = 0
|
|
|
|
pending_y_rel = 0
|
|
|
|
|
|
|
|
async def spam_mouse_movements():
|
|
|
|
while True:
|
|
|
|
# TODO get absinfo beforehand
|
|
|
|
max_value = 32767
|
|
|
|
|
|
|
|
if abs_y is not None and abs_x is not None:
|
|
|
|
speed = (abs_x ** 2 + abs_y ** 2) ** 0.5
|
|
|
|
max_speed = ((max_value ** 2) * 2) ** 0.5
|
|
|
|
non_linearity = 2
|
|
|
|
factor = (speed / max_speed) ** non_linearity
|
|
|
|
rel_x = abs_x / max_value * factor * 40
|
|
|
|
rel_y = abs_y / max_value * factor * 40
|
|
|
|
|
|
|
|
pending_x_rel = rel_x
|
|
|
|
pending_y_rel = rel_y
|
|
|
|
rel_x = int(pending_x_rel)
|
|
|
|
rel_y = int(pending_y_rel)
|
|
|
|
pending_x_rel -= rel_x
|
|
|
|
pending_y_rel -= rel_y
|
|
|
|
|
|
|
|
print('factor', factor)
|
|
|
|
print('speed', speed)
|
|
|
|
print(rel_x, rel_y)
|
|
|
|
|
|
|
|
self._write(
|
|
|
|
keymapper_device,
|
|
|
|
evdev.ecodes.EV_REL,
|
|
|
|
evdev.ecodes.ABS_Y,
|
|
|
|
rel_y
|
|
|
|
)
|
|
|
|
|
|
|
|
self._write(
|
|
|
|
keymapper_device,
|
|
|
|
evdev.ecodes.EV_REL,
|
|
|
|
evdev.ecodes.ABS_X,
|
|
|
|
rel_x
|
|
|
|
)
|
|
|
|
|
|
|
|
await asyncio.sleep(1 / 60)
|
|
|
|
|
|
|
|
asyncio.ensure_future(spam_mouse_movements())
|
|
|
|
|
2020-11-28 14:43:24 +00:00
|
|
|
async for event in device.async_read_loop():
|
2020-11-30 15:22:17 +00:00
|
|
|
if self.map_abs_to_rel() and event.type == evdev.ecodes.EV_ABS:
|
|
|
|
if event.code not in [evdev.ecodes.ABS_X, evdev.ecodes.ABS_Y]:
|
|
|
|
continue
|
2020-11-30 18:40:17 +00:00
|
|
|
|
|
|
|
if event.code == evdev.ecodes.ABS_X:
|
|
|
|
abs_x = event.value
|
|
|
|
|
|
|
|
if event.code == evdev.ecodes.ABS_Y:
|
|
|
|
abs_y = event.value
|
|
|
|
|
2020-11-30 15:22:17 +00:00
|
|
|
continue
|
|
|
|
|
2020-11-28 14:43:24 +00:00
|
|
|
if event.type != evdev.ecodes.EV_KEY:
|
|
|
|
keymapper_device.write(event.type, event.code, event.value)
|
|
|
|
# this already includes SYN events, so need to syn here again
|
|
|
|
continue
|
|
|
|
|
|
|
|
if event.value == 2:
|
|
|
|
# linux does them itself, no need to trigger them
|
|
|
|
continue
|
|
|
|
|
|
|
|
input_keycode = event.code + KEYCODE_OFFSET
|
|
|
|
|
|
|
|
character = self.mapping.get_character(input_keycode)
|
|
|
|
|
|
|
|
if character is None:
|
|
|
|
# unknown keycode, forward it
|
|
|
|
target_keycode = input_keycode
|
2020-11-28 23:28:46 +00:00
|
|
|
elif macros.get(input_keycode) is not None:
|
2020-11-28 21:54:22 +00:00
|
|
|
if event.value == 0:
|
|
|
|
continue
|
|
|
|
|
2020-11-28 17:39:55 +00:00
|
|
|
logger.spam(
|
|
|
|
'got code:%s value:%s, maps to macro %s',
|
|
|
|
event.code + KEYCODE_OFFSET,
|
|
|
|
event.value,
|
|
|
|
character
|
|
|
|
)
|
2020-11-28 21:54:22 +00:00
|
|
|
macro = macros.get(input_keycode)
|
|
|
|
if macro is not None:
|
|
|
|
asyncio.ensure_future(macro.run())
|
|
|
|
continue
|
2020-11-28 14:43:24 +00:00
|
|
|
else:
|
2020-11-30 15:22:17 +00:00
|
|
|
# TODO compile int-int mapping instead of going this route.
|
|
|
|
# I think that makes the reverse mapping obsolete.
|
2020-11-30 17:59:34 +00:00
|
|
|
target_keycode = system_mapping.get(character)
|
2020-11-28 14:43:24 +00:00
|
|
|
if target_keycode is None:
|
|
|
|
logger.error(
|
2020-11-30 17:59:34 +00:00
|
|
|
'Don\'t know what %s maps to',
|
2020-11-28 14:43:24 +00:00
|
|
|
character
|
|
|
|
)
|
|
|
|
continue
|
|
|
|
|
2020-11-30 17:59:34 +00:00
|
|
|
logger.spam(
|
|
|
|
'got code:%s value:%s, maps to code:%s char:%s',
|
|
|
|
event.code + KEYCODE_OFFSET,
|
|
|
|
event.value,
|
|
|
|
target_keycode,
|
|
|
|
character
|
|
|
|
)
|
2020-11-28 14:43:24 +00:00
|
|
|
|
2020-11-30 15:22:17 +00:00
|
|
|
self._write(
|
|
|
|
keymapper_device,
|
|
|
|
event.type,
|
|
|
|
target_keycode - KEYCODE_OFFSET,
|
|
|
|
event.value
|
|
|
|
)
|
2020-11-28 14:43:24 +00:00
|
|
|
|
2020-11-28 16:49:32 +00:00
|
|
|
# this should only ever happen in tests to avoid blocking them
|
|
|
|
# forever, as soon as all events are consumed. In normal operation
|
|
|
|
# there is no end to the events.
|
|
|
|
logger.error(
|
|
|
|
'The injector for "%s" stopped early',
|
|
|
|
keymapper_device.device.path
|
|
|
|
)
|
|
|
|
|
2020-11-19 10:12:28 +00:00
|
|
|
@ensure_numlock
|
2020-11-18 19:03:37 +00:00
|
|
|
def stop_injecting(self):
|
|
|
|
"""Stop injecting keycodes."""
|
2020-11-20 20:38:59 +00:00
|
|
|
logger.info('Stopping injecting keycodes for device %s', self.device)
|
2020-11-28 14:43:24 +00:00
|
|
|
if self._process is not None and self._process.is_alive():
|
|
|
|
self._process.terminate()
|