input-remapper/keymapper/dev/macros.py

359 lines
10 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
# 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/>.
"""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
2020-11-27 20:27:15 +00:00
2020-11-28 16:49:32 +00:00
from keymapper.logger import logger
2020-11-28 21:54:22 +00:00
from keymapper.config import config
2020-12-04 13:38:41 +00:00
from keymapper.state import system_mapping
2020-11-27 20:27:15 +00:00
2020-11-28 22:44:40 +00:00
MODIFIER = 1
CHILD_MACRO = 2
SLEEP = 3
REPEAT = 4
KEYSTROKE = 5
DEBUG = 6
2020-12-04 13:38:41 +00:00
def is_this_a_macro(output):
"""Figure out if this is a macro."""
if '(' in output and ')' in output and len(output) >= 4:
return True
class _Macro:
2020-11-27 20:27:15 +00:00
"""Supports chaining and preparing actions."""
2020-12-04 13:38:41 +00:00
def __init__(self, depth, code):
2020-11-28 17:27:28 +00:00
"""Create a macro instance that can be populated with tasks.
Parameters
----------
2020-11-28 22:44:40 +00:00
depth : int
0 for the outermost parent macro, 1 or greater for child macros,
like the second argument of repeat.
2020-12-02 15:17:52 +00:00
code : string
The original parsed code, for logging purposes.
2020-11-28 17:27:28 +00:00
"""
2020-11-27 20:27:15 +00:00
self.tasks = []
2020-12-04 13:38:41 +00:00
self.handler = lambda *args: logger.error('No handler set')
2020-11-28 22:44:40 +00:00
self.depth = depth
2020-12-02 15:17:52 +00:00
self.code = code
2020-11-27 20:27:15 +00:00
2020-12-04 13:38:41 +00:00
# all required capabilities, without those of child macros
self.capabilities = set()
def get_capabilities(self):
"""Resolve all capabilities of the macro and those of its children."""
capabilities = self.capabilities.copy()
for task_type, task in self.tasks:
if task_type == CHILD_MACRO:
capabilities.update(task.get_capabilities())
return capabilities
def set_handler(self, handler):
"""Set the handler function.
Parameters
----------
handler : func
A function that accepts keycodes as the first parameter and the
key-press state as the second. 1 for down and 0 for up. The
macro will write to this function once executed with `.run()`.
"""
self.handler = handler
for task_type, task in self.tasks:
if task_type == CHILD_MACRO:
task.set_handler(handler)
2020-11-28 19:59:24 +00:00
async def run(self):
2020-11-28 14:43:24 +00:00
"""Run the macro."""
2020-12-04 13:38:41 +00:00
for task_type, task in self.tasks:
if task_type == CHILD_MACRO:
task = task.run
2020-11-28 19:59:24 +00:00
coroutine = task()
if asyncio.iscoroutine(coroutine):
await coroutine
2020-11-27 20:27:15 +00:00
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(
'Expected the second param for repeat to be '
f'a macro, but got {macro}'
)
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}"')
self.capabilities.add(code)
self.tasks.append((MODIFIER, lambda: self.handler(code, 1)))
2020-11-28 21:54:22 +00:00
self.add_keycode_pause()
2020-12-04 13:38:41 +00:00
self.tasks.append((CHILD_MACRO, macro))
2020-11-28 21:54:22 +00:00
self.add_keycode_pause()
2020-12-04 13:38:41 +00:00
self.tasks.append((MODIFIER, lambda: self.handler(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(
'Expected the second param for repeat to be '
f'a macro, but got "{macro}"'
)
2020-12-04 13:38:41 +00:00
repeats = int(repeats)
2020-12-04 13:52:08 +00:00
2020-11-27 20:27:15 +00:00
for _ in range(repeats):
2020-12-04 13:38:41 +00:00
self.tasks.append((CHILD_MACRO, 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."""
2020-12-02 18:33:31 +00:00
sleeptime = config.get('macros.keystroke_sleep_ms') / 1000
2020-11-28 21:54:22 +00:00
async def sleep():
await asyncio.sleep(sleeptime)
2020-11-28 22:44:40 +00:00
self.tasks.append((SLEEP, 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:
raise KeyError(f'Unknown key "{character}"')
self.capabilities.add(code)
self.tasks.append((KEYSTROKE, lambda: self.handler(code, 1)))
2020-11-28 21:54:22 +00:00
self.add_keycode_pause()
2020-12-04 13:38:41 +00:00
self.tasks.append((KEYSTROKE, lambda: self.handler(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 21:54:22 +00:00
def wait(self, sleeptime):
"""Wait time in milliseconds."""
2020-12-04 13:38:41 +00:00
sleeptime = int(sleeptime)
2020-11-28 21:54:22 +00:00
sleeptime /= 1000
2020-11-28 19:59:24 +00:00
2020-11-28 21:54:22 +00:00
async def sleep():
await asyncio.sleep(sleeptime)
2020-11-28 22:44:40 +00:00
self.tasks.append((SLEEP, 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
if (char == ',') and brackets == 0:
# , 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
if brackets == 0 and start != len(inner):
# one last parameter
params.append(inner[start:].strip())
return params
2020-11-29 00:53:12 +00:00
def _count_brackets(macro):
"""Find where the first opening bracket closes."""
brackets = 0
position = 0
for char in macro:
position += 1
if char == '(':
brackets += 1
continue
if char == ')':
brackets -= 1
if brackets < 0:
raise Exception(f'There is one ")" too much at {position}')
if brackets == 0:
# the closing bracket of the call
break
if brackets != 0:
raise Exception(f'There are {brackets} closing brackets missing')
2020-12-01 23:02:41 +00:00
return position
2020-11-29 00:53:12 +00:00
2020-12-04 13:38:41 +00:00
def _parse_recurse(macro, 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
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)
2020-11-28 16:49:32 +00:00
if macro_instance is None:
2020-12-04 13:38:41 +00:00
macro_instance = _Macro(depth, macro)
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
functions = {
'm': macro_instance.modify,
'r': macro_instance.repeat,
'k': macro_instance.keycode,
'w': macro_instance.wait
}
if functions.get(call) 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
inner = macro[2:position - 1]
# 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 = [
2020-12-04 13:38:41 +00:00
_parse_recurse(param.strip(), 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-11-28 16:49:32 +00:00
functions[call](*params)
# 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)
2020-12-04 13:38:41 +00:00
_parse_recurse(chain, 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
2020-12-04 13:38:41 +00:00
def parse(macro):
"""parse and generate a _Macro that can be run as often as you want.
2020-12-04 13:52:08 +00:00
You need to use set_handler on it before running. If it could not
be parsed, possibly due to syntax errors, will log the error and
return None.
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)"
"""
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)
logger.spam('preparing macro %s for later execution', macro)
try:
2020-12-04 13:38:41 +00:00
return _parse_recurse(macro)
2020-11-29 00:53:12 +00:00
except Exception as error:
logger.error('Failed to parse macro "%s": %s', macro, error)
return None