input-remapper/keymapper/mapping.py

277 lines
8.5 KiB
Python
Raw Normal View History

2020-11-09 22:16:30 +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-09 22:16:30 +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/>.
2020-11-09 22:34:30 +00:00
"""Contains and manages mappings."""
2020-11-09 22:16:30 +00:00
2020-11-18 09:33:59 +00:00
import os
import json
2020-11-28 14:43:24 +00:00
import copy
2021-04-02 14:33:20 +00:00
from evdev.ecodes import EV_KEY, BTN_LEFT
2020-11-09 22:16:30 +00:00
from keymapper.logger import logger
from keymapper.paths import touch
from keymapper.config import ConfigBase, config
2020-12-31 20:47:56 +00:00
from keymapper.key import Key
2020-12-31 20:46:57 +00:00
2021-01-01 13:09:28 +00:00
DISABLE_NAME = 'disable'
DISABLE_CODE = -1
2020-12-31 20:46:57 +00:00
def split_key(key):
"""Take a key like "1,2,3" and return a 3-tuple of ints."""
2020-12-31 20:47:56 +00:00
key = key.strip()
2020-12-31 20:46:57 +00:00
if ',' not in key:
logger.error('Found invalid key: "%s"', key)
return None
if key.count(',') == 1:
# support for legacy mapping objects that didn't include
# the value in the key
ev_type, code = key.split(',')
value = 1
elif key.count(',') == 2:
ev_type, code, value = key.split(',')
else:
logger.error('Found more than two commas in the key: "%s"', key)
return None
try:
key = (int(ev_type), int(code), int(value))
except ValueError:
logger.error('Found non-int in: "%s"', key)
return None
return key
class Mapping(ConfigBase):
"""Contains and manages mappings and config of a single preset."""
2020-11-09 22:16:30 +00:00
def __init__(self):
2020-12-31 20:47:56 +00:00
self._mapping = {} # a mapping of Key objects to strings
2020-11-09 22:16:30 +00:00
self.changed = False
2021-01-07 16:15:12 +00:00
# are there actually any keys set in the mapping file?
self.num_saved_keys = 0
super().__init__(fallback=config)
2020-11-30 20:17:14 +00:00
2020-11-09 22:16:30 +00:00
def __iter__(self):
2020-12-31 20:47:56 +00:00
"""Iterate over Key objects and their character."""
2020-12-31 20:46:57 +00:00
return iter(self._mapping.items())
2020-11-09 22:16:30 +00:00
def __len__(self):
return len(self._mapping)
2020-12-27 14:38:08 +00:00
def set(self, *args):
"""Set a config value. See `ConfigBase.set`."""
self.changed = True
return super().set(*args)
def remove(self, *args):
"""Remove a config value. See `ConfigBase.remove`."""
self.changed = True
return super().remove(*args)
def change(self, new_key, character, previous_key=None):
2020-11-09 22:16:30 +00:00
"""Replace the mapping of a keycode with a different one.
Parameters
----------
2020-12-31 20:47:56 +00:00
new_key : Key
character : string
A single character known to xkb or linux.
Examples: KEY_KP1, Shift_L, a, B, BTN_LEFT.
2020-12-31 20:47:56 +00:00
previous_key : Key or None
the previous key
If not set, will not remove any previous mapping. If you recently
used (1, 10, 1) for new_key and want to overwrite that with
2021-02-05 11:59:29 +00:00
(1, 11, 1), provide (1, 10, 1) here.
2020-11-09 22:16:30 +00:00
"""
2020-12-31 20:47:56 +00:00
if not isinstance(new_key, Key):
raise TypeError(f'Expected {new_key} to be a Key object')
if character is None:
raise ValueError('Expected `character` not to be None')
character = character.strip()
logger.debug('%s will map to "%s"', new_key, character)
2020-12-31 20:46:57 +00:00
self.clear(new_key) # this also clears all equivalent keys
self._mapping[new_key] = character
if previous_key is not None:
code_changed = new_key != previous_key
if code_changed:
2020-11-09 22:16:30 +00:00
# clear previous mapping of that code, because the line
# representing that one will now represent a different one
self.clear(previous_key)
2020-11-09 22:16:30 +00:00
self.changed = True
2020-11-09 22:16:30 +00:00
def clear(self, key):
2020-11-09 22:16:30 +00:00
"""Remove a keycode from the mapping.
Parameters
----------
2020-12-31 20:47:56 +00:00
key : Key
2020-11-09 22:16:30 +00:00
"""
2020-12-31 20:47:56 +00:00
if not isinstance(key, Key):
raise TypeError('Expected key to be a Key object')
2020-12-31 20:46:57 +00:00
2020-12-31 20:47:56 +00:00
for permutation in key.get_permutations():
if permutation in self._mapping:
logger.debug('%s will be cleared', permutation)
del self._mapping[permutation]
self.changed = True
2021-01-10 14:16:22 +00:00
# there should be only one variation of the permutations
# in the mapping actually
2020-11-09 22:16:30 +00:00
def empty(self):
"""Remove all mappings."""
self._mapping = {}
self.changed = True
def load(self, path):
"""Load a dumped JSON from home to overwrite the mappings.
Parameters
path : string
Path of the preset file
"""
2020-11-22 20:04:09 +00:00
logger.info('Loading preset from "%s"', path)
2020-11-18 09:33:59 +00:00
if not os.path.exists(path):
raise FileNotFoundError(
f'Tried to load non-existing preset "{path}"'
)
2020-11-18 09:33:59 +00:00
self.clear_config()
2020-11-22 20:41:29 +00:00
with open(path, 'r') as file:
2020-11-30 20:17:14 +00:00
preset_dict = json.load(file)
if not isinstance(preset_dict.get('mapping'), dict):
2021-01-07 16:15:12 +00:00
logger.error(
'Expected mapping to be a dict, but was %s. '
'Invalid preset config at "%s"',
preset_dict.get('mapping'), path
)
return
2020-12-02 18:33:31 +00:00
for key, character in preset_dict['mapping'].items():
2020-12-31 20:47:56 +00:00
try:
key = Key(*[
split_key(chunk) for chunk in key.split('+')
if chunk.strip() != ''
])
except ValueError as error:
logger.error(str(error))
continue
if None in key:
continue
logger.spam('%s maps to %s', key, character)
self._mapping[key] = character
2020-11-18 09:33:59 +00:00
# add any metadata of the mapping
2020-11-30 20:17:14 +00:00
for key in preset_dict:
if key == 'mapping':
continue
self._config[key] = preset_dict[key]
2020-11-30 20:17:14 +00:00
2020-11-18 09:33:59 +00:00
self.changed = False
2021-01-07 16:15:12 +00:00
self.num_saved_keys = len(self)
2020-11-28 14:43:24 +00:00
def clone(self):
"""Create a copy of the mapping."""
mapping = Mapping()
mapping._mapping = copy.deepcopy(self._mapping)
mapping.changed = self.changed
2020-11-28 14:48:57 +00:00
return mapping
2020-11-28 14:43:24 +00:00
def save(self, path):
"""Dump as JSON into home."""
2020-11-18 09:33:59 +00:00
logger.info('Saving preset to %s', path)
touch(path)
2020-11-18 09:33:59 +00:00
2020-11-22 20:41:29 +00:00
with open(path, 'w') as file:
if self._config.get('mapping') is not None:
logger.error(
2021-01-07 16:15:12 +00:00
'"mapping" is reserved and cannot be used as config '
'key: %s',
self._config.get('mapping')
)
2021-01-07 16:15:12 +00:00
preset_dict = self._config.copy() # shallow copy
# make sure to keep the option to add metadata if ever needed,
# so put the mapping into a special key
2020-12-02 18:33:31 +00:00
json_ready_mapping = {}
# tuple keys are not possible in json, encode them as string
2020-12-02 18:33:31 +00:00
for key, value in self._mapping.items():
2020-12-31 20:47:56 +00:00
new_key = '+'.join([
','.join([
str(value)
for value in sub_key
2020-12-31 20:46:57 +00:00
])
2020-12-31 20:47:56 +00:00
for sub_key in key
])
2020-12-02 18:33:31 +00:00
json_ready_mapping[new_key] = value
preset_dict['mapping'] = json_ready_mapping
2020-11-30 20:17:14 +00:00
json.dump(preset_dict, file, indent=4)
2020-11-22 20:41:29 +00:00
file.write('\n')
2020-11-18 09:33:59 +00:00
self.changed = False
2021-01-07 16:15:12 +00:00
self.num_saved_keys = len(self)
def get_character(self, key):
2020-11-09 22:16:30 +00:00
"""Read the character that is mapped to this keycode.
Parameters
----------
2021-04-02 14:33:20 +00:00
key : Key
2020-11-09 22:16:30 +00:00
"""
2020-12-31 20:47:56 +00:00
if not isinstance(key, Key):
raise TypeError('Expected key to be a Key object')
for permutation in key.get_permutations():
existing = self._mapping.get(permutation)
if existing is not None:
return existing
2021-01-01 21:20:33 +00:00
return None
2021-04-02 14:33:20 +00:00
def dangerously_mapped_btn_left(self):
"""Return True if this mapping disables BTN_Left."""
if self.get_character(Key(EV_KEY, BTN_LEFT, 1)) is not None:
values = [value.lower() for value in self._mapping.values()]
return 'btn_left' not in values
return False