first commit

This commit is contained in:
2025-11-01 06:00:52 +05:30
parent 6a49b604a7
commit ae7194a9f2
2110 changed files with 382375 additions and 0 deletions

View File

@@ -0,0 +1,249 @@
# coding=utf-8
# pynput
# Copyright (C) 2015-2024 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
The module containing keyboard classes.
See the documentation for more information.
"""
# pylint: disable=C0103
# KeyCode, Key, Controller and Listener are not constants
import itertools
from pynput._util import backend, Events
backend = backend(__name__)
KeyCode = backend.KeyCode
Key = backend.Key
Controller = backend.Controller
Listener = backend.Listener
del backend
# pylint: disable=C0326; it is easier to read column aligned keys
#: The keys used as modifiers; the first value in each tuple is the
#: base modifier to use for subsequent modifiers.
_MODIFIER_KEYS = (
(Key.alt_gr, (Key.alt_gr.value,)),
(Key.alt, (Key.alt.value, Key.alt_l.value, Key.alt_r.value)),
(Key.cmd, (Key.cmd.value, Key.cmd_l.value, Key.cmd_r.value)),
(Key.ctrl, (Key.ctrl.value, Key.ctrl_l.value, Key.ctrl_r.value)),
(Key.shift, (Key.shift.value, Key.shift_l.value, Key.shift_r.value)))
#: Normalised modifiers as a mapping from virtual key code to basic modifier.
_NORMAL_MODIFIERS = {
value: key
for combination in _MODIFIER_KEYS
for key, value in zip(
itertools.cycle((combination[0],)),
combination[1])}
#: Control codes to transform into key codes when typing
_CONTROL_CODES = {
'\n': Key.enter,
'\r': Key.enter,
'\t': Key.tab}
# pylint: enable=C0326
class Events(Events):
"""A keyboard event listener supporting synchronous iteration over the
events.
Possible events are:
:class:`Events.Press`
A key was pressed.
:class:`Events.Release`
A key was released.
"""
_Listener = Listener
class Press(Events.Event):
"""A key press event.
"""
def __init__(self, key, injected):
#: The key.
self.key = key
#: Whether this event is synthetic.
self.injected = injected
class Release(Events.Event):
"""A key release event.
"""
def __init__(self, key, injected):
#: The key.
self.key = key
#: Whether this event is synthetic.
self.injected = injected
def __init__(self):
super(Events, self).__init__(
on_press=self.Press,
on_release=self.Release)
class HotKey(object):
"""A combination of keys acting as a hotkey.
This class acts as a container of hotkey state for a keyboard listener.
:param set keys: The collection of keys that must be pressed for this
hotkey to activate. Please note that a common limitation of the
hardware is that at most three simultaneously pressed keys are
supported, so using more keys may not work.
:param callable on_activate: The activation callback.
"""
def __init__(self, keys, on_activate):
self._state = set()
self._keys = set(keys)
self._on_activate = on_activate
@staticmethod
def parse(keys):
"""Parses a key combination string.
Key combination strings are sequences of key identifiers separated by
``'+'``. Key identifiers are either single characters representing a
keyboard key, such as ``'a'``, or special key names identified by names
enclosed by brackets, such as ``'<ctrl>'``.
Keyboard keys are case-insensitive.
:raises ValueError: if a part of the keys string is invalid, or if it
contains multiple equal parts
"""
def parts():
start = 0
for i, c in enumerate(keys):
if c == '+' and i != start:
yield keys[start:i]
start = i + 1
if start == len(keys):
raise ValueError(keys)
else:
yield keys[start:]
def parse(s):
if len(s) == 1:
return KeyCode.from_char(s.lower())
elif len(s) > 2 and (s[0], s[-1]) == ('<', '>'):
p = s[1:-1]
try:
# We want to represent modifiers as Key instances, and all
# other keys as KeyCodes
key = Key[p.lower()]
if key in _NORMAL_MODIFIERS.values():
return key
else:
return KeyCode.from_vk(key.value.vk)
except KeyError:
try:
return KeyCode.from_vk(int(p))
except ValueError:
raise ValueError(s)
else:
raise ValueError(s)
# Split the string and parse the individual parts
raw_parts = list(parts())
parsed_parts = [
parse(s)
for s in raw_parts]
# Ensure no duplicate parts
if len(parsed_parts) != len(set(parsed_parts)):
raise ValueError(keys)
else:
return parsed_parts
def press(self, key):
"""Updates the hotkey state for a pressed key.
If the key is not currently pressed, but is the last key for the full
combination, the activation callback will be invoked.
Please note that the callback will only be invoked once.
:param key: The key being pressed.
:type key: Key or KeyCode
"""
if key in self._keys and key not in self._state:
self._state.add(key)
if self._state == self._keys:
self._on_activate()
def release(self, key):
"""Updates the hotkey state for a released key.
:param key: The key being released.
:type key: Key or KeyCode
"""
if key in self._state:
self._state.remove(key)
class GlobalHotKeys(Listener):
"""A keyboard listener supporting a number of global hotkeys.
This is a convenience wrapper to simplify registering a number of global
hotkeys.
:param dict hotkeys: A mapping from hotkey description to hotkey action.
Keys are strings passed to :meth:`HotKey.parse`.
:raises ValueError: if any hotkey description is invalid
"""
def __init__(self, hotkeys, *args, **kwargs):
self._hotkeys = [
HotKey(HotKey.parse(key), value)
for key, value in hotkeys.items()]
super(GlobalHotKeys, self).__init__(
on_press=self._on_press,
on_release=self._on_release,
*args,
**kwargs)
def _on_press(self, key, injected):
"""The press callback.
This is automatically registered upon creation.
:param key: The key provided by the base class.
:param injected: Whether the event was injected.
"""
if not injected:
for hotkey in self._hotkeys:
hotkey.press(self.canonical(key))
def _on_release(self, key, injected):
"""The release callback.
This is automatically registered upon creation.
:param key: The key provided by the base class.
:param injected: Whether the event was injected.
"""
if not injected:
for hotkey in self._hotkeys:
hotkey.release(self.canonical(key))

View File

@@ -0,0 +1,754 @@
# coding=utf-8
# pynput
# Copyright (C) 2015-2024 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains the base implementation.
The actual interface to keyboard classes is defined here, but the
implementation is located in a platform dependent module.
"""
# pylint: disable=R0903
# We implement stubs
import contextlib
import enum
import threading
import unicodedata
import six
from pynput._util import AbstractListener, prefix
from pynput import _logger
class KeyCode(object):
"""
A :class:`KeyCode` represents the description of a key code used by the
operating system.
"""
#: The names of attributes used as platform extensions.
_PLATFORM_EXTENSIONS = []
def __init__(self, vk=None, char=None, is_dead=False, **kwargs):
self.vk = vk
self.char = six.text_type(char) if char is not None else None
self.is_dead = is_dead
if self.is_dead:
try:
self.combining = unicodedata.lookup(
'COMBINING ' + unicodedata.name(self.char))
except KeyError:
self.is_dead = False
self.combining = None
if self.is_dead and not self.combining:
raise KeyError(char)
else:
self.combining = None
for key in self._PLATFORM_EXTENSIONS:
setattr(self, key, kwargs.pop(key, None))
if kwargs:
raise ValueError(kwargs)
def __repr__(self):
if self.is_dead:
return '[%s]' % repr(self.char)
if self.char is not None:
return repr(self.char)
else:
return '<%d>' % self.vk
def __str__(self):
return repr(self)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
if self.char is not None and other.char is not None:
return self.char == other.char and self.is_dead == other.is_dead
else:
return self.vk == other.vk and all(
getattr(self, f) == getattr(other, f)
for f in self._PLATFORM_EXTENSIONS)
def __hash__(self):
return hash(repr(self))
def join(self, key):
"""Applies this dead key to another key and returns the result.
Joining a dead key with space (``' '``) or itself yields the non-dead
version of this key, if one exists; for example,
``KeyCode.from_dead('~').join(KeyCode.from_char(' '))`` equals
``KeyCode.from_char('~')`` and
``KeyCode.from_dead('~').join(KeyCode.from_dead('~'))``.
:param KeyCode key: The key to join with this key.
:return: a key code
:raises ValueError: if the keys cannot be joined
"""
# A non-dead key cannot be joined
if not self.is_dead:
raise ValueError(self)
# Joining two of the same keycodes, or joining with space, yields the
# non-dead version of the key
if key.char == ' ' or self == key:
return self.from_char(self.char)
# Otherwise we combine the characters
if key.char is not None:
combined = unicodedata.normalize(
'NFC',
key.char + self.combining)
if combined:
return self.from_char(combined)
raise ValueError(key)
@classmethod
def from_vk(cls, vk, **kwargs):
"""Creates a key from a virtual key code.
:param vk: The virtual key code.
:param kwargs: Any other parameters to pass.
:return: a key code
"""
return cls(vk=vk, **kwargs)
@classmethod
def from_char(cls, char, **kwargs):
"""Creates a key from a character.
:param str char: The character.
:return: a key code
"""
return cls(char=char, **kwargs)
@classmethod
def from_dead(cls, char, **kwargs):
"""Creates a dead key.
:param char: The dead key. This should be the unicode character
representing the stand alone character, such as ``'~'`` for
*COMBINING TILDE*.
:return: a key code
"""
return cls(char=char, is_dead=True, **kwargs)
class Key(enum.Enum):
"""A class representing various buttons that may not correspond to
letters. This includes modifier keys and function keys.
The actual values for these items differ between platforms. Some platforms
may have additional buttons, but these are guaranteed to be present
everywhere.
"""
#: A generic Alt key. This is a modifier.
alt = KeyCode.from_vk(0)
#: The left Alt key. This is a modifier.
alt_l = KeyCode.from_vk(0)
#: The right Alt key. This is a modifier.
alt_r = KeyCode.from_vk(0)
#: The AltGr key. This is a modifier.
alt_gr = KeyCode.from_vk(0)
#: The Backspace key.
backspace = KeyCode.from_vk(0)
#: The CapsLock key.
caps_lock = KeyCode.from_vk(0)
#: A generic command button. On *PC* platforms, this corresponds to the
#: Super key or Windows key, and on *Mac* it corresponds to the Command
#: key. This may be a modifier.
cmd = KeyCode.from_vk(0)
#: The left command button. On *PC* platforms, this corresponds to the
#: Super key or Windows key, and on *Mac* it corresponds to the Command
#: key. This may be a modifier.
cmd_l = KeyCode.from_vk(0)
#: The right command button. On *PC* platforms, this corresponds to the
#: Super key or Windows key, and on *Mac* it corresponds to the Command
#: key. This may be a modifier.
cmd_r = KeyCode.from_vk(0)
#: A generic Ctrl key. This is a modifier.
ctrl = KeyCode.from_vk(0)
#: The left Ctrl key. This is a modifier.
ctrl_l = KeyCode.from_vk(0)
#: The right Ctrl key. This is a modifier.
ctrl_r = KeyCode.from_vk(0)
#: The Delete key.
delete = KeyCode.from_vk(0)
#: A down arrow key.
down = KeyCode.from_vk(0)
#: The End key.
end = KeyCode.from_vk(0)
#: The Enter or Return key.
enter = KeyCode.from_vk(0)
#: The Esc key.
esc = KeyCode.from_vk(0)
#: The function keys. F1 to F20 are defined.
f1 = KeyCode.from_vk(0)
f2 = KeyCode.from_vk(0)
f3 = KeyCode.from_vk(0)
f4 = KeyCode.from_vk(0)
f5 = KeyCode.from_vk(0)
f6 = KeyCode.from_vk(0)
f7 = KeyCode.from_vk(0)
f8 = KeyCode.from_vk(0)
f9 = KeyCode.from_vk(0)
f10 = KeyCode.from_vk(0)
f11 = KeyCode.from_vk(0)
f12 = KeyCode.from_vk(0)
f13 = KeyCode.from_vk(0)
f14 = KeyCode.from_vk(0)
f15 = KeyCode.from_vk(0)
f16 = KeyCode.from_vk(0)
f17 = KeyCode.from_vk(0)
f18 = KeyCode.from_vk(0)
f19 = KeyCode.from_vk(0)
f20 = KeyCode.from_vk(0)
#: The Home key.
home = KeyCode.from_vk(0)
#: A left arrow key.
left = KeyCode.from_vk(0)
#: The PageDown key.
page_down = KeyCode.from_vk(0)
#: The PageUp key.
page_up = KeyCode.from_vk(0)
#: A right arrow key.
right = KeyCode.from_vk(0)
#: A generic Shift key. This is a modifier.
shift = KeyCode.from_vk(0)
#: The left Shift key. This is a modifier.
shift_l = KeyCode.from_vk(0)
#: The right Shift key. This is a modifier.
shift_r = KeyCode.from_vk(0)
#: The Space key.
space = KeyCode.from_vk(0)
#: The Tab key.
tab = KeyCode.from_vk(0)
#: An up arrow key.
up = KeyCode.from_vk(0)
#: The play/pause toggle.
media_play_pause = KeyCode.from_vk(0)
#: The volume mute button.
media_volume_mute = KeyCode.from_vk(0)
#: The volume down button.
media_volume_down = KeyCode.from_vk(0)
#: The volume up button.
media_volume_up = KeyCode.from_vk(0)
#: The previous track button.
media_previous = KeyCode.from_vk(0)
#: The next track button.
media_next = KeyCode.from_vk(0)
#: The Insert key. This may be undefined for some platforms.
insert = KeyCode.from_vk(0)
#: The Menu key. This may be undefined for some platforms.
menu = KeyCode.from_vk(0)
#: The NumLock key. This may be undefined for some platforms.
num_lock = KeyCode.from_vk(0)
#: The Pause/Break key. This may be undefined for some platforms.
pause = KeyCode.from_vk(0)
#: The PrintScreen key. This may be undefined for some platforms.
print_screen = KeyCode.from_vk(0)
#: The ScrollLock key. This may be undefined for some platforms.
scroll_lock = KeyCode.from_vk(0)
class Controller(object):
"""A controller for sending virtual keyboard events to the system.
"""
#: The virtual key codes
_KeyCode = KeyCode
#: The various keys.
_Key = Key
class InvalidKeyException(Exception):
"""The exception raised when an invalid ``key`` parameter is passed to
either :meth:`Controller.press` or :meth:`Controller.release`.
Its first argument is the ``key`` parameter.
"""
pass
class InvalidCharacterException(Exception):
"""The exception raised when an invalid character is encountered in
the string passed to :meth:`Controller.type`.
Its first argument is the index of the character in the string, and the
second the character.
"""
pass
def __init__(self):
self._log = _logger(self.__class__)
self._modifiers_lock = threading.RLock()
self._modifiers = set()
self._caps_lock = False
self._dead_key = None
def press(self, key):
"""Presses a key.
A key may be either a string of length 1, one of the :class:`Key`
members or a :class:`KeyCode`.
Strings will be transformed to :class:`KeyCode` using
:meth:`KeyCode.char`. Members of :class:`Key` will be translated to
their :meth:`~Key.value`.
:param key: The key to press.
:raises InvalidKeyException: if the key is invalid
:raises ValueError: if ``key`` is a string, but its length is not ``1``
"""
resolved = self._resolve(key)
if resolved is None:
raise self.InvalidKeyException(key)
self._update_modifiers(resolved, True)
# Update caps lock state
if resolved == self._Key.caps_lock.value:
self._caps_lock = not self._caps_lock
# If we currently have a dead key pressed, join it with this key
original = resolved
if self._dead_key:
try:
resolved = self._dead_key.join(resolved)
except ValueError:
self._handle(self._dead_key, True)
self._handle(self._dead_key, False)
# If the key is a dead key, keep it for later
if resolved.is_dead:
self._dead_key = resolved
return
try:
self._handle(resolved, True)
except self.InvalidKeyException:
if resolved != original:
self._handle(self._dead_key, True)
self._handle(self._dead_key, False)
self._handle(original, True)
self._dead_key = None
def release(self, key):
"""Releases a key.
A key may be either a string of length 1, one of the :class:`Key`
members or a :class:`KeyCode`.
Strings will be transformed to :class:`KeyCode` using
:meth:`KeyCode.char`. Members of :class:`Key` will be translated to
their :meth:`~Key.value`.
:param key: The key to release. If this is a string, it is passed to
:meth:`touches` and the returned releases are used.
:raises InvalidKeyException: if the key is invalid
:raises ValueError: if ``key`` is a string, but its length is not ``1``
"""
resolved = self._resolve(key)
if resolved is None:
raise self.InvalidKeyException(key)
self._update_modifiers(resolved, False)
# Ignore released dead keys
if resolved.is_dead:
return
self._handle(resolved, False)
def tap(self, key):
"""Presses and releases a key.
This is equivalent to the following code::
controller.press(key)
controller.release(key)
:param key: The key to press.
:raises InvalidKeyException: if the key is invalid
:raises ValueError: if ``key`` is a string, but its length is not ``1``
"""
self.press(key)
self.release(key)
def touch(self, key, is_press):
"""Calls either :meth:`press` or :meth:`release` depending on the value
of ``is_press``.
:param key: The key to press or release.
:param bool is_press: Whether to press the key.
:raises InvalidKeyException: if the key is invalid
"""
if is_press:
self.press(key)
else:
self.release(key)
@contextlib.contextmanager
def pressed(self, *args):
"""Executes a block with some keys pressed.
:param keys: The keys to keep pressed.
"""
for key in args:
self.press(key)
try:
yield
finally:
for key in reversed(args):
self.release(key)
def type(self, string):
"""Types a string.
This method will send all key presses and releases necessary to type
all characters in the string.
:param str string: The string to type.
:raises InvalidCharacterException: if an untypable character is
encountered
"""
from . import _CONTROL_CODES
for i, character in enumerate(string):
key = _CONTROL_CODES.get(character, character)
try:
self.press(key)
self.release(key)
except (ValueError, self.InvalidKeyException):
raise self.InvalidCharacterException(i, character)
@property
@contextlib.contextmanager
def modifiers(self):
"""The currently pressed modifier keys.
Please note that this reflects only the internal state of this
controller, and not the state of the operating system keyboard buffer.
This property cannot be used to determine whether a key is physically
pressed.
Only the generic modifiers will be set; when pressing either
:attr:`Key.shift_l`, :attr:`Key.shift_r` or :attr:`Key.shift`, only
:attr:`Key.shift` will be present.
Use this property within a context block thus::
with controller.modifiers as modifiers:
with_block()
This ensures that the modifiers cannot be modified by another thread.
"""
with self._modifiers_lock:
yield set(
self._as_modifier(modifier)
for modifier in self._modifiers)
@property
def alt_pressed(self):
"""Whether any *alt* key is pressed.
Please note that this reflects only the internal state of this
controller. See :attr:`modifiers` for more information.
"""
with self.modifiers as modifiers:
return self._Key.alt in modifiers
@property
def alt_gr_pressed(self):
"""Whether *altgr* is pressed.
Please note that this reflects only the internal state of this
controller. See :attr:`modifiers` for more information.
"""
with self.modifiers as modifiers:
return self._Key.alt_gr in modifiers
@property
def ctrl_pressed(self):
"""Whether any *ctrl* key is pressed.
Please note that this reflects only the internal state of this
controller. See :attr:`modifiers` for more information.
"""
with self.modifiers as modifiers:
return self._Key.ctrl in modifiers
@property
def shift_pressed(self):
"""Whether any *shift* key is pressed, or *caps lock* is toggled.
Please note that this reflects only the internal state of this
controller. See :attr:`modifiers` for more information.
"""
if self._caps_lock:
return True
with self.modifiers as modifiers:
return self._Key.shift in modifiers
def _resolve(self, key):
"""Resolves a key to a :class:`KeyCode` instance.
This method will convert any key representing a character to uppercase
if a shift modifier is active.
:param key: The key to resolve.
:return: a key code, or ``None`` if it cannot be resolved
"""
# Use the value for the key constants
if key in (k for k in self._Key):
return key.value
# Convert strings to key codes
if isinstance(key, six.string_types):
if len(key) != 1:
raise ValueError(key)
return self._KeyCode.from_char(key)
# Assume this is a proper key
if isinstance(key, self._KeyCode):
if key.char is not None and self.shift_pressed:
return self._KeyCode(vk=key.vk, char=key.char.upper())
else:
return key
def _update_modifiers(self, key, is_press):
"""Updates the current modifier list.
If ``key`` is not a modifier, no action is taken.
:param key: The key being pressed or released.
"""
# Check whether the key is a modifier
if self._as_modifier(key):
with self._modifiers_lock:
if is_press:
self._modifiers.add(key)
else:
try:
self._modifiers.remove(key)
except KeyError:
pass
def _as_modifier(self, key):
"""Returns a key as the modifier used internally if defined.
This method will convert values like :attr:`Key.alt_r.value` and
:attr:`Key.shift_l.value` to :attr:`Key.alt` and :attr:`Key.shift`.
:param key: The possible modifier key.
:return: the base modifier key, or ``None`` if ``key`` is not a
modifier
"""
from . import _NORMAL_MODIFIERS
return _NORMAL_MODIFIERS.get(key, None)
def _handle(self, key, is_press):
"""The platform implementation of the actual emitting of keyboard
events.
This is a platform dependent implementation.
:param Key key: The key to handle.
:param bool is_press: Whether this is a key press event.
"""
raise NotImplementedError()
# pylint: disable=W0223; This is also an abstract class
class Listener(AbstractListener):
"""A listener for keyboard events.
Instances of this class can be used as context managers. This is equivalent
to the following code::
listener.start()
try:
listener.wait()
with_statements()
finally:
listener.stop()
This class inherits from :class:`threading.Thread` and supports all its
methods. It will set :attr:`daemon` to ``True`` when created.
All callback arguments are optional; a callback may take less arguments
than actually passed, but not more, unless they are optional.
:param callable on_press: The callback to call when a button is pressed.
It will be called with the arguments ``(key, injected)``, where ``key``
is a :class:`KeyCode`, a :class:`Key` or ``None`` if the key is
unknown, and ``injected`` whether the event was injected and thus not
generated by an actual input device.
Please note that not all backends support ``injected`` and will always
set it to ``False``.
:param callable on_release: The callback to call when a button is released.
It will be called with the arguments ``(key, injected)``, where ``key``
is a :class:`KeyCode`, a :class:`Key` or ``None`` if the key is
unknown, and ``injected`` whether the event was injected and thus not
generated by an actual input device.
Please note that not all backends support ``injected`` and will always
set it to ``False``.
:param bool suppress: Whether to suppress events. Setting this to ``True``
will prevent the input events from being passed to the rest of the
system.
:param kwargs: Any non-standard platform dependent options. These should be
prefixed with the platform name thus: ``darwin_``, ``uinput_``,
``xorg_`` or ``win32_``.
Supported values are:
``darwin_intercept``
A callable taking the arguments ``(event_type, event)``, where
``event_type`` is ``Quartz.kCGEventKeyDown`` or
``Quartz.kCGEventKeyUp``, and ``event`` is a ``CGEventRef``.
This callable can freely modify the event using functions like
``Quartz.CGEventSetIntegerValueField``. If this callable does not
return the event, the event is suppressed system wide.
``uinput_device_paths``
A list of device paths.
If this is specified, *pynput* will limit the number of devices
checked for the capabilities needed to those passed, otherwise all
system devices will be used. Passing this might be required if an
incorrect device is chosen.
``win32_event_filter``
A callable taking the arguments ``(msg, data)``, where ``msg`` is
the current message, and ``data`` associated data as a
`KBDLLHOOKSTRUCT <https://docs.microsoft.com/en-gb/windows/win32/api/winuser/ns-winuser-kbdllhookstruct>`_.
If this callback returns ``False``, the event will not be
propagated to the listener callback.
If ``self.suppress_event()`` is called, the event is suppressed
system wide.
"""
def __init__(self, on_press=None, on_release=None, suppress=False,
**kwargs):
self._log = _logger(self.__class__)
option_prefix = prefix(Listener, self.__class__)
self._options = {
key[len(option_prefix):]: value
for key, value in kwargs.items()
if key.startswith(option_prefix)}
super(Listener, self).__init__(
on_press=self._wrap(on_press, 2),
on_release=self._wrap(on_release, 2),
suppress=suppress)
# pylint: enable=W0223
def canonical(self, key):
"""Performs normalisation of a key.
This method attempts to convert key events to their canonical form, so
that events will equal regardless of modifier state.
This method will convert upper case keys to lower case keys, convert
any modifiers with a right and left version to the same value, and may
slow perform additional platform dependent normalisation.
:param key: The key to normalise.
:type key: Key or KeyCode
:return: a key
:rtype: Key or KeyCode
"""
from pynput.keyboard import Key, KeyCode, _NORMAL_MODIFIERS
if isinstance(key, KeyCode) and key.char is not None:
return KeyCode.from_char(key.char.lower())
elif isinstance(key, Key) and key.value in _NORMAL_MODIFIERS:
return _NORMAL_MODIFIERS[key.value]
elif isinstance(key, Key) and key.value.vk is not None:
return KeyCode.from_vk(key.value.vk)
else:
return key

View File

@@ -0,0 +1,367 @@
# coding=utf-8
# pynput
# Copyright (C) 2015-2024 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
The keyboard implementation for *macOS*.
"""
# pylint: disable=C0111
# The documentation is extracted from the base classes
# pylint: disable=R0903
# We implement stubs
import enum
from Quartz import (
CGEventCreateKeyboardEvent,
CGEventGetFlags,
CGEventGetIntegerValueField,
CGEventGetType,
CGEventKeyboardGetUnicodeString,
CGEventKeyboardSetUnicodeString,
CGEventMaskBit,
CGEventPost,
CGEventSetFlags,
kCGEventFlagMaskAlternate,
kCGEventFlagMaskCommand,
kCGEventFlagMaskControl,
kCGEventFlagMaskShift,
kCGEventFlagsChanged,
kCGEventKeyDown,
kCGEventKeyUp,
kCGHIDEventTap,
kCGKeyboardEventKeycode,
NSEvent,
NSSystemDefined)
from pynput._util.darwin import (
get_unicode_to_keycode_map,
keycode_context,
ListenerMixin)
from pynput._util.darwin_vks import SYMBOLS
from . import _base
# From hidsystem/ev_keymap.h
NX_KEYTYPE_PLAY = 16
NX_KEYTYPE_MUTE = 7
NX_KEYTYPE_SOUND_DOWN = 1
NX_KEYTYPE_SOUND_UP = 0
NX_KEYTYPE_NEXT = 17
NX_KEYTYPE_PREVIOUS = 18
NX_KEYTYPE_EJECT = 14
# pylint: disable=C0103; We want to use the names from the C API
# This is undocumented, but still widely known
kSystemDefinedEventMediaKeysSubtype = 8
# We extract this here since the name is very long
otherEventWithType = getattr(
NSEvent,
'otherEventWithType_'
'location_'
'modifierFlags_'
'timestamp_'
'windowNumber_'
'context_'
'subtype_'
'data1_'
'data2_')
# pylint: enable=C0103
class KeyCode(_base.KeyCode):
_PLATFORM_EXTENSIONS = (
# Whether this is a media key
'_is_media',
)
# Be explicit about fields
_is_media = None
@classmethod
def _from_media(cls, vk, **kwargs):
"""Creates a media key from a key code.
:param int vk: The key code.
:return: a key code
"""
return cls.from_vk(vk, _is_media=True, **kwargs)
def _event(self, modifiers, mapping, is_pressed):
"""This key as a *Quartz* event.
:param set modifiers: The currently active modifiers.
:param mapping: The current keyboard mapping.
:param bool is_press: Whether to generate a press event.
:return: a *Quartz* event
"""
vk = self.vk or mapping.get(self.char)
if self._is_media:
result = otherEventWithType(
NSSystemDefined,
(0, 0),
0xa00 if is_pressed else 0xb00,
0,
0,
0,
8,
(self.vk << 16) | ((0xa if is_pressed else 0xb) << 8),
-1).CGEvent()
else:
result = CGEventCreateKeyboardEvent(
None, 0 if vk is None else vk, is_pressed)
CGEventSetFlags(
result,
0
| (kCGEventFlagMaskAlternate
if Key.alt in modifiers else 0)
| (kCGEventFlagMaskCommand
if Key.cmd in modifiers else 0)
| (kCGEventFlagMaskControl
if Key.ctrl in modifiers else 0)
| (kCGEventFlagMaskShift
if Key.shift in modifiers else 0))
if vk is None and self.char is not None:
CGEventKeyboardSetUnicodeString(
result, len(self.char), self.char)
return result
# pylint: disable=W0212
class Key(enum.Enum):
# Default keys
alt = KeyCode.from_vk(0x3A)
alt_l = KeyCode.from_vk(0x3A)
alt_r = KeyCode.from_vk(0x3D)
alt_gr = KeyCode.from_vk(0x3D)
backspace = KeyCode.from_vk(0x33)
caps_lock = KeyCode.from_vk(0x39)
cmd = KeyCode.from_vk(0x37)
cmd_l = KeyCode.from_vk(0x37)
cmd_r = KeyCode.from_vk(0x36)
ctrl = KeyCode.from_vk(0x3B)
ctrl_l = KeyCode.from_vk(0x3B)
ctrl_r = KeyCode.from_vk(0x3E)
delete = KeyCode.from_vk(0x75)
down = KeyCode.from_vk(0x7D)
end = KeyCode.from_vk(0x77)
enter = KeyCode.from_vk(0x24)
esc = KeyCode.from_vk(0x35)
f1 = KeyCode.from_vk(0x7A)
f2 = KeyCode.from_vk(0x78)
f3 = KeyCode.from_vk(0x63)
f4 = KeyCode.from_vk(0x76)
f5 = KeyCode.from_vk(0x60)
f6 = KeyCode.from_vk(0x61)
f7 = KeyCode.from_vk(0x62)
f8 = KeyCode.from_vk(0x64)
f9 = KeyCode.from_vk(0x65)
f10 = KeyCode.from_vk(0x6D)
f11 = KeyCode.from_vk(0x67)
f12 = KeyCode.from_vk(0x6F)
f13 = KeyCode.from_vk(0x69)
f14 = KeyCode.from_vk(0x6B)
f15 = KeyCode.from_vk(0x71)
f16 = KeyCode.from_vk(0x6A)
f17 = KeyCode.from_vk(0x40)
f18 = KeyCode.from_vk(0x4F)
f19 = KeyCode.from_vk(0x50)
f20 = KeyCode.from_vk(0x5A)
home = KeyCode.from_vk(0x73)
left = KeyCode.from_vk(0x7B)
page_down = KeyCode.from_vk(0x79)
page_up = KeyCode.from_vk(0x74)
right = KeyCode.from_vk(0x7C)
shift = KeyCode.from_vk(0x38)
shift_l = KeyCode.from_vk(0x38)
shift_r = KeyCode.from_vk(0x3C)
space = KeyCode.from_vk(0x31, char=' ')
tab = KeyCode.from_vk(0x30)
up = KeyCode.from_vk(0x7E)
media_play_pause = KeyCode._from_media(NX_KEYTYPE_PLAY)
media_volume_mute = KeyCode._from_media(NX_KEYTYPE_MUTE)
media_volume_down = KeyCode._from_media(NX_KEYTYPE_SOUND_DOWN)
media_volume_up = KeyCode._from_media(NX_KEYTYPE_SOUND_UP)
media_previous = KeyCode._from_media(NX_KEYTYPE_PREVIOUS)
media_next = KeyCode._from_media(NX_KEYTYPE_NEXT)
media_eject = KeyCode._from_media(NX_KEYTYPE_EJECT)
# pylint: enable=W0212
class Controller(_base.Controller):
_KeyCode = KeyCode
_Key = Key
def __init__(self):
super(Controller, self).__init__()
self._mapping = get_unicode_to_keycode_map()
def _handle(self, key, is_press):
with self.modifiers as modifiers:
CGEventPost(
kCGHIDEventTap,
(key if key not in (k for k in Key) else key.value)._event(
modifiers, self._mapping, is_press))
class Listener(ListenerMixin, _base.Listener):
#: The events that we listen to
_EVENTS = (
CGEventMaskBit(kCGEventKeyDown) |
CGEventMaskBit(kCGEventKeyUp) |
CGEventMaskBit(kCGEventFlagsChanged) |
CGEventMaskBit(NSSystemDefined)
)
# pylint: disable=W0212
#: A mapping from keysym to special key
_SPECIAL_KEYS = {
(key.value.vk, key.value._is_media): key
for key in Key}
# pylint: enable=W0212
#: The event flags set for the various modifier keys
_MODIFIER_FLAGS = {
Key.alt: kCGEventFlagMaskAlternate,
Key.alt_l: kCGEventFlagMaskAlternate,
Key.alt_r: kCGEventFlagMaskAlternate,
Key.cmd: kCGEventFlagMaskCommand,
Key.cmd_l: kCGEventFlagMaskCommand,
Key.cmd_r: kCGEventFlagMaskCommand,
Key.ctrl: kCGEventFlagMaskControl,
Key.ctrl_l: kCGEventFlagMaskControl,
Key.ctrl_r: kCGEventFlagMaskControl,
Key.shift: kCGEventFlagMaskShift,
Key.shift_l: kCGEventFlagMaskShift,
Key.shift_r: kCGEventFlagMaskShift}
def __init__(self, *args, **kwargs):
super(Listener, self).__init__(*args, **kwargs)
self._flags = 0
self._context = None
self._intercept = self._options.get(
'intercept',
None)
def _run(self):
with keycode_context() as context:
self._context = context
try:
super(Listener, self)._run()
finally:
self._context = None
def _handle_message(self, _proxy, event_type, event, _refcon, injected):
# Convert the event to a KeyCode; this may fail, and in that case we
# pass None
try:
key = self._event_to_key(event)
except IndexError:
key = None
try:
if event_type == kCGEventKeyDown:
# This is a normal key press
self.on_press(key, injected)
elif event_type == kCGEventKeyUp:
# This is a normal key release
self.on_release(key, injected)
elif key == Key.caps_lock:
# We only get an event when caps lock is toggled, so we fake
# press and release
self.on_press(key, injected)
self.on_release(key, injected)
elif event_type == NSSystemDefined:
sys_event = NSEvent.eventWithCGEvent_(event)
if sys_event.subtype() == kSystemDefinedEventMediaKeysSubtype:
# The key in the special key dict; True since it is a media
# key
key = ((sys_event.data1() & 0xffff0000) >> 16, True)
if key in self._SPECIAL_KEYS:
flags = sys_event.data1() & 0x0000ffff
is_press = ((flags & 0xff00) >> 8) == 0x0a
if is_press:
self.on_press(self._SPECIAL_KEYS[key])
else:
self.on_release(self._SPECIAL_KEYS[key])
else:
# This is a modifier event---excluding caps lock---for which we
# must check the current modifier state to determine whether
# the key was pressed or released
flags = CGEventGetFlags(event)
is_press = flags & self._MODIFIER_FLAGS.get(key, 0)
if is_press:
self.on_press(key, injected)
else:
self.on_release(key, injected)
finally:
# Store the current flag mask to be able to detect modifier state
# changes
self._flags = CGEventGetFlags(event)
def _event_to_key(self, event):
"""Converts a *Quartz* event to a :class:`KeyCode`.
:param event: The event to convert.
:return: a :class:`pynput.keyboard.KeyCode`
:raises IndexError: if the key code is invalid
"""
vk = CGEventGetIntegerValueField(
event, kCGKeyboardEventKeycode)
event_type = CGEventGetType(event)
is_media = True if event_type == NSSystemDefined else None
# First try special keys...
key = (vk, is_media)
if key in self._SPECIAL_KEYS:
return self._SPECIAL_KEYS[key]
# ...then try characters...
length, chars = CGEventKeyboardGetUnicodeString(
event, 100, None, None)
try:
printable = chars.isprintable()
except AttributeError:
printable = chars.isalnum()
if not printable and vk in SYMBOLS \
and CGEventGetFlags(event) \
& kCGEventFlagMaskControl:
return KeyCode.from_char(SYMBOLS[vk], vk=vk)
elif length > 0:
return KeyCode.from_char(chars, vk=vk)
# ...and fall back on a virtual key code
return KeyCode.from_vk(vk)

View File

@@ -0,0 +1,23 @@
# coding=utf-8
# pynput
# Copyright (C) 2015-2024 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module contains a dummy implementation.
It cannot be used, but importing it will not raise any exceptions.
"""
from ._base import Controller, Key, KeyCode, Listener

View File

@@ -0,0 +1,446 @@
# coding=utf-8
# pynput
# Copyright (C) 2015-2024 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
The keyboard implementation for *uinput*.
"""
# pylint: disable=C0111
# The documentation is extracted from the base classes
# pylint: disable=R0903
# We implement stubs
import enum
import errno
import functools
import os
import re
import subprocess
import evdev
from evdev.events import KeyEvent
from pynput._util import xorg_keysyms
from pynput._util.uinput import ListenerMixin
from . import _base
class KeyCode(_base.KeyCode):
_PLATFORM_EXTENSIONS = (
# The name for this key
'_x_name',
'_kernel_name',
)
# Be explicit about fields
_x_name = None
_kernel_name = None
# pylint: enable=W0212
@classmethod
def _from_name(cls, x_name, kernel_name, **kwargs):
"""Creates a key from a name.
:param str x_name: The X name.
:param str kernel_name: The kernel name.
:return: a key code
"""
try:
vk = getattr(evdev.ecodes, kernel_name)
except AttributeError:
vk = None
return cls.from_vk(
vk, _x_name=x_name, _kernel_name=kernel_name, **kwargs)
# pylint: disable=W0212
class Key(enum.Enum):
alt = KeyCode._from_name('Alt_L', 'KEY_LEFTALT')
alt_l = KeyCode._from_name('Alt_L', 'KEY_LEFTALT')
alt_r = KeyCode._from_name('Alt_R', 'KEY_RIGHTALT')
alt_gr = KeyCode._from_name('Mode_switch', 'KEY_RIGHTALT')
backspace = KeyCode._from_name('BackSpace', 'KEY_BACKSPACE')
caps_lock = KeyCode._from_name('Caps_Lock', 'KEY_CAPSLOCK')
cmd = KeyCode._from_name('Super_L', 'KEY_LEFTMETA')
cmd_l = KeyCode._from_name('Super_L', 'KEY_LEFTMETA')
cmd_r = KeyCode._from_name('Super_R', 'KEY_RIGHTMETA')
ctrl = KeyCode._from_name('Control_L', 'KEY_LEFTCTRL')
ctrl_l = KeyCode._from_name('Control_L', 'KEY_LEFTCTRL')
ctrl_r = KeyCode._from_name('Control_R', 'KEY_RIGHTCTRL')
delete = KeyCode._from_name('Delete', 'KEY_DELETE')
down = KeyCode._from_name('Down', 'KEY_DOWN')
end = KeyCode._from_name('End', 'KEY_END')
enter = KeyCode._from_name('Return', 'KEY_ENTER')
esc = KeyCode._from_name('Escape', 'KEY_ESC')
f1 = KeyCode._from_name('F1', 'KEY_F1')
f2 = KeyCode._from_name('F2', 'KEY_F2')
f3 = KeyCode._from_name('F3', 'KEY_F3')
f4 = KeyCode._from_name('F4', 'KEY_F4')
f5 = KeyCode._from_name('F5', 'KEY_F5')
f6 = KeyCode._from_name('F6', 'KEY_F6')
f7 = KeyCode._from_name('F7', 'KEY_F7')
f8 = KeyCode._from_name('F8', 'KEY_F8')
f9 = KeyCode._from_name('F9', 'KEY_F9')
f10 = KeyCode._from_name('F10', 'KEY_F10')
f11 = KeyCode._from_name('F11', 'KEY_F11')
f12 = KeyCode._from_name('F12', 'KEY_F12')
f13 = KeyCode._from_name('F13', 'KEY_F13')
f14 = KeyCode._from_name('F14', 'KEY_F14')
f15 = KeyCode._from_name('F15', 'KEY_F15')
f16 = KeyCode._from_name('F16', 'KEY_F16')
f17 = KeyCode._from_name('F17', 'KEY_F17')
f18 = KeyCode._from_name('F18', 'KEY_F18')
f19 = KeyCode._from_name('F19', 'KEY_F19')
f20 = KeyCode._from_name('F20', 'KEY_F20')
home = KeyCode._from_name('Home', 'KEY_HOME')
left = KeyCode._from_name('Left', 'KEY_LEFT')
page_down = KeyCode._from_name('Page_Down', 'KEY_PAGEDOWN')
page_up = KeyCode._from_name('Page_Up', 'KEY_PAGEUP')
right = KeyCode._from_name('Right', 'KEY_RIGHT')
shift = KeyCode._from_name('Shift_L', 'KEY_LEFTSHIFT')
shift_l = KeyCode._from_name('Shift_L', 'KEY_LEFTSHIFT')
shift_r = KeyCode._from_name('Shift_R', 'KEY_RIGHTSHIFT')
space = KeyCode._from_name('space', 'KEY_SPACE', char=' ')
tab = KeyCode._from_name('Tab', 'KEY_TAB', char='\t')
up = KeyCode._from_name('Up', 'KEY_UP')
media_play_pause = KeyCode._from_name('Play', 'KEY_PLAYPAUSE')
media_volume_mute = KeyCode._from_name('Mute', 'KEY_MUTE')
media_volume_down = KeyCode._from_name('LowerVolume', 'KEY_VOLUMEDOWN')
media_volume_up = KeyCode._from_name('RaiseVolume', 'KEY_VOLUMEUP')
media_previous = KeyCode._from_name('Prev', 'KEY_PREVIOUSSONG')
media_next = KeyCode._from_name('Next', 'KEY_NEXTSONG')
insert = KeyCode._from_name('Insert', 'KEY_INSERT')
menu = KeyCode._from_name('Menu', 'KEY_MENU')
num_lock = KeyCode._from_name('Num_Lock', 'KEY_NUMLOCK')
pause = KeyCode._from_name('Pause', 'KEY_PAUSE')
print_screen = KeyCode._from_name('Print', 'KEY_SYSRQ')
scroll_lock = KeyCode._from_name('Scroll_Lock', 'KEY_SCROLLLOCK')
# pylint: enable=W0212
class Layout(object):
"""A description of the keyboard layout.
"""
#: A regular expression to parse keycodes in the dumpkeys output
#:
#: The groups are: keycode number, key names.
KEYCODE_RE = re.compile(
r'keycode\s+(\d+)\s+=(.*)')
class Key(object):
"""A key in a keyboard layout.
"""
def __init__(self, normal, shifted, alt, alt_shifted):
self._values = (
normal,
shifted,
alt,
alt_shifted)
def __str__(self):
return ('<'
'normal: {}, '
'shifted: {}, '
'alternative: {}, '
'shifted alternative: {}>').format(
self.normal, self.shifted, self.alt, self.alt_shifted)
__repr__ = __str__
def __iter__(self):
return iter(self._values)
def __getitem__(self, i):
return self._values[i]
@property
def normal(self):
"""The normal key.
"""
return self._values[0]
@property
def shifted(self):
"""The shifted key.
"""
return self._values[1]
@property
def alt(self):
"""The alternative key.
"""
return self._values[2]
@property
def alt_shifted(self):
"""The shifted alternative key.
"""
return self._values[3]
def __init__(self):
def as_char(k):
return k.value.char if isinstance(k, Key) else k.char
self._vk_table = self._load()
self._char_table = {
as_char(key): (
vk,
set()
| {Key.shift} if i & 1 else set()
| {Key.alt_gr} if i & 2 else set())
for vk, keys in self._vk_table.items()
for i, key in enumerate(keys)
if key is not None and as_char(key) is not None}
def for_vk(self, vk, modifiers):
"""Reads a key for a virtual key code and modifier state.
:param int vk: The virtual key code.
:param set modifiers: A set of modifiers.
:return: a mapped key
:raises KeyError: if ``vk`` is an unknown key
"""
return self._vk_table[vk][
0
| (1 if Key.shift in modifiers else 0)
| (2 if Key.alt_gr in modifiers else 0)]
def for_char(self, char):
"""Reads a virtual key code and modifier state for a character.
:param str char: The character.
:return: the tuple ``(vk, modifiers)``
:raises KeyError: if ``vk`` is an unknown key
"""
return self._char_table[char]
@functools.lru_cache()
def _load(self):
"""Loads the keyboard layout.
For simplicity, we call out to the ``dumpkeys`` binary. In the future,
we may want to implement this ourselves.
"""
result = {}
for keycode, names in self.KEYCODE_RE.findall(
subprocess.check_output(
['dumpkeys', '--full-table', '--keys-only']).decode('utf-8')):
vk = int(keycode)
keys = tuple(
self._parse(vk, name)
for name in names.split()[:4])
if any(key is not None for key in keys):
result[vk] = self.Key(*keys)
return result
def _parse(self, vk, name):
"""Parses a single key from the ``dumpkeys`` output.
:param int vk: The key code.
:param str name: The key name.
:return: a key representation
"""
try:
# First try special keys...
return next(
key
for key in Key
if key.value._x_name == name)
except StopIteration:
# ...then characters...
try:
_, char = xorg_keysyms.SYMBOLS[name.lstrip('+')]
if char:
return KeyCode.from_char(char, vk=vk)
except KeyError:
pass
# ...and finally special dumpkeys names
try:
return KeyCode.from_char({
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '5',
'six': '6',
'seven': '7',
'eight': '8',
'nine': '9',
'zero': '0'}[name])
except KeyError:
pass
class Controller(_base.Controller):
_KeyCode = KeyCode
_Key = Key
def __init__(self, *args, **kwargs):
super(Controller, self).__init__(*args, **kwargs)
self._layout = LAYOUT
self._dev = evdev.UInput()
def __del__(self):
if hasattr(self, '_dev'):
self._dev.close()
def _handle(self, key, is_press):
# Resolve the key to a virtual key code and a possible set of required
# modifiers
try:
vk, required_modifiers = self._to_vk_and_modifiers(key)
except ValueError:
raise self.InvalidKeyException(key)
# Determine how we need to modify the modifier state
if is_press and required_modifiers is not None:
with self.modifiers as modifiers:
vk, required_modifiers = self._layout.for_char(key.char)
to_press = {
getattr(evdev.ecodes, key.value._kernel_name)
for key in (required_modifiers - modifiers)}
to_release = {
getattr(evdev.ecodes, key.value._kernel_name)
for key in (modifiers - required_modifiers)}
else:
to_release = set()
to_press = set()
# Update the modifier state, send the key, and finally release any
# modifiers
cleanup = []
try:
for k in to_release:
self._send(k, False)
cleanup.append((k, True))
for k in to_press:
self._send(k, True)
cleanup.append((k, False))
self._send(vk, is_press)
finally:
for e in reversed(cleanup):
# pylint: disable E722; we want to suppress exceptions
try:
self._send(*e)
except:
pass
# pylint: enable E722
self._dev.syn()
def _to_vk_and_modifiers(self, key):
"""Resolves a key to a virtual key code and a modifier set.
:param key: The key to resolve.
:type key: Key or KeyCode
:return: a virtual key code and possible required modifiers
"""
if hasattr(key, 'vk') and key.vk is not None:
return (key.vk, None)
elif hasattr(key, 'char') and key.char is not None:
return self._layout.for_char(key.char)
else:
raise ValueError(key)
def _send(self, vk, is_press):
"""Sends a virtual key event.
This method does not perform ``SYN``.
:param int vk: The virtual key.
:param bool is_press: Whether this is a press event.
"""
self._dev.write(evdev.ecodes.EV_KEY, vk, int(is_press))
class Listener(ListenerMixin, _base.Listener):
_EVENTS = (
evdev.ecodes.EV_KEY,)
#: A
_MODIFIERS = {
Key.alt.value.vk: Key.alt,
Key.alt_l.value.vk: Key.alt,
Key.alt_r.value.vk: Key.alt,
Key.alt_gr.value.vk: Key.alt_gr,
Key.shift.value.vk: Key.shift,
Key.shift_l.value.vk: Key.shift,
Key.shift_r.value.vk: Key.shift}
def __init__(self, *args, **kwargs):
super(Listener, self).__init__(*args, **kwargs)
self._layout = LAYOUT
self._modifiers = set()
def _handle_message(self, event):
is_press = event.value in (KeyEvent.key_down, KeyEvent.key_hold)
vk = event.code
# Update the modifier state
if vk in self._MODIFIERS:
modifier = self._MODIFIERS[vk]
if is_press:
self._modifiers.add(modifier)
elif modifier in self._modifiers:
self._modifiers.remove(modifier)
# Attempt to map the virtual key code to a key
try:
key = self._layout.for_vk(vk, self._modifiers)
except KeyError:
try:
key = next(
key
for key in Key
if key.value.vk == vk)
except StopIteration:
key = KeyCode.from_vk(vk)
# We do not know whether these events are injected
if is_press:
self.on_press(key, False)
else:
self.on_release(key, False)
try:
#: The keyboard layout.
LAYOUT = Layout()
except subprocess.CalledProcessError as e:
raise ImportError('failed to load keyboard layout: "' + str(e) + (
'"; please make sure you are root' if os.getuid() != 1 else '"'))
except OSError as e:
raise ImportError({
errno.ENOENT: 'the binary dumpkeys is not installed'}.get(
e.args[0],
str(e)))

View File

@@ -0,0 +1,389 @@
# coding=utf-8
# pynput
# Copyright (C) 2015-2024 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
The keyboard implementation for *Windows*.
"""
# pylint: disable=C0111
# The documentation is extracted from the base classes
# pylint: disable=R0903
# We implement stubs
import contextlib
import ctypes
import enum
import six
from ctypes import wintypes
import pynput._util.win32_vks as VK
from pynput._util import AbstractListener
from pynput._util.win32 import (
INPUT,
INPUT_union,
KEYBDINPUT,
KeyTranslator,
ListenerMixin,
MapVirtualKey,
SendInput,
SystemHook,
VkKeyScan)
from . import _base
class KeyCode(_base.KeyCode):
_PLATFORM_EXTENSIONS = (
# Any extra flags.
'_flags',
#: The scan code.
'_scan',
)
# Be explicit about fields
_flags = None
_scan = None
def _parameters(self, is_press):
"""The parameters to pass to ``SendInput`` to generate this key.
:param bool is_press: Whether to generate a press event.
:return: all arguments to pass to ``SendInput`` for this key
:rtype: dict
:raise ValueError: if this key is a unicode character that cannot be
represented by a single UTF-16 value
"""
if self.vk:
vk = self.vk
scan = self._scan \
or MapVirtualKey(vk, MapVirtualKey.MAPVK_VK_TO_VSC)
flags = 0
elif ord(self.char) > 0xFFFF:
raise ValueError
else:
res = VkKeyScan(self.char)
if (res >> 8) & 0xFF == 0:
vk = res & 0xFF
scan = self._scan \
or MapVirtualKey(vk, MapVirtualKey.MAPVK_VK_TO_VSC)
flags = 0
else:
vk = 0
scan = ord(self.char)
flags = KEYBDINPUT.UNICODE
state_flags = (KEYBDINPUT.KEYUP if not is_press else 0)
return dict(
dwFlags=(self._flags or 0) | flags | state_flags,
wVk=vk,
wScan=scan)
@classmethod
def _from_ext(cls, vk, **kwargs):
"""Creates an extended key code.
:param vk: The virtual key code.
:param kwargs: Any other parameters to pass.
:return: a key code
"""
return cls.from_vk(vk, _flags=KEYBDINPUT.EXTENDEDKEY, **kwargs)
# pylint: disable=W0212
class Key(enum.Enum):
alt = KeyCode.from_vk(VK.MENU)
alt_l = KeyCode.from_vk(VK.LMENU)
alt_r = KeyCode._from_ext(VK.RMENU)
alt_gr = KeyCode.from_vk(VK.RMENU)
backspace = KeyCode.from_vk(VK.BACK)
caps_lock = KeyCode.from_vk(VK.CAPITAL)
cmd = KeyCode.from_vk(VK.LWIN)
cmd_l = KeyCode.from_vk(VK.LWIN)
cmd_r = KeyCode.from_vk(VK.RWIN)
ctrl = KeyCode.from_vk(VK.CONTROL)
ctrl_l = KeyCode.from_vk(VK.LCONTROL)
ctrl_r = KeyCode._from_ext(VK.RCONTROL)
delete = KeyCode._from_ext(VK.DELETE)
down = KeyCode._from_ext(VK.DOWN)
end = KeyCode._from_ext(VK.END)
enter = KeyCode.from_vk(VK.RETURN)
esc = KeyCode.from_vk(VK.ESCAPE)
f1 = KeyCode.from_vk(VK.F1)
f2 = KeyCode.from_vk(VK.F2)
f3 = KeyCode.from_vk(VK.F3)
f4 = KeyCode.from_vk(VK.F4)
f5 = KeyCode.from_vk(VK.F5)
f6 = KeyCode.from_vk(VK.F6)
f7 = KeyCode.from_vk(VK.F7)
f8 = KeyCode.from_vk(VK.F8)
f9 = KeyCode.from_vk(VK.F9)
f10 = KeyCode.from_vk(VK.F10)
f11 = KeyCode.from_vk(VK.F11)
f12 = KeyCode.from_vk(VK.F12)
f13 = KeyCode.from_vk(VK.F13)
f14 = KeyCode.from_vk(VK.F14)
f15 = KeyCode.from_vk(VK.F15)
f16 = KeyCode.from_vk(VK.F16)
f17 = KeyCode.from_vk(VK.F17)
f18 = KeyCode.from_vk(VK.F18)
f19 = KeyCode.from_vk(VK.F19)
f20 = KeyCode.from_vk(VK.F20)
f21 = KeyCode.from_vk(VK.F21)
f22 = KeyCode.from_vk(VK.F22)
f23 = KeyCode.from_vk(VK.F23)
f24 = KeyCode.from_vk(VK.F24)
home = KeyCode._from_ext(VK.HOME)
left = KeyCode._from_ext(VK.LEFT)
page_down = KeyCode._from_ext(VK.NEXT)
page_up = KeyCode._from_ext(VK.PRIOR)
right = KeyCode._from_ext(VK.RIGHT)
shift = KeyCode.from_vk(VK.LSHIFT)
shift_l = KeyCode.from_vk(VK.LSHIFT)
shift_r = KeyCode.from_vk(VK.RSHIFT)
space = KeyCode.from_vk(VK.SPACE, char=' ')
tab = KeyCode.from_vk(VK.TAB)
up = KeyCode._from_ext(VK.UP)
media_play_pause = KeyCode._from_ext(VK.MEDIA_PLAY_PAUSE)
media_stop = KeyCode._from_ext(VK.MEDIA_STOP)
media_volume_mute = KeyCode._from_ext(VK.VOLUME_MUTE)
media_volume_down = KeyCode._from_ext(VK.VOLUME_DOWN)
media_volume_up = KeyCode._from_ext(VK.VOLUME_UP)
media_previous = KeyCode._from_ext(VK.MEDIA_PREV_TRACK)
media_next = KeyCode._from_ext(VK.MEDIA_NEXT_TRACK)
insert = KeyCode._from_ext(VK.INSERT)
menu = KeyCode.from_vk(VK.APPS)
num_lock = KeyCode._from_ext(VK.NUMLOCK)
pause = KeyCode.from_vk(VK.PAUSE)
print_screen = KeyCode._from_ext(VK.SNAPSHOT)
scroll_lock = KeyCode.from_vk(VK.SCROLL)
# pylint: enable=W0212
class Controller(_base.Controller):
_KeyCode = KeyCode
_Key = Key
def __init__(self, *args, **kwargs):
super(Controller, self).__init__(*args, **kwargs)
def _handle(self, key, is_press):
try:
SendInput(
1,
ctypes.byref(INPUT(
type=INPUT.KEYBOARD,
value=INPUT_union(
ki=KEYBDINPUT(**key._parameters(is_press))))),
ctypes.sizeof(INPUT))
except ValueError:
# If key._parameters raises ValueError, the key is a unicode
# characters outsice of the range of a single UTF-16 value, and we
# must break it up into its surrogates
byte_data = bytearray(key.char.encode('utf-16le'))
surrogates = [
byte_data[i] | (byte_data[i + 1] << 8)
for i in range(0, len(byte_data), 2)]
state_flags = KEYBDINPUT.UNICODE \
| (KEYBDINPUT.KEYUP if not is_press else 0)
SendInput(
len(surrogates),
(INPUT * len(surrogates))(*(
INPUT(
INPUT.KEYBOARD,
INPUT_union(
ki=KEYBDINPUT(
dwFlags=state_flags,
wScan=scan)))
for scan in surrogates)),
ctypes.sizeof(INPUT))
class Listener(ListenerMixin, _base.Listener):
#: The Windows hook ID for low level keyboard events, ``WH_KEYBOARD_LL``
_EVENTS = 13
_WM_INPUTLANGCHANGE = 0x0051
_WM_KEYDOWN = 0x0100
_WM_KEYUP = 0x0101
_WM_SYSKEYDOWN = 0x0104
_WM_SYSKEYUP = 0x0105
# A bit flag attached to messages indicating that the payload is an actual
# UTF-16 character code
_UTF16_FLAG = 0x1000
# A bit flag attached to messages indicating that the event was injected
_INJECTED_FLAG = 0x2000
# A special virtual key code designating unicode characters
_VK_PACKET = 0xE7
#: The messages that correspond to a key press
_PRESS_MESSAGES = (_WM_KEYDOWN, _WM_SYSKEYDOWN)
#: The messages that correspond to a key release
_RELEASE_MESSAGES = (_WM_KEYUP, _WM_SYSKEYUP)
#: Additional window messages to propagate to the subclass handler.
_WM_NOTIFICATIONS = (
_WM_INPUTLANGCHANGE,
)
#: A mapping from keysym to special key
_SPECIAL_KEYS = {
key.value.vk: key
for key in Key}
_HANDLED_EXCEPTIONS = (
SystemHook.SuppressException,)
class _KBDLLHOOKSTRUCT(ctypes.Structure):
"""Contains information about a mouse event passed to a
``WH_KEYBOARD_LL`` hook procedure, ``LowLevelKeyboardProc``.
"""
LLKHF_INJECTED = 0x00000010
LLKHF_LOWER_IL_INJECTED = 0x00000002
_fields_ = [
('vkCode', wintypes.DWORD),
('scanCode', wintypes.DWORD),
('flags', wintypes.DWORD),
('time', wintypes.DWORD),
('dwExtraInfo', ctypes.c_void_p)]
#: A pointer to a :class:`KBDLLHOOKSTRUCT`
_LPKBDLLHOOKSTRUCT = ctypes.POINTER(_KBDLLHOOKSTRUCT)
def __init__(self, *args, **kwargs):
super(Listener, self).__init__(*args, **kwargs)
self._translator = KeyTranslator()
self._event_filter = self._options.get(
'event_filter',
lambda msg, data: True)
def _convert(self, code, msg, lpdata):
if code != SystemHook.HC_ACTION:
return
data = ctypes.cast(lpdata, self._LPKBDLLHOOKSTRUCT).contents
is_packet = data.vkCode == self._VK_PACKET
injected = (data.flags & (0
| self._KBDLLHOOKSTRUCT.LLKHF_INJECTED
| self._KBDLLHOOKSTRUCT.LLKHF_LOWER_IL_INJECTED)) != 0
message = (msg
| (self._UTF16_FLAG if is_packet else 0)
| (self._INJECTED_FLAG if injected else 0))
# Suppress further propagation of the event if it is filtered
if self._event_filter(msg, data) is False:
return None
elif is_packet:
return (message, data.scanCode)
else:
return (message, data.vkCode)
@AbstractListener._emitter
def _process(self, wparam, lparam):
msg = wparam
vk = lparam
# If the key has the UTF-16 flag, we treat it as a unicode character,
# otherwise convert the event to a KeyCode; this may fail, and in that
# case we pass None
is_utf16 = msg & self._UTF16_FLAG
injected = bool(msg & self._INJECTED_FLAG)
message = msg & ~(self._UTF16_FLAG | self._INJECTED_FLAG)
if is_utf16:
scan = vk
key = KeyCode.from_char(six.unichr(scan))
else:
try:
key = self._event_to_key(msg, vk)
except OSError:
key = None
if message in self._PRESS_MESSAGES:
self.on_press(key, injected)
elif message in self._RELEASE_MESSAGES:
self.on_release(key, injected)
# pylint: disable=R0201
@contextlib.contextmanager
def _receive(self):
"""An empty context manager; we do not need to fake keyboard events.
"""
yield
# pylint: enable=R0201
def _on_notification(self, code, wparam, lparam):
"""Receives ``WM_INPUTLANGCHANGE`` and updates the cached layout.
"""
if code == self._WM_INPUTLANGCHANGE:
self._translator.update_layout()
def _event_to_key(self, msg, vk):
"""Converts an :class:`_KBDLLHOOKSTRUCT` to a :class:`KeyCode`.
:param msg: The message received.
:param vk: The virtual key code to convert.
:return: a :class:`pynput.keyboard.KeyCode`
:raises OSError: if the message and data could not be converted
"""
# If the virtual key code corresponds to a Key value, we prefer that
if vk in self._SPECIAL_KEYS:
return self._SPECIAL_KEYS[vk]
else:
return KeyCode(**self._translate(
vk,
msg in self._PRESS_MESSAGES))
def _translate(self, vk, is_press):
"""Translates a virtual key code to a parameter list passable to
:class:`pynput.keyboard.KeyCode`.
:param int vk: The virtual key code.
:param bool is_press: Whether this is a press event.
:return: a parameter list to the :class:`pynput.keyboard.KeyCode`
constructor
"""
return self._translator(vk, is_press)
def canonical(self, key):
# If the key has a scan code, and we can find the character for it,
# return that, otherwise call the super class
scan = getattr(key, '_scan', None)
if scan is not None:
char = self._translator.char_from_scan(scan)
if char is not None:
return KeyCode.from_char(char)
return super(Listener, self).canonical(key)

View File

@@ -0,0 +1,667 @@
# coding=utf-8
# pynput
# Copyright (C) 2015-2024 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
The keyboard implementation for *Xorg*.
"""
# pylint: disable=C0111
# The documentation is extracted from the base classes
# pylint: disable=R0903
# We implement stubs
# pylint: disable=W0611
try:
import pynput._util.xorg
except Exception as e:
raise ImportError('failed to acquire X connection: {}'.format(str(e)), e)
# pylint: enable=W0611
import enum
import threading
import Xlib.display
import Xlib.ext
import Xlib.ext.xtest
import Xlib.X
import Xlib.XK
import Xlib.protocol
import Xlib.keysymdef.xkb
from pynput._util import NotifierMixin
from pynput._util.xorg import (
alt_mask,
alt_gr_mask,
char_to_keysym,
display_manager,
index_to_shift,
keyboard_mapping,
ListenerMixin,
numlock_mask,
shift_to_index,
symbol_to_keysym)
from pynput._util.xorg_keysyms import (
CHARS,
DEAD_KEYS,
KEYPAD_KEYS,
KEYSYMS,
SYMBOLS)
from . import _base
class KeyCode(_base.KeyCode):
_PLATFORM_EXTENSIONS = (
# The symbol name for this key
'_symbol',
)
# Be explicit about fields
_symbol = None
@classmethod
def _from_symbol(cls, symbol, **kwargs):
"""Creates a key from a symbol.
:param str symbol: The symbol name.
:return: a key code
"""
# First try simple translation
keysym = Xlib.XK.string_to_keysym(symbol)
if keysym:
return cls.from_vk(keysym, _symbol=symbol, **kwargs)
# If that fails, try checking a module attribute of Xlib.keysymdef.xkb
if not keysym:
# pylint: disable=W0702; we want to ignore errors
try:
symbol = 'XK_' + symbol
return cls.from_vk(
getattr(Xlib.keysymdef.xkb, symbol, 0),
_symbol=symbol,
**kwargs)
except:
return cls.from_vk(
SYMBOLS.get(symbol, (0,))[0],
_symbol=symbol,
**kwargs)
# pylint: enable=W0702
@classmethod
def _from_media(cls, name, **kwargs):
"""Creates a media key from a partial name.
:param str name: The name. The actual symbol name will be this string
with ``'XF86_Audio'`` prepended.
:return: a key code
"""
return cls._from_symbol('XF86_Audio' + name, **kwargs)
# pylint: disable=W0212
class Key(enum.Enum):
# Default keys
alt = KeyCode._from_symbol('Alt_L')
alt_l = KeyCode._from_symbol('Alt_L')
alt_r = KeyCode._from_symbol('Alt_R')
alt_gr = KeyCode._from_symbol('Mode_switch')
backspace = KeyCode._from_symbol('BackSpace')
caps_lock = KeyCode._from_symbol('Caps_Lock')
cmd = KeyCode._from_symbol('Super_L')
cmd_l = KeyCode._from_symbol('Super_L')
cmd_r = KeyCode._from_symbol('Super_R')
ctrl = KeyCode._from_symbol('Control_L')
ctrl_l = KeyCode._from_symbol('Control_L')
ctrl_r = KeyCode._from_symbol('Control_R')
delete = KeyCode._from_symbol('Delete')
down = KeyCode._from_symbol('Down')
end = KeyCode._from_symbol('End')
enter = KeyCode._from_symbol('Return')
esc = KeyCode._from_symbol('Escape')
f1 = KeyCode._from_symbol('F1')
f2 = KeyCode._from_symbol('F2')
f3 = KeyCode._from_symbol('F3')
f4 = KeyCode._from_symbol('F4')
f5 = KeyCode._from_symbol('F5')
f6 = KeyCode._from_symbol('F6')
f7 = KeyCode._from_symbol('F7')
f8 = KeyCode._from_symbol('F8')
f9 = KeyCode._from_symbol('F9')
f10 = KeyCode._from_symbol('F10')
f11 = KeyCode._from_symbol('F11')
f12 = KeyCode._from_symbol('F12')
f13 = KeyCode._from_symbol('F13')
f14 = KeyCode._from_symbol('F14')
f15 = KeyCode._from_symbol('F15')
f16 = KeyCode._from_symbol('F16')
f17 = KeyCode._from_symbol('F17')
f18 = KeyCode._from_symbol('F18')
f19 = KeyCode._from_symbol('F19')
f20 = KeyCode._from_symbol('F20')
home = KeyCode._from_symbol('Home')
left = KeyCode._from_symbol('Left')
page_down = KeyCode._from_symbol('Page_Down')
page_up = KeyCode._from_symbol('Page_Up')
right = KeyCode._from_symbol('Right')
shift = KeyCode._from_symbol('Shift_L')
shift_l = KeyCode._from_symbol('Shift_L')
shift_r = KeyCode._from_symbol('Shift_R')
space = KeyCode._from_symbol('space', char=' ')
tab = KeyCode._from_symbol('Tab')
up = KeyCode._from_symbol('Up')
media_play_pause = KeyCode._from_media('Play')
media_volume_mute = KeyCode._from_media('Mute')
media_volume_down = KeyCode._from_media('LowerVolume')
media_volume_up = KeyCode._from_media('RaiseVolume')
media_previous = KeyCode._from_media('Prev')
media_next = KeyCode._from_media('Next')
insert = KeyCode._from_symbol('Insert')
menu = KeyCode._from_symbol('Menu')
num_lock = KeyCode._from_symbol('Num_Lock')
pause = KeyCode._from_symbol('Pause')
print_screen = KeyCode._from_symbol('Print')
scroll_lock = KeyCode._from_symbol('Scroll_Lock')
# pylint: enable=W0212
class Controller(NotifierMixin, _base.Controller):
_KeyCode = KeyCode
_Key = Key
#: The shift mask for :attr:`Key.ctrl`
CTRL_MASK = Xlib.X.ControlMask
#: The shift mask for :attr:`Key.shift`
SHIFT_MASK = Xlib.X.ShiftMask
def __init__(self, *args, **kwargs):
super(Controller, self).__init__(*args, **kwargs)
self._display = Xlib.display.Display()
self._keyboard_mapping = None
self._borrows = {}
self._borrow_lock = threading.RLock()
# pylint: disable=C0103; this is treated as a class scope constant, but
# we cannot set it in the class scope, as it requires a Display instance
self.ALT_MASK = alt_mask(self._display)
self.ALT_GR_MASK = alt_gr_mask(self._display)
# pylint: enable=C0103
def __del__(self):
if hasattr(self, '_display'):
self._display.close()
@property
def keyboard_mapping(self):
"""A mapping from *keysyms* to *key codes*.
Each value is the tuple ``(key_code, shift_state)``. By sending an
event with the specified *key code* and shift state, the specified
*keysym* will be touched.
"""
if not self._keyboard_mapping:
self._update_keyboard_mapping()
return self._keyboard_mapping
def _handle(self, key, is_press):
"""Resolves a key identifier and sends a keyboard event.
:param int key: The key to handle.
:param bool is_press: Whether this is a press.
"""
event = Xlib.display.event.KeyPress if is_press \
else Xlib.display.event.KeyRelease
keysym = self._keysym(key)
# Make sure to verify that the key was resolved
if keysym is None:
raise self.InvalidKeyException(key)
# If the key has a virtual key code, use that immediately with
# fake_input; fake input,being an X server extension, has access to
# more internal state that we do
if key.vk is not None:
with display_manager(self._display) as dm:
Xlib.ext.xtest.fake_input(
dm,
Xlib.X.KeyPress if is_press else Xlib.X.KeyRelease,
dm.keysym_to_keycode(key.vk))
# Otherwise use XSendEvent; we need to use this in the general case to
# work around problems with keyboard layouts
else:
try:
keycode, shift_state = self.keyboard_mapping[keysym]
self._send_key(event, keycode, shift_state)
except KeyError:
with self._borrow_lock:
keycode, index, count = self._borrows[keysym]
self._send_key(
event,
keycode,
index_to_shift(self._display, index))
count += 1 if is_press else -1
self._borrows[keysym] = (keycode, index, count)
# Notify any running listeners
self._emit('_on_fake_event', key, is_press)
def _keysym(self, key):
"""Converts a key to a *keysym*.
:param KeyCode key: The key code to convert.
"""
return self._resolve_dead(key) if key.is_dead else None \
or self._resolve_special(key) \
or self._resolve_normal(key) \
or self._resolve_borrowed(key) \
or self._resolve_borrowing(key)
def _send_key(self, event, keycode, shift_state):
"""Sends a single keyboard event.
:param event: The *X* keyboard event.
:param int keycode: The calculated keycode.
:param int shift_state: The shift state. The actual value used is
:attr:`shift_state` or'd with this value.
"""
with display_manager(self._display) as dm, self.modifiers as modifiers:
# Under certain cimcumstances, such as when running under Xephyr,
# the value returned by dm.get_input_focus is an int
window = dm.get_input_focus().focus
send_event = getattr(
window,
'send_event',
lambda event: dm.send_event(window, event))
send_event(event(
detail=keycode,
state=shift_state | self._shift_mask(modifiers),
time=0,
root=dm.screen().root,
window=window,
same_screen=0,
child=Xlib.X.NONE,
root_x=0, root_y=0, event_x=0, event_y=0))
def _resolve_dead(self, key):
"""Tries to resolve a dead key.
:param str identifier: The identifier to resolve.
"""
# pylint: disable=W0702; we want to ignore errors
try:
keysym, _ = SYMBOLS[CHARS[key.combining]]
except:
return None
# pylint: enable=W0702
if keysym not in self.keyboard_mapping:
return None
return keysym
def _resolve_special(self, key):
"""Tries to resolve a special key.
A special key has the :attr:`~KeyCode.vk` attribute set.
:param KeyCode key: The key to resolve.
"""
if not key.vk:
return None
return key.vk
def _resolve_normal(self, key):
"""Tries to resolve a normal key.
A normal key exists on the keyboard, and is typed by pressing
and releasing a simple key, possibly in combination with a modifier.
:param KeyCode key: The key to resolve.
"""
keysym = self._key_to_keysym(key)
if keysym is None:
return None
if keysym not in self.keyboard_mapping:
return None
return keysym
def _resolve_borrowed(self, key):
"""Tries to resolve a key by looking up the already borrowed *keysyms*.
A borrowed *keysym* does not exist on the keyboard, but has been
temporarily added to the layout.
:param KeyCode key: The key to resolve.
"""
keysym = self._key_to_keysym(key)
if keysym is None:
return None
with self._borrow_lock:
if keysym not in self._borrows:
return None
return keysym
def _resolve_borrowing(self, key):
"""Tries to resolve a key by modifying the layout temporarily.
A borrowed *keysym* does not exist on the keyboard, but is temporarily
added to the layout.
:param KeyCode key: The key to resolve.
"""
keysym = self._key_to_keysym(key)
if keysym is None:
return None
mapping = self._display.get_keyboard_mapping(8, 255 - 8)
def i2kc(index):
return index + 8
def kc2i(keycode):
return keycode - 8
#: Finds a keycode and index by looking at already used keycodes
def reuse():
for _, (keycode, _, _) in self._borrows.items():
keycodes = mapping[kc2i(keycode)]
# Only the first four items are addressable by X
for index in range(4):
if not keycodes[index]:
return keycode, index
#: Finds a keycode and index by using a new keycode
def borrow():
for i, keycodes in enumerate(mapping):
if not any(keycodes):
return i2kc(i), 0
#: Finds a keycode and index by reusing an old, unused one
def overwrite():
for keysym, (keycode, index, count) in self._borrows.items():
if count < 1:
del self._borrows[keysym]
return keycode, index
#: Registers a keycode for a specific key and modifier state
def register(dm, keycode, index):
i = kc2i(keycode)
# Check for use of empty mapping with a character that has upper
# and lower forms
lower = key.char.lower()
upper = key.char.upper()
if lower != upper and len(lower) == 1 and len(upper) == 1 and all(
m == Xlib.XK.NoSymbol
for m in mapping[i]):
lower = self._key_to_keysym(KeyCode.from_char(lower))
upper = self._key_to_keysym(KeyCode.from_char(upper))
if lower:
mapping[i][0] = lower
self._borrows[lower] = (keycode, 0, 0)
if upper:
mapping[i][1] = upper
self._borrows[upper] = (keycode, 1, 0)
else:
mapping[i][index] = keysym
self._borrows[keysym] = (keycode, index, 0)
dm.change_keyboard_mapping(keycode, mapping[i:i + 1])
try:
with display_manager(self._display) as dm, self._borrow_lock as _:
# First try an already used keycode, then try a new one, and
# fall back on reusing one that is not currently pressed
register(dm, *(
reuse() or
borrow() or
overwrite()))
return keysym
except TypeError:
return None
def _key_to_keysym(self, key):
"""Converts a character key code to a *keysym*.
:param KeyCode key: The key code.
:return: a keysym if found
:rtype: int or None
"""
# If the key code already has a VK, simply return it
if key.vk is not None:
return key.vk
# If the character has no associated symbol, we try to map the
# character to a keysym
symbol = CHARS.get(key.char, None)
if symbol is None:
return char_to_keysym(key.char)
# Otherwise we attempt to convert the symbol to a keysym
# pylint: disable=W0702; we want to ignore errors
try:
return symbol_to_keysym(symbol)
except:
try:
return SYMBOLS[symbol][0]
except:
return None
# pylint: enable=W0702
def _shift_mask(self, modifiers):
"""The *X* modifier mask to apply for a set of modifiers.
:param set modifiers: A set of active modifiers for which to get the
shift mask.
"""
return (
0
| (self.ALT_MASK
if Key.alt in modifiers else 0)
| (self.ALT_GR_MASK
if Key.alt_gr in modifiers else 0)
| (self.CTRL_MASK
if Key.ctrl in modifiers else 0)
| (self.SHIFT_MASK
if Key.shift in modifiers else 0))
def _update_keyboard_mapping(self):
"""Updates the keyboard mapping.
"""
with display_manager(self._display) as dm:
self._keyboard_mapping = keyboard_mapping(dm)
@Controller._receiver
class Listener(ListenerMixin, _base.Listener):
_EVENTS = (
Xlib.X.KeyPress,
Xlib.X.KeyRelease)
#: A mapping from keysym to special key
_SPECIAL_KEYS = {
key.value.vk: key
for key in Key}
#: A mapping from numeric keypad keys to keys
_KEYPAD_KEYS = {
KEYPAD_KEYS['KP_0']: KeyCode.from_char('0'),
KEYPAD_KEYS['KP_1']: KeyCode.from_char('1'),
KEYPAD_KEYS['KP_2']: KeyCode.from_char('2'),
KEYPAD_KEYS['KP_3']: KeyCode.from_char('3'),
KEYPAD_KEYS['KP_4']: KeyCode.from_char('4'),
KEYPAD_KEYS['KP_5']: KeyCode.from_char('5'),
KEYPAD_KEYS['KP_6']: KeyCode.from_char('6'),
KEYPAD_KEYS['KP_7']: KeyCode.from_char('7'),
KEYPAD_KEYS['KP_8']: KeyCode.from_char('8'),
KEYPAD_KEYS['KP_9']: KeyCode.from_char('9'),
KEYPAD_KEYS['KP_Add']: KeyCode.from_char('+'),
KEYPAD_KEYS['KP_Decimal']: KeyCode.from_char(','),
KEYPAD_KEYS['KP_Delete']: Key.delete,
KEYPAD_KEYS['KP_Divide']: KeyCode.from_char('/'),
KEYPAD_KEYS['KP_Down']: Key.down,
KEYPAD_KEYS['KP_End']: Key.end,
KEYPAD_KEYS['KP_Enter']: Key.enter,
KEYPAD_KEYS['KP_Equal']: KeyCode.from_char('='),
KEYPAD_KEYS['KP_F1']: Key.f1,
KEYPAD_KEYS['KP_F2']: Key.f2,
KEYPAD_KEYS['KP_F3']: Key.f3,
KEYPAD_KEYS['KP_F4']: Key.f4,
KEYPAD_KEYS['KP_Home']: Key.home,
KEYPAD_KEYS['KP_Insert']: Key.insert,
KEYPAD_KEYS['KP_Left']: Key.left,
KEYPAD_KEYS['KP_Multiply']: KeyCode.from_char('*'),
KEYPAD_KEYS['KP_Page_Down']: Key.page_down,
KEYPAD_KEYS['KP_Page_Up']: Key.page_up,
KEYPAD_KEYS['KP_Right']: Key.right,
KEYPAD_KEYS['KP_Space']: Key.space,
KEYPAD_KEYS['KP_Subtract']: KeyCode.from_char('-'),
KEYPAD_KEYS['KP_Tab']: Key.tab,
KEYPAD_KEYS['KP_Up']: Key.up}
def __init__(self, *args, **kwargs):
super(Listener, self).__init__(*args, **kwargs)
self._keyboard_mapping = None
def _run(self):
with self._receive():
super(Listener, self)._run()
def _initialize(self, display):
# Get the keyboard mapping to be able to translate event details to
# key codes
min_keycode = display.display.info.min_keycode
keycode_count = display.display.info.max_keycode - min_keycode + 1
self._keyboard_mapping = display.get_keyboard_mapping(
min_keycode, keycode_count)
def _handle_message(self, display, event, injected):
# Convert the event to a KeyCode; this may fail, and in that case we
# pass None
try:
key = self._event_to_key(display, event)
except IndexError:
key = None
if event.type == Xlib.X.KeyPress:
self.on_press(key, injected)
elif event.type == Xlib.X.KeyRelease:
self.on_release(key, injected)
def _suppress_start(self, display):
display.screen().root.grab_keyboard(
self._event_mask, Xlib.X.GrabModeAsync, Xlib.X.GrabModeAsync,
Xlib.X.CurrentTime)
def _suppress_stop(self, display):
display.ungrab_keyboard(Xlib.X.CurrentTime)
def _on_fake_event(self, key, is_press):
"""The handler for fake press events sent by the controllers.
:param KeyCode key: The key pressed.
:param bool is_press: Whether this is a press event.
"""
(self.on_press if is_press else self.on_release)(
self._SPECIAL_KEYS.get(key.vk, key), True)
def _keycode_to_keysym(self, display, keycode, index):
"""Converts a keycode and shift state index to a keysym.
This method uses a simplified version of the *X* convention to locate
the correct keysym in the display table: since this method is only used
to locate special keys, alphanumeric keys are not treated specially.
:param display: The current *X* display.
:param keycode: The keycode.
:param index: The shift state index.
:return: a keysym
"""
keysym = display.keycode_to_keysym(keycode, index)
if keysym:
return keysym
elif index & 0x2:
return self._keycode_to_keysym(display, keycode, index & ~0x2)
elif index & 0x1:
return self._keycode_to_keysym(display, keycode, index & ~0x1)
else:
return 0
def _event_to_key(self, display, event):
"""Converts an *X* event to a :class:`KeyCode`.
:param display: The current *X* display.
:param event: The event to convert.
:return: a :class:`pynput.keyboard.KeyCode`
:raises IndexError: if the key code is invalid
"""
keycode = event.detail
index = shift_to_index(display, event.state)
# First try special keys...
keysym = self._keycode_to_keysym(display, keycode, index)
if keysym in self._SPECIAL_KEYS:
return self._SPECIAL_KEYS[keysym]
elif keysym in self._KEYPAD_KEYS:
# We must recalculate the index if numlock is active; index 1 is the
# one to use
try:
return self._KEYPAD_KEYS[
self._keycode_to_keysym(
display,
keycode,
bool(event.state & numlock_mask(display)))]
except KeyError:
# Since we recalculated the key, this may happen
pass
# ...then try characters...
name = KEYSYMS.get(keysym, None)
if name is not None and name in SYMBOLS:
char = SYMBOLS[name][1].upper() if index & 1 else SYMBOLS[name][1]
if char in DEAD_KEYS:
return KeyCode.from_dead(DEAD_KEYS[char], vk=keysym)
else:
return KeyCode.from_char(char, vk=keysym)
# ...and fall back on a virtual key code
return KeyCode.from_vk(keysym)