input-remapper/inputremapper/injection/numlock.py

84 lines
2.3 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
2022-01-01 12:00:49 +00:00
# input-remapper - GUI for device specific keyboard mappings
2023-02-27 16:07:42 +00:00
# Copyright (C) 2023 sezanzeb <proxima@sezanzeb.de>
#
2022-01-01 12:00:49 +00:00
# This file is part of input-remapper.
#
2022-01-01 12:00:49 +00:00
# input-remapper 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.
#
2022-01-01 12:00:49 +00:00
# input-remapper 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
2022-01-01 12:00:49 +00:00
# along with input-remapper. If not, see <https://www.gnu.org/licenses/>.
"""Functions to handle numlocks.
For unknown reasons the numlock status can change when starting injections,
which is why these functions exist.
"""
import re
import subprocess
2022-01-01 12:00:49 +00:00
from inputremapper.logger import logger
def is_numlock_on():
"""Get the current state of the numlock."""
try:
xset_q = subprocess.check_output(
["xset", "q"],
stderr=subprocess.STDOUT,
).decode()
2021-09-26 10:44:56 +00:00
num_lock_status = re.search(r"Num Lock:\s+(.+?)\s", xset_q)
if num_lock_status is not None:
2021-09-26 10:44:56 +00:00
return num_lock_status[1] == "on"
return False
except (FileNotFoundError, subprocess.CalledProcessError):
# tty
return None
def set_numlock(state):
"""Set the numlock to a given state of True or False."""
if state is None:
return
2021-09-26 10:44:56 +00:00
value = {True: "on", False: "off"}[state]
try:
2021-09-26 10:44:56 +00:00
subprocess.check_output(["numlockx", value])
except subprocess.CalledProcessError:
# might be in a tty
pass
except FileNotFoundError:
# doesn't seem to be installed everywhere
2021-09-26 10:44:56 +00:00
logger.debug("numlockx not found")
def ensure_numlock(func):
"""Decorator to reset the numlock to its initial state afterwards."""
2021-09-26 10:44:56 +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)
set_numlock(numlock_before)
return result
2021-09-26 10:44:56 +00:00
return wrapped