input-remapper/keymapper/injection/macros.py

586 lines
18 KiB
Python
Raw Normal View History

2020-11-27 20:27:15 +00:00
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# key-mapper - GUI for device specific keyboard mappings
2021-02-22 18:48:20 +00:00
# Copyright (C) 2021 sezanzeb <proxima@sezanzeb.de>
2020-11-27 20:27:15 +00:00
#
# 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/>.
"""Executes more complex patterns of keystrokes.
To keep it short on the UI, the available functions are one-letter long.
2020-11-28 19:59:24 +00:00
The outermost macro (in the examples below the one created by 'r',
2020-11-27 20:27:15 +00:00
'r' and 'w') will be started, which triggers a chain reaction to execute
all of the configured stuff.
Examples
--------
2020-11-28 19:59:24 +00:00
r(3, k(a).w(10)): a <10ms> a <10ms> a
r(2, k(a).k(-)).k(b): a - a - b
w(1000).m(Shift_L, r(2, k(a))).w(10).k(b): <1s> A A <10ms> b
2020-11-27 20:27:15 +00:00
"""
2020-11-28 19:59:24 +00:00
import asyncio
2020-11-28 16:49:32 +00:00
import re
2021-03-19 22:03:03 +00:00
import copy
from evdev.ecodes import ecodes, EV_KEY, EV_REL, REL_X, REL_Y, REL_WHEEL, \
REL_HWHEEL
2020-11-27 20:27:15 +00:00
2020-11-28 16:49:32 +00:00
from keymapper.logger import logger
2020-12-04 13:38:41 +00:00
from keymapper.state import system_mapping
2020-11-27 20:27:15 +00:00
2020-12-04 13:38:41 +00:00
def is_this_a_macro(output):
"""Figure out if this is a macro."""
2020-12-05 12:08:07 +00:00
if not isinstance(output, str):
return False
if '+' in output.strip():
# for example "a + b"
return True
2020-12-04 16:38:04 +00:00
return '(' in output and ')' in output and len(output) >= 4
2020-12-04 13:38:41 +00:00
class _Macro:
2020-12-05 10:13:10 +00:00
"""Supports chaining and preparing actions.
Calling functions on _Macro does not inject anything yet, it means that
once .run is used it will be executed along with all other queued tasks.
"""
def __init__(self, code, mapping):
2020-11-28 17:27:28 +00:00
"""Create a macro instance that can be populated with tasks.
Parameters
----------
2021-03-19 22:03:03 +00:00
code : string or None
2020-12-02 15:17:52 +00:00
The original parsed code, for logging purposes.
mapping : Mapping
The preset object, needed for some config stuff
2020-11-28 17:27:28 +00:00
"""
2020-11-27 20:27:15 +00:00
self.tasks = []
2020-12-02 15:17:52 +00:00
self.code = code
self.mapping = mapping
2020-12-05 10:13:10 +00:00
# is a lock so that h() can be realized
self._holding_lock = asyncio.Lock()
2020-11-27 20:27:15 +00:00
2020-12-06 13:23:00 +00:00
self.running = False
2020-12-04 13:38:41 +00:00
# all required capabilities, without those of child macros
2021-03-19 22:03:03 +00:00
self.capabilities = {
EV_KEY: set(),
EV_REL: set(),
}
2020-12-05 10:58:29 +00:00
2020-12-05 10:13:10 +00:00
self.child_macros = []
2020-12-04 13:38:41 +00:00
def is_holding(self):
"""Check if the macro is waiting for a key to be released."""
return self._holding_lock.locked()
2020-12-04 13:38:41 +00:00
def get_capabilities(self):
"""Resolve all capabilities of the macro and those of its children."""
2021-03-19 22:03:03 +00:00
capabilities = copy.deepcopy(self.capabilities)
2020-12-05 10:13:10 +00:00
for macro in self.child_macros:
2021-03-19 22:03:03 +00:00
macro_capabilities = macro.get_capabilities()
for ev_type in macro_capabilities:
if ev_type not in capabilities:
capabilities[ev_type] = set()
capabilities[ev_type].update(macro_capabilities[ev_type])
2020-12-04 13:38:41 +00:00
return capabilities
2021-02-13 19:19:31 +00:00
async def run(self, handler):
"""Run the macro.
2020-12-04 13:38:41 +00:00
Parameters
----------
2021-02-13 19:19:31 +00:00
handler : function
2021-03-19 22:03:03 +00:00
Will receive int type, code and value for an event to write
2020-12-04 13:38:41 +00:00
"""
2021-02-20 13:15:40 +00:00
if self.running:
logger.error('Tried to run already running macro "%s"', self.code)
return
2020-12-06 13:23:00 +00:00
self.running = True
2021-03-19 22:03:03 +00:00
for task in self.tasks:
# one could call tasks the compiled macros. it's lambda functions
# that receive the handler as an argument, so that they know
# where to send the event to.
2021-02-13 19:19:31 +00:00
coroutine = task(handler)
2020-11-28 19:59:24 +00:00
if asyncio.iscoroutine(coroutine):
await coroutine
2020-11-27 20:27:15 +00:00
2020-12-06 13:23:00 +00:00
# done
self.running = False
def press_key(self):
"""The user pressed the key down."""
if self.is_holding():
logger.error('Already holding')
return
asyncio.ensure_future(self._holding_lock.acquire())
for macro in self.child_macros:
macro.press_key()
2020-12-05 10:13:10 +00:00
2020-12-05 10:58:29 +00:00
def release_key(self):
"""The user released the key."""
if self._holding_lock is not None:
self._holding_lock.release()
2020-12-05 10:58:29 +00:00
for macro in self.child_macros:
macro.release_key()
def hold(self, macro=None):
2020-12-05 10:13:10 +00:00
"""Loops the execution until key release."""
if macro is None:
# no parameters: block until released
2021-02-13 19:19:31 +00:00
async def task(_):
# wait until the key is released. Only then it will be
# able to acquire the lock. Release it right after so that
# it can be acquired by press_key again.
try:
await self._holding_lock.acquire()
self._holding_lock.release()
except RuntimeError as error:
# The specific bug in question has been fixed already,
# but lets keep this check here for the future. Not
# catching errors here causes the macro to never be
# released
logger.error('Failed h(): %s', error)
2021-03-19 22:03:03 +00:00
self.tasks.append(task)
else:
if not isinstance(macro, _Macro):
raise ValueError(
'Expected the param for h (hold) to be '
f'a macro (like k(a)), but got "{macro}"'
)
2021-02-13 19:19:31 +00:00
async def task(handler):
while self.is_holding():
# run the child macro completely to avoid
# not-releasing any key
2021-02-13 19:19:31 +00:00
await macro.run(handler)
2021-03-19 22:03:03 +00:00
self.tasks.append(task)
self.child_macros.append(macro)
2020-12-05 10:58:29 +00:00
2020-12-05 10:13:10 +00:00
return self
2020-11-28 16:49:32 +00:00
def modify(self, modifier, macro):
2020-11-27 20:27:15 +00:00
"""Do stuff while a modifier is activated.
Parameters
----------
modifier : str
macro : _Macro
2020-11-27 20:27:15 +00:00
"""
2020-12-04 13:52:08 +00:00
if not isinstance(macro, _Macro):
raise ValueError(
2020-12-05 12:08:07 +00:00
'Expected the second param for m (modify) to be '
f'a macro (like k(a)), but got {macro}'
2020-12-04 13:52:08 +00:00
)
2020-12-04 13:38:41 +00:00
modifier = str(modifier)
code = system_mapping.get(modifier)
if code is None:
raise KeyError(f'Unknown modifier "{modifier}"')
2021-03-19 22:03:03 +00:00
self.capabilities[EV_KEY].add(code)
2020-12-04 13:38:41 +00:00
2020-12-05 10:58:29 +00:00
self.child_macros.append(macro)
2021-03-19 22:03:03 +00:00
self.tasks.append(lambda handler: handler(EV_KEY, code, 1))
2020-11-28 21:54:22 +00:00
self.add_keycode_pause()
2021-03-19 22:03:03 +00:00
self.tasks.append(macro.run)
2020-11-28 21:54:22 +00:00
self.add_keycode_pause()
2021-03-19 22:03:03 +00:00
self.tasks.append(lambda handler: handler(EV_KEY, code, 0))
2020-11-28 21:54:22 +00:00
self.add_keycode_pause()
2020-11-27 20:27:15 +00:00
return self
2020-11-28 16:49:32 +00:00
def repeat(self, repeats, macro):
2020-11-27 20:27:15 +00:00
"""Repeat actions.
Parameters
----------
repeats : int
macro : _Macro
2020-11-27 20:27:15 +00:00
"""
2020-12-04 13:52:08 +00:00
if not isinstance(macro, _Macro):
raise ValueError(
2020-12-05 12:08:07 +00:00
'Expected the second param for r (repeat) to be '
f'a macro (like k(a)), but got "{macro}"'
2020-12-04 13:52:08 +00:00
)
2020-12-04 18:21:54 +00:00
try:
repeats = int(repeats)
except ValueError as error:
2020-12-04 18:21:54 +00:00
raise ValueError(
2020-12-05 12:08:07 +00:00
'Expected the first param for r (repeat) to be '
2020-12-04 18:21:54 +00:00
f'a number, but got "{repeats}"'
) from error
2020-12-04 13:52:08 +00:00
2020-11-27 20:27:15 +00:00
for _ in range(repeats):
2021-03-19 22:03:03 +00:00
self.tasks.append(macro.run)
2020-12-05 10:58:29 +00:00
self.child_macros.append(macro)
2020-11-27 20:27:15 +00:00
return self
2020-11-28 21:54:22 +00:00
def add_keycode_pause(self):
"""To add a pause between keystrokes."""
sleeptime = self.mapping.get('macros.keystroke_sleep_ms') / 1000
2020-11-28 21:54:22 +00:00
2021-02-13 19:19:31 +00:00
async def sleep(_):
2020-11-28 21:54:22 +00:00
await asyncio.sleep(sleeptime)
2021-03-19 22:03:03 +00:00
self.tasks.append(sleep)
2020-11-28 21:54:22 +00:00
2020-11-28 16:49:32 +00:00
def keycode(self, character):
2020-11-28 14:43:24 +00:00
"""Write the character."""
2020-12-04 13:38:41 +00:00
character = str(character)
code = system_mapping.get(character)
if code is None:
2021-03-19 22:03:03 +00:00
raise KeyError(f'Unknown key "{character}"')
2020-12-04 13:38:41 +00:00
2021-03-19 22:03:03 +00:00
self.capabilities[EV_KEY].add(code)
2020-12-04 13:38:41 +00:00
2021-03-19 22:03:03 +00:00
self.tasks.append(lambda handler: handler(EV_KEY, code, 1))
self.add_keycode_pause()
self.tasks.append(lambda handler: handler(EV_KEY, code, 0))
2020-11-28 21:54:22 +00:00
self.add_keycode_pause()
2021-03-19 22:03:03 +00:00
return self
def event(self, ev_type, code, value):
"""Write any event.
Parameters
----------
ev_type: str or int
examples: 2, 'EV_KEY'
code : int or int
examples: 52, 'KEY_A'
value : int
"""
if isinstance(ev_type, str):
ev_type = ecodes[ev_type.upper()]
if isinstance(code, str):
code = ecodes[code.upper()]
if ev_type not in self.capabilities:
self.capabilities[ev_type] = set()
if ev_type == EV_REL:
# add all capabilities that are required for the display server
# to recognize the device as mouse
self.capabilities[EV_REL].add(REL_X)
self.capabilities[EV_REL].add(REL_Y)
self.capabilities[EV_REL].add(REL_WHEEL)
self.capabilities[ev_type].add(code)
self.tasks.append(lambda handler: handler(ev_type, code, value))
2020-11-28 21:54:22 +00:00
self.add_keycode_pause()
2021-03-19 22:03:03 +00:00
2020-11-27 20:27:15 +00:00
return self
2021-03-19 22:03:03 +00:00
def mouse(self, direction, speed):
"""Shortcut for h(e(...))."""
code, value = {
'up': (REL_Y, -1),
'down': (REL_Y, 1),
'left': (REL_X, -1),
'right': (REL_X, 1),
}[direction.lower()]
value *= speed
child_macro = _Macro(None, self.mapping)
child_macro.event(EV_REL, code, value)
self.hold(child_macro)
def wheel(self, direction, speed):
"""Shortcut for h(e(...))."""
code, value = {
'up': (REL_WHEEL, 1),
'down': (REL_WHEEL, -1),
'left': (REL_HWHEEL, 1),
'right': (REL_HWHEEL, -1),
}[direction.lower()]
child_macro = _Macro(None, self.mapping)
child_macro.event(EV_REL, code, value)
child_macro.wait(100 / speed)
self.hold(child_macro)
2020-11-28 21:54:22 +00:00
def wait(self, sleeptime):
"""Wait time in milliseconds."""
2020-12-04 18:21:54 +00:00
try:
sleeptime = int(sleeptime)
except ValueError as error:
2020-12-04 18:21:54 +00:00
raise ValueError(
2020-12-05 12:08:07 +00:00
'Expected the param for w (wait) to be '
2020-12-04 18:21:54 +00:00
f'a number, but got "{sleeptime}"'
) from error
2020-12-04 18:21:54 +00:00
2020-11-28 21:54:22 +00:00
sleeptime /= 1000
2020-11-28 19:59:24 +00:00
2021-02-13 19:19:31 +00:00
async def sleep(_):
2020-11-28 21:54:22 +00:00
await asyncio.sleep(sleeptime)
2021-03-19 22:03:03 +00:00
self.tasks.append(sleep)
2020-11-27 20:27:15 +00:00
return self
def _extract_params(inner):
2020-11-28 16:49:32 +00:00
"""Extract parameters from the inner contents of a call.
Parameters
----------
inner : string
for example 'r, r(2, k(a))' should result in ['r', 'r(2, k(a)']
"""
inner = inner.strip()
brackets = 0
params = []
start = 0
for position, char in enumerate(inner):
if char == '(':
brackets += 1
if char == ')':
brackets -= 1
2020-12-04 18:21:54 +00:00
if char == ',' and brackets == 0:
2020-11-28 16:49:32 +00:00
# , potentially starts another parameter, but only if
# the current brackets are all closed.
params.append(inner[start:position].strip())
# skip the comma
start = position + 1
2020-12-04 18:21:54 +00:00
# one last parameter
params.append(inner[start:].strip())
2020-11-28 16:49:32 +00:00
return params
2020-11-29 00:53:12 +00:00
def _count_brackets(macro):
"""Find where the first opening bracket closes."""
2020-12-04 18:21:54 +00:00
openings = macro.count('(')
closings = macro.count(')')
if openings != closings:
raise Exception(
f'You entered {openings} opening and {closings} '
'closing brackets'
)
2020-11-29 00:53:12 +00:00
brackets = 0
position = 0
for char in macro:
position += 1
if char == '(':
brackets += 1
continue
if char == ')':
brackets -= 1
if brackets == 0:
# the closing bracket of the call
break
2020-12-01 23:02:41 +00:00
return position
2020-11-29 00:53:12 +00:00
def _parse_recurse(macro, mapping, macro_instance=None, depth=0):
2020-11-28 16:49:32 +00:00
"""Handle a subset of the macro, e.g. one parameter or function call.
Parameters
----------
macro : string
Just like parse
mapping : Mapping
The preset configuration
macro_instance : _Macro or None
2020-11-28 16:49:32 +00:00
A macro instance to add tasks to
depth : int
"""
# to anyone who knows better about compilers and thinks this is horrible:
# please make a pull request. Because it probably is.
# not using eval for security reasons ofc. And this syntax doesn't need
# string quotes for its params.
2020-11-28 17:27:28 +00:00
# If this gets more complicated than that I'd rather make a macro
# editor GUI and store them as json.
assert isinstance(macro, str)
assert isinstance(depth, int)
if macro == '':
return None
2020-11-28 16:49:32 +00:00
if macro_instance is None:
macro_instance = _Macro(macro, mapping)
2020-11-28 17:27:28 +00:00
else:
assert isinstance(macro_instance, _Macro)
2020-11-28 16:49:32 +00:00
macro = macro.strip()
space = ' ' * depth
# is it another macro?
2020-11-28 22:44:40 +00:00
call_match = re.match(r'^(\w+)\(', macro)
2020-11-28 16:49:32 +00:00
call = call_match[1] if call_match else None
if call is not None:
# available functions in the macro and the minimum and maximum number
# of their parameters
2020-11-28 16:49:32 +00:00
functions = {
'm': (macro_instance.modify, 2, 2),
'r': (macro_instance.repeat, 2, 2),
'k': (macro_instance.keycode, 1, 1),
2021-03-19 22:03:03 +00:00
'e': (macro_instance.event, 3, 3),
'w': (macro_instance.wait, 1, 1),
2021-03-19 22:03:03 +00:00
'h': (macro_instance.hold, 0, 1),
'mouse': (macro_instance.mouse, 2, 2),
'wheel': (macro_instance.wheel, 2, 2)
2020-11-28 16:49:32 +00:00
}
function = functions.get(call)
if function is None:
2020-11-28 22:50:28 +00:00
raise Exception(f'Unknown function {call}')
2020-11-28 16:49:32 +00:00
# get all the stuff inbetween
2020-12-01 23:02:41 +00:00
position = _count_brackets(macro)
2020-11-28 16:49:32 +00:00
2021-03-19 22:03:03 +00:00
inner = macro[macro.index('(') + 1:position - 1]
2020-11-28 16:49:32 +00:00
# split "3, k(a).w(10)" into parameters
string_params = _extract_params(inner)
2020-11-28 16:49:32 +00:00
logger.spam('%scalls %s with %s', space, call, string_params)
# evaluate the params
params = [
_parse_recurse(param.strip(), mapping, None, depth + 1)
2020-11-28 16:49:32 +00:00
for param in string_params
]
2020-11-28 22:50:28 +00:00
logger.spam('%sadd call to %s with %s', space, call, params)
2020-12-04 18:21:54 +00:00
if len(params) < function[1] or len(params) > function[2]:
if function[1] != function[2]:
msg = (
f'{call} takes between {function[1]} and {function[2]}, '
f'not {len(params)} parameters'
)
else:
msg = (
f'{call} takes {function[1]}, '
f'not {len(params)} parameters'
)
raise ValueError(msg)
function[0](*params)
2020-11-28 16:49:32 +00:00
# is after this another call? Chain it to the macro_instance
if len(macro) > position and macro[position] == '.':
chain = macro[position + 1:]
logger.spam('%sfollowed by %s', space, chain)
_parse_recurse(chain, mapping, macro_instance, depth)
2020-11-28 16:49:32 +00:00
return macro_instance
2020-11-29 00:53:12 +00:00
# probably a parameter for an outer function
try:
2020-12-04 13:52:08 +00:00
# if possible, parse as int
2020-11-29 00:53:12 +00:00
macro = int(macro)
except ValueError:
2020-12-04 13:52:08 +00:00
# use as string instead
2020-11-29 00:53:12 +00:00
pass
2020-12-04 13:52:08 +00:00
2020-11-29 00:53:12 +00:00
logger.spam('%s%s %s', space, type(macro), macro)
return macro
def handle_plus_syntax(macro):
"""transform a + b + c to m(a, m(b, m(c, h())))"""
if '+' not in macro:
return macro
if '(' in macro or ')' in macro:
logger.error('Mixing "+" and macros is unsupported: "%s"', macro)
return macro
chunks = [chunk.strip() for chunk in macro.split('+')]
output = ''
depth = 0
for chunk in chunks:
if chunk == '':
# invalid syntax
logger.error('Invalid syntax for "%s"', macro)
return macro
depth += 1
output += f'm({chunk},'
output += 'h()'
output += depth * ')'
logger.debug('Transformed "%s" to "%s"', macro, output)
return output
def parse(macro, mapping, return_errors=False):
"""parse and generate a _Macro that can be run as often as you want.
2021-02-13 19:19:31 +00:00
If it could not be parsed, possibly due to syntax errors, will log the
error and return None.
2020-12-04 13:52:08 +00:00
Parameters
----------
macro : string
"r(3, k(a).w(10))"
"r(2, k(a).k(-)).k(b)"
"w(1000).m(Shift_L, r(2, k(a))).w(10, 20).k(b)"
mapping : Mapping
The preset object, needed for some config stuff
2020-12-05 12:08:07 +00:00
return_errors : bool
2021-01-25 23:14:52 +00:00
If True, returns errors as a string or None if parsing worked.
If False, returns the parsed macro.
"""
macro = handle_plus_syntax(macro)
2020-11-28 22:44:40 +00:00
# whitespaces, tabs, newlines and such don't serve a purpose. make
2020-11-28 22:50:28 +00:00
# the log output clearer and the parsing easier.
2020-11-28 22:44:40 +00:00
macro = re.sub(r'\s', '', macro)
2020-12-04 18:21:54 +00:00
if '"' in macro or "'" in macro:
logger.info('Quotation marks in macros are not needed')
macro = macro.replace('"', '').replace("'", '')
2020-12-05 12:08:07 +00:00
if return_errors:
logger.spam('checking the syntax of %s', macro)
else:
logger.spam('preparing macro %s for later execution', macro)
try:
macro_object = _parse_recurse(macro, mapping)
2020-12-05 12:08:07 +00:00
return macro_object if not return_errors else None
2020-11-29 00:53:12 +00:00
except Exception as error:
2021-03-19 22:03:03 +00:00
logger.error('Failed to parse macro "%s": %s', macro, error.__repr__())
2020-12-05 12:08:07 +00:00
return str(error) if return_errors else None