first commit
This commit is contained in:
489
myenv/lib/python3.10/site-packages/pynput/_util/__init__.py
Normal file
489
myenv/lib/python3.10/site-packages/pynput/_util/__init__.py
Normal file
@@ -0,0 +1,489 @@
|
||||
# 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/>.
|
||||
"""
|
||||
General utility functions and classes.
|
||||
"""
|
||||
|
||||
# pylint: disable=R0903
|
||||
# We implement minimal mixins
|
||||
|
||||
# pylint: disable=W0212
|
||||
# We implement an internal API
|
||||
|
||||
import contextlib
|
||||
import functools
|
||||
import importlib
|
||||
import inspect
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
import six
|
||||
|
||||
from six.moves import queue
|
||||
|
||||
|
||||
#: Possible resolutions for import related errors.
|
||||
RESOLUTIONS = {
|
||||
'darwin': 'Please make sure that you have Python bindings for the '
|
||||
'system frameworks installed',
|
||||
'uinput': 'Please make sure that you are running as root, and that '
|
||||
'the utility dumpkeys is installed',
|
||||
'xorg': 'Please make sure that you have an X server running, and that '
|
||||
'the DISPLAY environment variable is set correctly'}
|
||||
|
||||
|
||||
def backend(package):
|
||||
"""Returns the backend module for a package.
|
||||
|
||||
:param str package: The package for which to load a backend.
|
||||
"""
|
||||
backend_name = os.environ.get(
|
||||
'PYNPUT_BACKEND_{}'.format(package.rsplit('.')[-1].upper()),
|
||||
os.environ.get('PYNPUT_BACKEND', None))
|
||||
if backend_name:
|
||||
modules = [backend_name]
|
||||
elif sys.platform == 'darwin':
|
||||
modules = ['darwin']
|
||||
elif sys.platform == 'win32':
|
||||
modules = ['win32']
|
||||
else:
|
||||
modules = ['xorg']
|
||||
|
||||
errors = []
|
||||
resolutions = []
|
||||
for module in modules:
|
||||
try:
|
||||
return importlib.import_module('._' + module, package)
|
||||
except ImportError as e:
|
||||
errors.append(e)
|
||||
if module in RESOLUTIONS:
|
||||
resolutions.append(RESOLUTIONS[module])
|
||||
|
||||
raise ImportError('this platform is not supported: {}'.format(
|
||||
'; '.join(str(e) for e in errors)) + ('\n\n'
|
||||
'Try one of the following resolutions:\n\n'
|
||||
+ '\n\n'.join(
|
||||
' * {}'.format(s)
|
||||
for s in resolutions))
|
||||
if resolutions else '')
|
||||
|
||||
|
||||
def prefix(base, cls):
|
||||
"""Calculates the prefix to use for platform specific options for a
|
||||
specific class.
|
||||
|
||||
The prefix if the name of the module containing the class that is an
|
||||
immediate subclass of ``base`` among the super classes of ``cls``.
|
||||
"""
|
||||
for super_cls in filter(
|
||||
lambda cls: issubclass(cls, base),
|
||||
cls.__mro__[1:]):
|
||||
if super_cls is base:
|
||||
return cls.__module__.rsplit('.', 1)[-1][1:] + '_'
|
||||
else:
|
||||
result = prefix(base, super_cls)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
|
||||
class AbstractListener(threading.Thread):
|
||||
"""A class implementing the basic behaviour for event listeners.
|
||||
|
||||
Instances of this class can be used as context managers. This is equivalent
|
||||
to the following code::
|
||||
|
||||
listener.start()
|
||||
listener.wait()
|
||||
try:
|
||||
with_statements()
|
||||
finally:
|
||||
listener.stop()
|
||||
|
||||
Actual implementations of this class must set the attribute ``_log``, which
|
||||
must be an instance of :class:`logging.Logger`.
|
||||
|
||||
: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: A mapping from callback attribute to callback handler. All
|
||||
handlers will be wrapped in a function reading the return value of the
|
||||
callback, and if it ``is False``, raising :class:`StopException`.
|
||||
|
||||
Any callback that is falsy will be ignored.
|
||||
"""
|
||||
class StopException(Exception):
|
||||
"""If an event listener callback raises this exception, the current
|
||||
listener is stopped.
|
||||
"""
|
||||
pass
|
||||
|
||||
#: Exceptions that are handled outside of the emitter and should thus not
|
||||
#: be passed through the queue
|
||||
_HANDLED_EXCEPTIONS = tuple()
|
||||
|
||||
def __init__(self, suppress=False, **kwargs):
|
||||
super(AbstractListener, self).__init__()
|
||||
|
||||
def wrapper(f):
|
||||
def inner(*args):
|
||||
if f(*args) is False:
|
||||
raise self.StopException()
|
||||
return inner
|
||||
|
||||
self._suppress = suppress
|
||||
self._running = False
|
||||
self._thread = threading.current_thread()
|
||||
self._condition = threading.Condition()
|
||||
self._ready = False
|
||||
|
||||
# Allow multiple calls to stop
|
||||
self._queue = queue.Queue(10)
|
||||
|
||||
self.daemon = True
|
||||
|
||||
for name, callback in kwargs.items():
|
||||
setattr(self, name, wrapper(callback))
|
||||
|
||||
@property
|
||||
def suppress(self):
|
||||
"""Whether to suppress events.
|
||||
"""
|
||||
return self._suppress
|
||||
|
||||
@property
|
||||
def running(self):
|
||||
"""Whether the listener is currently running.
|
||||
"""
|
||||
return self._running
|
||||
|
||||
def stop(self):
|
||||
"""Stops listening for events.
|
||||
|
||||
When this method returns, no more events will be delivered. Once this
|
||||
method has been called, the listener instance cannot be used any more,
|
||||
since a listener is a :class:`threading.Thread`, and once stopped it
|
||||
cannot be restarted.
|
||||
|
||||
To resume listening for event, a new listener must be created.
|
||||
"""
|
||||
if self._running:
|
||||
self._running = False
|
||||
self._queue.put(None)
|
||||
self._stop_platform()
|
||||
|
||||
def __enter__(self):
|
||||
self.start()
|
||||
self.wait()
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, value, traceback):
|
||||
self.stop()
|
||||
|
||||
def wait(self):
|
||||
"""Waits for this listener to become ready.
|
||||
"""
|
||||
self._condition.acquire()
|
||||
while not self._ready:
|
||||
self._condition.wait()
|
||||
self._condition.release()
|
||||
|
||||
def run(self):
|
||||
"""The thread runner method.
|
||||
"""
|
||||
self._running = True
|
||||
self._thread = threading.current_thread()
|
||||
self._run()
|
||||
|
||||
# Make sure that the queue contains something
|
||||
self._queue.put(None)
|
||||
|
||||
@classmethod
|
||||
def _emitter(cls, f):
|
||||
"""A decorator to mark a method as the one emitting the callbacks.
|
||||
|
||||
This decorator will wrap the method and catch exception. If a
|
||||
:class:`StopException` is caught, the listener will be stopped
|
||||
gracefully. If any other exception is caught, it will be propagated to
|
||||
the thread calling :meth:`join` and reraised there.
|
||||
"""
|
||||
@functools.wraps(f)
|
||||
def inner(self, *args, **kwargs):
|
||||
# pylint: disable=W0702; we want to catch all exception
|
||||
try:
|
||||
return f(self, *args, **kwargs)
|
||||
except Exception as e:
|
||||
if not isinstance(e, self._HANDLED_EXCEPTIONS):
|
||||
if not isinstance(e, AbstractListener.StopException):
|
||||
self._log.exception(
|
||||
'Unhandled exception in listener callback')
|
||||
self._queue.put(
|
||||
None if isinstance(e, cls.StopException)
|
||||
else sys.exc_info())
|
||||
self.stop()
|
||||
raise
|
||||
# pylint: enable=W0702
|
||||
|
||||
return inner
|
||||
|
||||
def _mark_ready(self):
|
||||
"""Marks this listener as ready to receive events.
|
||||
|
||||
This method must be called from :meth:`_run`. :meth:`wait` will block
|
||||
until this method is called.
|
||||
"""
|
||||
self._condition.acquire()
|
||||
self._ready = True
|
||||
self._condition.notify()
|
||||
self._condition.release()
|
||||
|
||||
def _run(self):
|
||||
"""The implementation of the :meth:`run` method.
|
||||
|
||||
This is a platform dependent implementation.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def _stop_platform(self):
|
||||
"""The implementation of the :meth:`stop` method.
|
||||
|
||||
This is a platform dependent implementation.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def _wrap(self, f, args):
|
||||
"""Wraps a callable to make it accept ``args`` number of arguments.
|
||||
|
||||
:param f: The callable to wrap. If this is ``None`` a no-op wrapper is
|
||||
returned.
|
||||
|
||||
:param int args: The number of arguments to accept.
|
||||
|
||||
:raises ValueError: if f requires more than ``args`` arguments
|
||||
"""
|
||||
if f is None:
|
||||
return lambda *a: None
|
||||
else:
|
||||
argspec = inspect.getfullargspec(f)
|
||||
actual = len(inspect.signature(f).parameters)
|
||||
defaults = len(argspec.defaults) if argspec.defaults else 0
|
||||
if actual - defaults > args:
|
||||
raise ValueError(f)
|
||||
elif actual >= args or argspec.varargs is not None:
|
||||
return f
|
||||
else:
|
||||
return lambda *a: f(*a[:actual])
|
||||
|
||||
def join(self, timeout=None, *args):
|
||||
start = time.time()
|
||||
super(AbstractListener, self).join(timeout, *args)
|
||||
timeout = max(0.0, timeout - (time.time() - start)) \
|
||||
if timeout is not None \
|
||||
else None
|
||||
|
||||
# Reraise any exceptions; make sure not to block if a timeout was
|
||||
# provided
|
||||
try:
|
||||
exc_type, exc_value, exc_traceback = self._queue.get(
|
||||
timeout=timeout)
|
||||
six.reraise(exc_type, exc_value, exc_traceback)
|
||||
except queue.Empty:
|
||||
pass
|
||||
except TypeError:
|
||||
return
|
||||
|
||||
|
||||
class Events(object):
|
||||
"""A base class to enable iterating over events.
|
||||
"""
|
||||
#: The listener class providing events.
|
||||
_Listener = None
|
||||
|
||||
class Event(object):
|
||||
def __str__(self):
|
||||
return '{}({})'.format(
|
||||
self.__class__.__name__,
|
||||
', '.join(
|
||||
'{}={}'.format(k, v)
|
||||
for (k, v) in vars(self).items()))
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.__class__ == other.__class__ \
|
||||
and dir(self) == dir(other) \
|
||||
and all(
|
||||
getattr(self, k) == getattr(other, k)
|
||||
for k in dir(self))
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(Events, self).__init__()
|
||||
self._event_queue = queue.Queue()
|
||||
self._sentinel = object()
|
||||
self._listener = self._Listener(*args, **{
|
||||
key: self._event_mapper(value)
|
||||
for (key, value) in kwargs.items()})
|
||||
self.start = self._listener.start
|
||||
|
||||
def __enter__(self):
|
||||
self._listener.__enter__()
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
self._listener.__exit__(*args)
|
||||
|
||||
# Drain the queue to ensure that the put does not block
|
||||
while True:
|
||||
try:
|
||||
self._event_queue.get_nowait()
|
||||
except queue.Empty:
|
||||
break
|
||||
|
||||
self._event_queue.put(self._sentinel)
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
def __next__(self):
|
||||
event = self.get()
|
||||
if event is not None:
|
||||
return event
|
||||
else:
|
||||
raise StopIteration()
|
||||
|
||||
def get(self, timeout=None):
|
||||
"""Attempts to read the next event.
|
||||
|
||||
:param int timeout: An optional timeout. If this is not provided, this
|
||||
method may block infinitely.
|
||||
|
||||
:return: the next event, or ``None`` if the source has been stopped or
|
||||
no events were received
|
||||
"""
|
||||
try:
|
||||
event = self._event_queue.get(timeout=timeout)
|
||||
return event if event is not self._sentinel else None
|
||||
except queue.Empty:
|
||||
return None
|
||||
|
||||
def _event_mapper(self, event):
|
||||
"""Generates an event callback to transforms the callback arguments to
|
||||
an event and then publishes it.
|
||||
|
||||
:param callback event: A function generating an event object.
|
||||
|
||||
:return: a callback
|
||||
"""
|
||||
@functools.wraps(event)
|
||||
def inner(*args):
|
||||
try:
|
||||
self._event_queue.put(event(*args), block=False)
|
||||
except queue.Full:
|
||||
pass
|
||||
|
||||
return inner
|
||||
|
||||
|
||||
class NotifierMixin(object):
|
||||
"""A mixin for notifiers of fake events.
|
||||
|
||||
This mixin can be used for controllers on platforms where sending fake
|
||||
events does not cause a listener to receive a notification.
|
||||
"""
|
||||
def _emit(self, action, *args):
|
||||
"""Sends a notification to all registered listeners.
|
||||
|
||||
This method will ensure that listeners that raise
|
||||
:class:`StopException` are stopped.
|
||||
|
||||
:param str action: The name of the notification.
|
||||
|
||||
:param args: The arguments to pass.
|
||||
"""
|
||||
stopped = []
|
||||
for listener in self._listeners():
|
||||
try:
|
||||
getattr(listener, action)(*args)
|
||||
except listener.StopException:
|
||||
stopped.append(listener)
|
||||
for listener in stopped:
|
||||
listener.stop()
|
||||
|
||||
@classmethod
|
||||
def _receiver(cls, listener_class):
|
||||
"""A decorator to make a class able to receive fake events from a
|
||||
controller.
|
||||
|
||||
This decorator will add the method ``_receive`` to the decorated class.
|
||||
|
||||
This method is a context manager which ensures that all calls to
|
||||
:meth:`_emit` will invoke the named method in the listener instance
|
||||
while the block is active.
|
||||
"""
|
||||
@contextlib.contextmanager
|
||||
def receive(self):
|
||||
"""Executes a code block with this listener instance registered as
|
||||
a receiver of fake input events.
|
||||
"""
|
||||
self._controller_class._add_listener(self)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self._controller_class._remove_listener(self)
|
||||
|
||||
listener_class._receive = receive
|
||||
listener_class._controller_class = cls
|
||||
|
||||
# Make sure this class has the necessary attributes
|
||||
if not hasattr(cls, '_listener_cache'):
|
||||
cls._listener_cache = set()
|
||||
cls._listener_lock = threading.Lock()
|
||||
|
||||
return listener_class
|
||||
|
||||
@classmethod
|
||||
def _listeners(cls):
|
||||
"""Iterates over the set of running listeners.
|
||||
|
||||
This method will quit without acquiring the lock if the set is empty,
|
||||
so there is potential for race conditions. This is an optimisation,
|
||||
since :class:`Controller` will need to call this method for every
|
||||
control event.
|
||||
"""
|
||||
if not cls._listener_cache:
|
||||
return
|
||||
with cls._listener_lock:
|
||||
for listener in cls._listener_cache:
|
||||
yield listener
|
||||
|
||||
@classmethod
|
||||
def _add_listener(cls, listener):
|
||||
"""Adds a listener to the set of running listeners.
|
||||
|
||||
:param listener: The listener for fake events.
|
||||
"""
|
||||
with cls._listener_lock:
|
||||
cls._listener_cache.add(listener)
|
||||
|
||||
@classmethod
|
||||
def _remove_listener(cls, listener):
|
||||
"""Removes this listener from the set of running listeners.
|
||||
|
||||
:param listener: The listener for fake events.
|
||||
"""
|
||||
with cls._listener_lock:
|
||||
cls._listener_cache.remove(listener)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
302
myenv/lib/python3.10/site-packages/pynput/_util/darwin.py
Normal file
302
myenv/lib/python3.10/site-packages/pynput/_util/darwin.py
Normal file
@@ -0,0 +1,302 @@
|
||||
# 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/>.
|
||||
"""
|
||||
Utility functions and classes for the *Darwin* backend.
|
||||
"""
|
||||
|
||||
# pylint: disable=C0103
|
||||
# pylint: disable=R0903
|
||||
# This module contains wrapper classes
|
||||
|
||||
import contextlib
|
||||
import ctypes
|
||||
import ctypes.util
|
||||
import six
|
||||
|
||||
import objc
|
||||
import HIServices
|
||||
|
||||
from CoreFoundation import (
|
||||
CFRelease
|
||||
)
|
||||
|
||||
from Quartz import (
|
||||
CFMachPortCreateRunLoopSource,
|
||||
CFRunLoopAddSource,
|
||||
CFRunLoopGetCurrent,
|
||||
CFRunLoopRunInMode,
|
||||
CFRunLoopStop,
|
||||
CGEventGetIntegerValueField,
|
||||
CGEventTapCreate,
|
||||
CGEventTapEnable,
|
||||
kCFRunLoopDefaultMode,
|
||||
kCFRunLoopRunTimedOut,
|
||||
kCGEventSourceUnixProcessID,
|
||||
kCGEventTapOptionDefault,
|
||||
kCGEventTapOptionListenOnly,
|
||||
kCGHeadInsertEventTap,
|
||||
kCGSessionEventTap)
|
||||
|
||||
|
||||
from . import AbstractListener
|
||||
|
||||
|
||||
def _wrap_value(value):
|
||||
"""Converts a pointer to a *Python objc* value.
|
||||
|
||||
:param value: The pointer to convert.
|
||||
|
||||
:return: a wrapped value
|
||||
"""
|
||||
return objc.objc_object(c_void_p=value) if value is not None else None
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _wrapped(value):
|
||||
"""A context manager that converts a raw pointer to a *Python objc* value.
|
||||
|
||||
When the block is exited, the value is released.
|
||||
|
||||
:param value: The raw value to wrap.
|
||||
"""
|
||||
wrapped_value = _wrap_value(value)
|
||||
|
||||
try:
|
||||
yield value
|
||||
finally:
|
||||
CFRelease(wrapped_value)
|
||||
|
||||
|
||||
class CarbonExtra(object):
|
||||
"""A class exposing some missing functionality from *Carbon* as class
|
||||
attributes.
|
||||
"""
|
||||
_Carbon = ctypes.cdll.LoadLibrary(ctypes.util.find_library('Carbon'))
|
||||
|
||||
_Carbon.TISCopyCurrentKeyboardInputSource.argtypes = []
|
||||
_Carbon.TISCopyCurrentKeyboardInputSource.restype = ctypes.c_void_p
|
||||
|
||||
_Carbon.TISCopyCurrentASCIICapableKeyboardLayoutInputSource.argtypes = []
|
||||
_Carbon.TISCopyCurrentASCIICapableKeyboardLayoutInputSource.restype = \
|
||||
ctypes.c_void_p
|
||||
|
||||
_Carbon.TISGetInputSourceProperty.argtypes = [
|
||||
ctypes.c_void_p, ctypes.c_void_p]
|
||||
_Carbon.TISGetInputSourceProperty.restype = ctypes.c_void_p
|
||||
|
||||
_Carbon.LMGetKbdType.argtypes = []
|
||||
_Carbon.LMGetKbdType.restype = ctypes.c_uint32
|
||||
|
||||
_Carbon.UCKeyTranslate.argtypes = [
|
||||
ctypes.c_void_p,
|
||||
ctypes.c_uint16,
|
||||
ctypes.c_uint16,
|
||||
ctypes.c_uint32,
|
||||
ctypes.c_uint32,
|
||||
ctypes.c_uint32,
|
||||
ctypes.POINTER(ctypes.c_uint32),
|
||||
ctypes.c_uint8,
|
||||
ctypes.POINTER(ctypes.c_uint8),
|
||||
ctypes.c_uint16 * 4]
|
||||
_Carbon.UCKeyTranslate.restype = ctypes.c_uint32
|
||||
|
||||
TISCopyCurrentKeyboardInputSource = \
|
||||
_Carbon.TISCopyCurrentKeyboardInputSource
|
||||
|
||||
TISCopyCurrentASCIICapableKeyboardLayoutInputSource = \
|
||||
_Carbon.TISCopyCurrentASCIICapableKeyboardLayoutInputSource
|
||||
|
||||
kTISPropertyUnicodeKeyLayoutData = ctypes.c_void_p.in_dll(
|
||||
_Carbon, 'kTISPropertyUnicodeKeyLayoutData')
|
||||
|
||||
TISGetInputSourceProperty = \
|
||||
_Carbon.TISGetInputSourceProperty
|
||||
|
||||
LMGetKbdType = \
|
||||
_Carbon.LMGetKbdType
|
||||
|
||||
kUCKeyActionDisplay = 3
|
||||
kUCKeyTranslateNoDeadKeysBit = 0
|
||||
|
||||
UCKeyTranslate = \
|
||||
_Carbon.UCKeyTranslate
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def keycode_context():
|
||||
"""Returns an opaque value representing a context for translating keycodes
|
||||
to strings.
|
||||
"""
|
||||
keyboard_type, layout_data = None, None
|
||||
for source in [
|
||||
CarbonExtra.TISCopyCurrentKeyboardInputSource,
|
||||
CarbonExtra.TISCopyCurrentASCIICapableKeyboardLayoutInputSource]:
|
||||
with _wrapped(source()) as keyboard:
|
||||
keyboard_type = CarbonExtra.LMGetKbdType()
|
||||
layout = _wrap_value(CarbonExtra.TISGetInputSourceProperty(
|
||||
keyboard,
|
||||
CarbonExtra.kTISPropertyUnicodeKeyLayoutData))
|
||||
layout_data = layout.bytes().tobytes() if layout else None
|
||||
if keyboard is not None and layout_data is not None:
|
||||
break
|
||||
yield (keyboard_type, layout_data)
|
||||
|
||||
|
||||
def keycode_to_string(context, keycode, modifier_state=0):
|
||||
"""Converts a keycode to a string.
|
||||
"""
|
||||
LENGTH = 4
|
||||
|
||||
keyboard_type, layout_data = context
|
||||
|
||||
dead_key_state = ctypes.c_uint32()
|
||||
length = ctypes.c_uint8()
|
||||
unicode_string = (ctypes.c_uint16 * LENGTH)()
|
||||
CarbonExtra.UCKeyTranslate(
|
||||
layout_data,
|
||||
keycode,
|
||||
CarbonExtra.kUCKeyActionDisplay,
|
||||
modifier_state,
|
||||
keyboard_type,
|
||||
CarbonExtra.kUCKeyTranslateNoDeadKeysBit,
|
||||
ctypes.byref(dead_key_state),
|
||||
LENGTH,
|
||||
ctypes.byref(length),
|
||||
unicode_string)
|
||||
return u''.join(
|
||||
six.unichr(unicode_string[i])
|
||||
for i in range(length.value))
|
||||
|
||||
|
||||
def get_unicode_to_keycode_map():
|
||||
"""Returns a mapping from unicode strings to virtual key codes.
|
||||
|
||||
:return: a dict mapping key codes to strings
|
||||
"""
|
||||
with keycode_context() as context:
|
||||
return {
|
||||
keycode_to_string(context, keycode): keycode
|
||||
for keycode in range(128)}
|
||||
|
||||
|
||||
class ListenerMixin(object):
|
||||
"""A mixin for *Quartz* event listeners.
|
||||
|
||||
Subclasses should set a value for :attr:`_EVENTS` and implement
|
||||
:meth:`_handle_message`.
|
||||
"""
|
||||
#: The events that we listen to
|
||||
_EVENTS = tuple()
|
||||
|
||||
#: Whether this process is trusted to monitor input events.
|
||||
IS_TRUSTED = False
|
||||
|
||||
def _run(self):
|
||||
self.IS_TRUSTED = HIServices.AXIsProcessTrusted()
|
||||
if not self.IS_TRUSTED:
|
||||
self._log.warning(
|
||||
'This process is not trusted! Input event monitoring will not '
|
||||
'be possible until it is added to accessibility clients.')
|
||||
|
||||
self._loop = None
|
||||
try:
|
||||
tap = self._create_event_tap()
|
||||
if tap is None:
|
||||
self._mark_ready()
|
||||
return
|
||||
|
||||
loop_source = CFMachPortCreateRunLoopSource(
|
||||
None, tap, 0)
|
||||
self._loop = CFRunLoopGetCurrent()
|
||||
|
||||
CFRunLoopAddSource(
|
||||
self._loop, loop_source, kCFRunLoopDefaultMode)
|
||||
CGEventTapEnable(tap, True)
|
||||
|
||||
self._mark_ready()
|
||||
|
||||
# pylint: disable=W0702; we want to silence errors
|
||||
try:
|
||||
while self.running:
|
||||
result = CFRunLoopRunInMode(
|
||||
kCFRunLoopDefaultMode, 1, False)
|
||||
try:
|
||||
if result != kCFRunLoopRunTimedOut:
|
||||
break
|
||||
except AttributeError:
|
||||
# This happens during teardown of the virtual machine
|
||||
break
|
||||
|
||||
except:
|
||||
# This exception will have been passed to the main thread
|
||||
pass
|
||||
# pylint: enable=W0702
|
||||
|
||||
finally:
|
||||
self._loop = None
|
||||
|
||||
def _stop_platform(self):
|
||||
# The base class sets the running flag to False; this will cause the
|
||||
# loop around run loop invocations to terminate and set this event
|
||||
try:
|
||||
if self._loop is not None:
|
||||
CFRunLoopStop(self._loop)
|
||||
except AttributeError:
|
||||
# The loop may not have been created
|
||||
pass
|
||||
|
||||
def _create_event_tap(self):
|
||||
"""Creates the event tap used by the listener.
|
||||
|
||||
:return: an event tap
|
||||
"""
|
||||
return CGEventTapCreate(
|
||||
kCGSessionEventTap,
|
||||
kCGHeadInsertEventTap,
|
||||
kCGEventTapOptionListenOnly if (
|
||||
True
|
||||
and not self.suppress
|
||||
and self._intercept is None)
|
||||
else kCGEventTapOptionDefault,
|
||||
self._EVENTS,
|
||||
self._handler,
|
||||
None)
|
||||
|
||||
@AbstractListener._emitter
|
||||
def _handler(self, proxy, event_type, event, refcon):
|
||||
"""The callback registered with *macOS* for mouse events.
|
||||
|
||||
This method will call the callbacks registered on initialisation.
|
||||
"""
|
||||
# An injected event will have a Unix process ID attached
|
||||
is_injected = (CGEventGetIntegerValueField(
|
||||
event,
|
||||
kCGEventSourceUnixProcessID)) != 0
|
||||
|
||||
self._handle_message(proxy, event_type, event, refcon, is_injected)
|
||||
if self._intercept is not None:
|
||||
return self._intercept(event_type, event)
|
||||
elif self.suppress:
|
||||
return None
|
||||
|
||||
def _handle_message(self, proxy, event_type, event, refcon):
|
||||
"""The device specific callback handler.
|
||||
|
||||
This method calls the appropriate callback registered when this
|
||||
listener was created based on the event.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
@@ -0,0 +1,79 @@
|
||||
# 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/>.
|
||||
|
||||
# pylint: disable=C0111,C0302
|
||||
|
||||
SYMBOLS = {
|
||||
0: 'a',
|
||||
1: 's',
|
||||
2: 'd',
|
||||
3: 'f',
|
||||
4: 'h',
|
||||
5: 'g',
|
||||
6: 'z',
|
||||
7: 'x',
|
||||
8: 'c',
|
||||
9: 'v',
|
||||
11: 'b',
|
||||
12: 'q',
|
||||
13: 'w',
|
||||
14: 'e',
|
||||
15: 'r',
|
||||
16: 'y',
|
||||
17: 't',
|
||||
18: '1',
|
||||
19: '2',
|
||||
20: '3',
|
||||
21: '4',
|
||||
22: '6',
|
||||
23: '5',
|
||||
24: '=',
|
||||
25: '9',
|
||||
26: '7',
|
||||
27: '-',
|
||||
28: '8',
|
||||
29: '0',
|
||||
30: ']',
|
||||
31: 'o',
|
||||
32: 'u',
|
||||
33: '[',
|
||||
34: 'i',
|
||||
35: 'p',
|
||||
37: 'l',
|
||||
38: 'j',
|
||||
39: '\'',
|
||||
40: 'k',
|
||||
41: ';',
|
||||
42: '\\',
|
||||
43: ',',
|
||||
44: '/',
|
||||
45: 'n',
|
||||
46: 'm',
|
||||
47: '.',
|
||||
49: ' ',
|
||||
50: '`',
|
||||
82: '0',
|
||||
83: '1',
|
||||
84: '2',
|
||||
85: '3',
|
||||
86: '4',
|
||||
87: '5',
|
||||
88: '6',
|
||||
89: '7',
|
||||
91: '8',
|
||||
92: '9',
|
||||
}
|
||||
99
myenv/lib/python3.10/site-packages/pynput/_util/uinput.py
Normal file
99
myenv/lib/python3.10/site-packages/pynput/_util/uinput.py
Normal file
@@ -0,0 +1,99 @@
|
||||
# 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/>.
|
||||
"""
|
||||
Utility functions and classes for the *uinput* backend.
|
||||
"""
|
||||
|
||||
# pylint: disable=R0903
|
||||
# We implement stubs
|
||||
|
||||
import evdev
|
||||
|
||||
|
||||
# Check that we have permissions to continue
|
||||
def _check():
|
||||
# TODO: Implement!
|
||||
pass
|
||||
_check()
|
||||
del _check
|
||||
|
||||
|
||||
class ListenerMixin(object):
|
||||
"""A mixin for *uinput* event listeners.
|
||||
|
||||
Subclasses should set a value for :attr:`_EVENTS` and implement
|
||||
:meth:`_handle_message`.
|
||||
"""
|
||||
#: The events for which to listen
|
||||
_EVENTS = tuple()
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(ListenerMixin, self).__init__(*args, **kwargs)
|
||||
self._dev = self._device(self._options.get(
|
||||
'device_paths',
|
||||
evdev.list_devices()))
|
||||
if self.suppress:
|
||||
self._dev.grab()
|
||||
|
||||
def _run(self):
|
||||
for event in self._dev.read_loop():
|
||||
if event.type in self._EVENTS:
|
||||
self._handle_message(event)
|
||||
|
||||
def _stop_platform(self):
|
||||
self._dev.close()
|
||||
|
||||
def _device(self, paths):
|
||||
"""Attempts to load a readable keyboard device.
|
||||
|
||||
:param paths: A list of paths.
|
||||
|
||||
:return: a compatible device
|
||||
"""
|
||||
dev, count = None, 0
|
||||
for path in paths:
|
||||
# Open the device
|
||||
try:
|
||||
next_dev = evdev.InputDevice(path)
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
# Does this device provide more handled event codes?
|
||||
capabilities = next_dev.capabilities()
|
||||
next_count = sum(
|
||||
len(codes)
|
||||
for event, codes in capabilities.items()
|
||||
if event in self._EVENTS)
|
||||
if next_count > count:
|
||||
dev = next_dev
|
||||
count = next_count
|
||||
else:
|
||||
next_dev.close()
|
||||
|
||||
if dev is None:
|
||||
raise OSError('no keyboard device available')
|
||||
else:
|
||||
return dev
|
||||
|
||||
def _handle_message(self, event):
|
||||
"""Handles a single event.
|
||||
|
||||
This method should call one of the registered event callbacks.
|
||||
|
||||
:param event: The event.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
598
myenv/lib/python3.10/site-packages/pynput/_util/win32.py
Normal file
598
myenv/lib/python3.10/site-packages/pynput/_util/win32.py
Normal file
@@ -0,0 +1,598 @@
|
||||
# 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/>.
|
||||
"""
|
||||
Utility functions and classes for the *win32* backend.
|
||||
"""
|
||||
|
||||
# pylint: disable=C0103
|
||||
# We want to make it obvious how structs are related
|
||||
|
||||
# pylint: disable=R0903
|
||||
# This module contains a number of structs
|
||||
|
||||
import contextlib
|
||||
import ctypes
|
||||
import itertools
|
||||
import threading
|
||||
|
||||
from ctypes import (
|
||||
windll,
|
||||
wintypes)
|
||||
|
||||
from . import AbstractListener, win32_vks as VK
|
||||
|
||||
|
||||
# LPDWORD is not in ctypes.wintypes on Python 2
|
||||
if not hasattr(wintypes, 'LPDWORD'):
|
||||
wintypes.LPDWORD = ctypes.POINTER(wintypes.DWORD)
|
||||
|
||||
|
||||
class MOUSEINPUT(ctypes.Structure):
|
||||
"""Contains information about a simulated mouse event.
|
||||
"""
|
||||
MOVE = 0x0001
|
||||
LEFTDOWN = 0x0002
|
||||
LEFTUP = 0x0004
|
||||
RIGHTDOWN = 0x0008
|
||||
RIGHTUP = 0x0010
|
||||
MIDDLEDOWN = 0x0020
|
||||
MIDDLEUP = 0x0040
|
||||
XDOWN = 0x0080
|
||||
XUP = 0x0100
|
||||
WHEEL = 0x0800
|
||||
HWHEEL = 0x1000
|
||||
ABSOLUTE = 0x8000
|
||||
|
||||
XBUTTON1 = 0x0001
|
||||
XBUTTON2 = 0x0002
|
||||
|
||||
_fields_ = [
|
||||
('dx', wintypes.LONG),
|
||||
('dy', wintypes.LONG),
|
||||
('mouseData', wintypes.DWORD),
|
||||
('dwFlags', wintypes.DWORD),
|
||||
('time', wintypes.DWORD),
|
||||
('dwExtraInfo', ctypes.c_void_p)]
|
||||
|
||||
|
||||
class KEYBDINPUT(ctypes.Structure):
|
||||
"""Contains information about a simulated keyboard event.
|
||||
"""
|
||||
EXTENDEDKEY = 0x0001
|
||||
KEYUP = 0x0002
|
||||
SCANCODE = 0x0008
|
||||
UNICODE = 0x0004
|
||||
|
||||
_fields_ = [
|
||||
('wVk', wintypes.WORD),
|
||||
('wScan', wintypes.WORD),
|
||||
('dwFlags', wintypes.DWORD),
|
||||
('time', wintypes.DWORD),
|
||||
('dwExtraInfo', ctypes.c_void_p)]
|
||||
|
||||
|
||||
class HARDWAREINPUT(ctypes.Structure):
|
||||
"""Contains information about a simulated message generated by an input
|
||||
device other than a keyboard or mouse.
|
||||
"""
|
||||
_fields_ = [
|
||||
('uMsg', wintypes.DWORD),
|
||||
('wParamL', wintypes.WORD),
|
||||
('wParamH', wintypes.WORD)]
|
||||
|
||||
|
||||
class INPUT_union(ctypes.Union):
|
||||
"""Represents the union of input types in :class:`INPUT`.
|
||||
"""
|
||||
_fields_ = [
|
||||
('mi', MOUSEINPUT),
|
||||
('ki', KEYBDINPUT),
|
||||
('hi', HARDWAREINPUT)]
|
||||
|
||||
|
||||
class INPUT(ctypes.Structure):
|
||||
"""Used by :attr:`SendInput` to store information for synthesizing input
|
||||
events such as keystrokes, mouse movement, and mouse clicks.
|
||||
"""
|
||||
MOUSE = 0
|
||||
KEYBOARD = 1
|
||||
HARDWARE = 2
|
||||
|
||||
_fields_ = [
|
||||
('type', wintypes.DWORD),
|
||||
('value', INPUT_union)]
|
||||
|
||||
|
||||
LPINPUT = ctypes.POINTER(INPUT)
|
||||
|
||||
VkKeyScan = windll.user32.VkKeyScanW
|
||||
VkKeyScan.argtypes = (
|
||||
wintypes.WCHAR,)
|
||||
|
||||
MapVirtualKey = windll.user32.MapVirtualKeyW
|
||||
MapVirtualKey.argtypes = (
|
||||
wintypes.UINT,
|
||||
wintypes.UINT)
|
||||
MapVirtualKey.MAPVK_VK_TO_VSC = 0
|
||||
|
||||
SendInput = windll.user32.SendInput
|
||||
SendInput.argtypes = (
|
||||
wintypes.UINT,
|
||||
ctypes.c_voidp, # Really LPINPUT
|
||||
ctypes.c_int)
|
||||
|
||||
GetCurrentThreadId = windll.kernel32.GetCurrentThreadId
|
||||
GetCurrentThreadId.restype = wintypes.DWORD
|
||||
|
||||
|
||||
class MessageLoop(object):
|
||||
"""A class representing a message loop.
|
||||
"""
|
||||
#: The message that signals this loop to terminate
|
||||
WM_STOP = 0x0401
|
||||
|
||||
_LPMSG = ctypes.POINTER(wintypes.MSG)
|
||||
|
||||
_GetMessage = windll.user32.GetMessageW
|
||||
_GetMessage.argtypes = (
|
||||
ctypes.c_voidp, # Really _LPMSG
|
||||
wintypes.HWND,
|
||||
wintypes.UINT,
|
||||
wintypes.UINT)
|
||||
_PeekMessage = windll.user32.PeekMessageW
|
||||
_PeekMessage.argtypes = (
|
||||
ctypes.c_voidp, # Really _LPMSG
|
||||
wintypes.HWND,
|
||||
wintypes.UINT,
|
||||
wintypes.UINT,
|
||||
wintypes.UINT)
|
||||
_PostThreadMessage = windll.user32.PostThreadMessageW
|
||||
_PostThreadMessage.argtypes = (
|
||||
wintypes.DWORD,
|
||||
wintypes.UINT,
|
||||
wintypes.WPARAM,
|
||||
wintypes.LPARAM)
|
||||
|
||||
PM_NOREMOVE = 0
|
||||
|
||||
def __init__(self):
|
||||
self._threadid = None
|
||||
self._event = threading.Event()
|
||||
self.thread = None
|
||||
|
||||
def __iter__(self):
|
||||
"""Initialises the message loop and yields all messages until
|
||||
:meth:`stop` is called.
|
||||
|
||||
:raises AssertionError: if :meth:`start` has not been called
|
||||
"""
|
||||
assert self._threadid is not None
|
||||
|
||||
try:
|
||||
# Pump messages until WM_STOP
|
||||
while True:
|
||||
msg = wintypes.MSG()
|
||||
lpmsg = ctypes.byref(msg)
|
||||
r = self._GetMessage(lpmsg, None, 0, 0)
|
||||
if r <= 0 or msg.message == self.WM_STOP:
|
||||
break
|
||||
else:
|
||||
yield msg
|
||||
|
||||
finally:
|
||||
self._threadid = None
|
||||
self.thread = None
|
||||
|
||||
def start(self):
|
||||
"""Starts the message loop.
|
||||
|
||||
This method must be called before iterating over messages, and it must
|
||||
be called from the same thread.
|
||||
"""
|
||||
self._threadid = GetCurrentThreadId()
|
||||
self.thread = threading.current_thread()
|
||||
|
||||
# Create the message loop
|
||||
msg = wintypes.MSG()
|
||||
lpmsg = ctypes.byref(msg)
|
||||
self._PeekMessage(lpmsg, None, 0x0400, 0x0400, self.PM_NOREMOVE)
|
||||
|
||||
# Set the event to signal to other threads that the loop is created
|
||||
self._event.set()
|
||||
|
||||
def stop(self):
|
||||
"""Stops the message loop.
|
||||
"""
|
||||
self._event.wait()
|
||||
if self._threadid:
|
||||
self.post(self.WM_STOP, 0, 0)
|
||||
|
||||
def post(self, msg, wparam, lparam):
|
||||
"""Posts a message to this message loop.
|
||||
|
||||
:param ctypes.wintypes.UINT msg: The message.
|
||||
|
||||
:param ctypes.wintypes.WPARAM wparam: The value of ``wParam``.
|
||||
|
||||
:param ctypes.wintypes.LPARAM lparam: The value of ``lParam``.
|
||||
"""
|
||||
self._PostThreadMessage(self._threadid, msg, wparam, lparam)
|
||||
|
||||
|
||||
class SystemHook(object):
|
||||
"""A class to handle Windows hooks.
|
||||
"""
|
||||
#: The hook action value for actions we should check
|
||||
HC_ACTION = 0
|
||||
|
||||
_HOOKPROC = ctypes.WINFUNCTYPE(
|
||||
wintypes.LPARAM,
|
||||
ctypes.c_int32, wintypes.WPARAM, wintypes.LPARAM)
|
||||
|
||||
_SetWindowsHookEx = windll.user32.SetWindowsHookExW
|
||||
_SetWindowsHookEx.argtypes = (
|
||||
ctypes.c_int,
|
||||
_HOOKPROC,
|
||||
wintypes.HINSTANCE,
|
||||
wintypes.DWORD)
|
||||
_UnhookWindowsHookEx = windll.user32.UnhookWindowsHookEx
|
||||
_UnhookWindowsHookEx.argtypes = (
|
||||
wintypes.HHOOK,)
|
||||
_CallNextHookEx = windll.user32.CallNextHookEx
|
||||
_CallNextHookEx.argtypes = (
|
||||
wintypes.HHOOK,
|
||||
ctypes.c_int,
|
||||
wintypes.WPARAM,
|
||||
wintypes.LPARAM)
|
||||
|
||||
#: The registered hook procedures
|
||||
_HOOKS = {}
|
||||
|
||||
class SuppressException(Exception):
|
||||
"""An exception raised by a hook callback to suppress further
|
||||
propagation of events.
|
||||
"""
|
||||
pass
|
||||
|
||||
def __init__(self, hook_id, on_hook=lambda code, msg, lpdata: None):
|
||||
self.hook_id = hook_id
|
||||
self.on_hook = on_hook
|
||||
self._hook = None
|
||||
|
||||
def __enter__(self):
|
||||
key = threading.current_thread().ident
|
||||
assert key not in self._HOOKS
|
||||
|
||||
# Add ourself to lookup table and install the hook
|
||||
self._HOOKS[key] = self
|
||||
self._hook = self._SetWindowsHookEx(
|
||||
self.hook_id,
|
||||
self._handler,
|
||||
None,
|
||||
0)
|
||||
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, value, traceback):
|
||||
key = threading.current_thread().ident
|
||||
assert key in self._HOOKS
|
||||
|
||||
if self._hook is not None:
|
||||
# Uninstall the hook and remove ourself from lookup table
|
||||
self._UnhookWindowsHookEx(self._hook)
|
||||
del self._HOOKS[key]
|
||||
|
||||
@staticmethod
|
||||
@_HOOKPROC
|
||||
def _handler(code, msg, lpdata):
|
||||
key = threading.current_thread().ident
|
||||
self = SystemHook._HOOKS.get(key, None)
|
||||
if self:
|
||||
# pylint: disable=W0702; we want to silence errors
|
||||
try:
|
||||
self.on_hook(code, msg, lpdata)
|
||||
except self.SuppressException:
|
||||
# Return non-zero to stop event propagation
|
||||
return 1
|
||||
except:
|
||||
# Ignore any errors
|
||||
pass
|
||||
# pylint: enable=W0702
|
||||
return SystemHook._CallNextHookEx(0, code, msg, lpdata)
|
||||
|
||||
|
||||
class ListenerMixin(object):
|
||||
"""A mixin for *win32* event listeners.
|
||||
|
||||
Subclasses should set a value for :attr:`_EVENTS` and implement
|
||||
:meth:`_handle_message`.
|
||||
|
||||
Subclasses must also be decorated with a decorator compatible with
|
||||
:meth:`pynput._util.NotifierMixin._receiver` or implement the method
|
||||
``_receive()``.
|
||||
"""
|
||||
#: The Windows hook ID for the events to capture.
|
||||
_EVENTS = None
|
||||
|
||||
#: The window message used to signal that an even should be handled.
|
||||
_WM_PROCESS = 0x410
|
||||
|
||||
#: Additional window messages to propagate to the subclass handler.
|
||||
_WM_NOTIFICATIONS = []
|
||||
|
||||
def suppress_event(self):
|
||||
"""Causes the currently filtered event to be suppressed.
|
||||
|
||||
This has a system wide effect and will generally result in no
|
||||
applications receiving the event.
|
||||
|
||||
This method will raise an undefined exception.
|
||||
"""
|
||||
raise SystemHook.SuppressException()
|
||||
|
||||
def _run(self):
|
||||
self._message_loop = MessageLoop()
|
||||
with self._receive():
|
||||
self._mark_ready()
|
||||
self._message_loop.start()
|
||||
|
||||
# pylint: disable=W0702; we want to silence errors
|
||||
try:
|
||||
with SystemHook(self._EVENTS, self._handler):
|
||||
# Just pump messages
|
||||
for msg in self._message_loop:
|
||||
if not self.running:
|
||||
break
|
||||
if msg.message == self._WM_PROCESS:
|
||||
self._process(msg.wParam, msg.lParam)
|
||||
elif msg.message in self._WM_NOTIFICATIONS:
|
||||
self._on_notification(
|
||||
msg.message, msg.wParam, msg.lParam)
|
||||
except:
|
||||
# This exception will have been passed to the main thread
|
||||
pass
|
||||
# pylint: enable=W0702
|
||||
|
||||
def _stop_platform(self):
|
||||
try:
|
||||
self._message_loop.stop()
|
||||
except AttributeError:
|
||||
# The loop may not have been created
|
||||
pass
|
||||
|
||||
@AbstractListener._emitter
|
||||
def _handler(self, code, msg, lpdata):
|
||||
"""The callback registered with *Windows* for events.
|
||||
|
||||
This method will post the message :attr:`_WM_PROCESS` to the message
|
||||
loop started with this listener using :meth:`MessageLoop.post`. The
|
||||
parameters are retrieved with a call to :meth:`_handle`.
|
||||
"""
|
||||
try:
|
||||
converted = self._convert(code, msg, lpdata)
|
||||
if converted is not None:
|
||||
self._message_loop.post(self._WM_PROCESS, *converted)
|
||||
except NotImplementedError:
|
||||
self._handle_message(code, msg, lpdata)
|
||||
|
||||
if self.suppress:
|
||||
self.suppress_event()
|
||||
|
||||
def _convert(self, code, msg, lpdata):
|
||||
"""The device specific callback handler.
|
||||
|
||||
This method converts a low-level message and data to a
|
||||
``WPARAM`` / ``LPARAM`` pair.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def _process(self, wparam, lparam):
|
||||
"""The device specific callback handler.
|
||||
|
||||
This method performs the actual dispatching of events.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def _handle_message(self, code, msg, lpdata):
|
||||
"""The device specific callback handler.
|
||||
|
||||
This method calls the appropriate callback registered when this
|
||||
listener was created based on the event.
|
||||
|
||||
This method is only called if :meth:`_convert` is not implemented.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def _on_notification(self, code, wparam, lparam):
|
||||
"""An additional notification handler.
|
||||
|
||||
This method will be called for every message in
|
||||
:attr:`_WM_NOTIFICATIONS`.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class KeyTranslator(object):
|
||||
"""A class to translate virtual key codes to characters.
|
||||
"""
|
||||
_GetAsyncKeyState = ctypes.windll.user32.GetAsyncKeyState
|
||||
_GetAsyncKeyState.argtypes = (
|
||||
ctypes.c_int,)
|
||||
_GetKeyboardLayout = ctypes.windll.user32.GetKeyboardLayout
|
||||
_GetKeyboardLayout.argtypes = (
|
||||
wintypes.DWORD,)
|
||||
_GetKeyboardState = ctypes.windll.user32.GetKeyboardState
|
||||
_GetKeyboardState.argtypes = (
|
||||
ctypes.c_voidp,)
|
||||
_GetKeyState = ctypes.windll.user32.GetAsyncKeyState
|
||||
_GetKeyState.argtypes = (
|
||||
ctypes.c_int,)
|
||||
_MapVirtualKeyEx = ctypes.windll.user32.MapVirtualKeyExW
|
||||
_MapVirtualKeyEx.argtypes = (
|
||||
wintypes.UINT,
|
||||
wintypes.UINT,
|
||||
wintypes.HKL)
|
||||
_ToUnicodeEx = ctypes.windll.user32.ToUnicodeEx
|
||||
_ToUnicodeEx.argtypes = (
|
||||
wintypes.UINT,
|
||||
wintypes.UINT,
|
||||
ctypes.c_voidp,
|
||||
ctypes.c_voidp,
|
||||
ctypes.c_int,
|
||||
wintypes.UINT,
|
||||
wintypes.HKL)
|
||||
|
||||
_MAPVK_VK_TO_VSC = 0
|
||||
_MAPVK_VSC_TO_VK = 1
|
||||
_MAPVK_VK_TO_CHAR = 2
|
||||
|
||||
def __init__(self):
|
||||
self.update_layout()
|
||||
|
||||
def __call__(self, vk, is_press):
|
||||
"""Converts a virtual key code to a string.
|
||||
|
||||
:param int vk: The virtual key code.
|
||||
|
||||
:param bool is_press: Whether this is a press.
|
||||
|
||||
:return: parameters suitable for the :class:`pynput.keyboard.KeyCode`
|
||||
constructor
|
||||
|
||||
:raises OSError: if a call to any *win32* function fails
|
||||
"""
|
||||
# Get a string representation of the key
|
||||
layout_data = self._layout_data[self._modifier_state()]
|
||||
scan = self._to_scan(vk, self._layout)
|
||||
character, is_dead = layout_data[scan]
|
||||
|
||||
return {
|
||||
'char': character,
|
||||
'is_dead': is_dead,
|
||||
'vk': vk,
|
||||
'_scan': scan}
|
||||
|
||||
def update_layout(self):
|
||||
"""Updates the cached layout data.
|
||||
"""
|
||||
self._layout, self._layout_data = self._generate_layout()
|
||||
|
||||
def char_from_scan(self, scan):
|
||||
"""Translates a scan code to a character, if possible.
|
||||
|
||||
:param int scan: The scan code to translate.
|
||||
|
||||
:return: maybe a character
|
||||
:rtype: str or None
|
||||
"""
|
||||
return self._layout_data[(False, False, False)][scan][0]
|
||||
|
||||
def _generate_layout(self):
|
||||
"""Generates the keyboard layout.
|
||||
|
||||
This method will call ``ToUnicodeEx``, which modifies kernel buffers,
|
||||
so it must *not* be called from the keyboard hook.
|
||||
|
||||
The return value is the tuple ``(layout_handle, layout_data)``, where
|
||||
``layout_data`` is a mapping from the tuple ``(shift, ctrl, alt)`` to
|
||||
an array indexed by scan code containing the data
|
||||
``(character, is_dead)``, and ``layout_handle`` is the handle of the
|
||||
layout.
|
||||
|
||||
:return: a composite layout
|
||||
"""
|
||||
layout_data = {}
|
||||
|
||||
state = (ctypes.c_ubyte * 255)()
|
||||
with self._thread_input() as active_thread:
|
||||
layout = self._GetKeyboardLayout(active_thread)
|
||||
vks = [
|
||||
self._to_vk(scan, layout)
|
||||
for scan in range(len(state))]
|
||||
|
||||
for shift, ctrl, alt in itertools.product(
|
||||
(False, True), (False, True), (False, True)):
|
||||
current = [(None, False)] * len(state)
|
||||
layout_data[(shift, ctrl, alt)] = current
|
||||
|
||||
# Update the keyboard state based on the modifier state
|
||||
state[VK.SHIFT] = 0x80 if shift else 0x00
|
||||
state[VK.CONTROL] = 0x80 if ctrl else 0x00
|
||||
state[VK.MENU] = 0x80 if alt else 0x00
|
||||
|
||||
# For each virtual key code...
|
||||
out = (ctypes.wintypes.WCHAR * 5)()
|
||||
for (scan, vk) in enumerate(vks):
|
||||
# ...translate it to a unicode character
|
||||
count = self._ToUnicodeEx(
|
||||
vk, scan, ctypes.byref(state), ctypes.byref(out),
|
||||
len(out), 0, layout)
|
||||
|
||||
# Cache the result if a key is mapped
|
||||
if count != 0:
|
||||
character = out[0]
|
||||
is_dead = count < 0
|
||||
current[scan] = (character, is_dead)
|
||||
|
||||
# If the key is dead, flush the keyboard state
|
||||
if is_dead:
|
||||
self._ToUnicodeEx(
|
||||
vk, scan, ctypes.byref(state),
|
||||
ctypes.byref(out), len(out), 0, layout)
|
||||
|
||||
return (layout, layout_data)
|
||||
|
||||
def _to_scan(self, vk, layout):
|
||||
"""Retrieves the scan code for a virtual key code.
|
||||
|
||||
:param int vk: The virtual key code.
|
||||
|
||||
:param layout: The keyboard layout.
|
||||
|
||||
:return: the scan code
|
||||
"""
|
||||
return self._MapVirtualKeyEx(
|
||||
vk, self._MAPVK_VK_TO_VSC, layout)
|
||||
|
||||
def _to_vk(self, scan, layout):
|
||||
"""Retrieves the virtual key code for a scan code.
|
||||
|
||||
:param int vscan: The scan code.
|
||||
|
||||
:param layout: The keyboard layout.
|
||||
|
||||
:return: the virtual key code
|
||||
"""
|
||||
return self._MapVirtualKeyEx(
|
||||
scan, self._MAPVK_VSC_TO_VK, layout)
|
||||
|
||||
def _modifier_state(self):
|
||||
"""Returns a key into :attr:`_layout_data` for the current modifier
|
||||
state.
|
||||
|
||||
:return: the current modifier state
|
||||
"""
|
||||
shift = bool(self._GetAsyncKeyState(VK.SHIFT) & 0x8000)
|
||||
ctrl = bool(self._GetAsyncKeyState(VK.CONTROL) & 0x8000)
|
||||
alt = bool(self._GetAsyncKeyState(VK.MENU) & 0x8000)
|
||||
return (shift, ctrl, alt)
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _thread_input(self):
|
||||
"""Yields the current thread ID.
|
||||
"""
|
||||
yield GetCurrentThreadId()
|
||||
179
myenv/lib/python3.10/site-packages/pynput/_util/win32_vks.py
Normal file
179
myenv/lib/python3.10/site-packages/pynput/_util/win32_vks.py
Normal file
@@ -0,0 +1,179 @@
|
||||
# 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/>.
|
||||
|
||||
# pylint: disable=C0111,C0302
|
||||
|
||||
LBUTTON = 1
|
||||
RBUTTON = 2
|
||||
CANCEL = 3
|
||||
MBUTTON = 4
|
||||
XBUTTON1 = 5
|
||||
XBUTTON2 = 6
|
||||
BACK = 8
|
||||
TAB = 9
|
||||
CLEAR = 12
|
||||
RETURN = 13
|
||||
SHIFT = 16
|
||||
CONTROL = 17
|
||||
MENU = 18
|
||||
PAUSE = 19
|
||||
CAPITAL = 20
|
||||
KANA = 21
|
||||
HANGEUL = 21
|
||||
HANGUL = 21
|
||||
JUNJA = 23
|
||||
FINAL = 24
|
||||
HANJA = 25
|
||||
KANJI = 25
|
||||
ESCAPE = 27
|
||||
CONVERT = 28
|
||||
NONCONVERT = 29
|
||||
ACCEPT = 30
|
||||
MODECHANGE = 31
|
||||
SPACE = 32
|
||||
PRIOR = 33
|
||||
NEXT = 34
|
||||
END = 35
|
||||
HOME = 36
|
||||
LEFT = 37
|
||||
UP = 38
|
||||
RIGHT = 39
|
||||
DOWN = 40
|
||||
SELECT = 41
|
||||
PRINT = 42
|
||||
EXECUTE = 43
|
||||
SNAPSHOT = 44
|
||||
INSERT = 45
|
||||
DELETE = 46
|
||||
HELP = 47
|
||||
LWIN = 91
|
||||
RWIN = 92
|
||||
APPS = 93
|
||||
SLEEP = 95
|
||||
NUMPAD0 = 96
|
||||
NUMPAD1 = 97
|
||||
NUMPAD2 = 98
|
||||
NUMPAD3 = 99
|
||||
NUMPAD4 = 100
|
||||
NUMPAD5 = 101
|
||||
NUMPAD6 = 102
|
||||
NUMPAD7 = 103
|
||||
NUMPAD8 = 104
|
||||
NUMPAD9 = 105
|
||||
MULTIPLY = 106
|
||||
ADD = 107
|
||||
SEPARATOR = 108
|
||||
SUBTRACT = 109
|
||||
DECIMAL = 110
|
||||
DIVIDE = 111
|
||||
F1 = 112
|
||||
F2 = 113
|
||||
F3 = 114
|
||||
F4 = 115
|
||||
F5 = 116
|
||||
F6 = 117
|
||||
F7 = 118
|
||||
F8 = 119
|
||||
F9 = 120
|
||||
F10 = 121
|
||||
F11 = 122
|
||||
F12 = 123
|
||||
F13 = 124
|
||||
F14 = 125
|
||||
F15 = 126
|
||||
F16 = 127
|
||||
F17 = 128
|
||||
F18 = 129
|
||||
F19 = 130
|
||||
F20 = 131
|
||||
F21 = 132
|
||||
F22 = 133
|
||||
F23 = 134
|
||||
F24 = 135
|
||||
NUMLOCK = 144
|
||||
SCROLL = 145
|
||||
OEM_NEC_EQUAL = 146
|
||||
OEM_FJ_JISHO = 146
|
||||
OEM_FJ_MASSHOU = 147
|
||||
OEM_FJ_TOUROKU = 148
|
||||
OEM_FJ_LOYA = 149
|
||||
OEM_FJ_ROYA = 150
|
||||
LSHIFT = 160
|
||||
RSHIFT = 161
|
||||
LCONTROL = 162
|
||||
RCONTROL = 163
|
||||
LMENU = 164
|
||||
RMENU = 165
|
||||
BROWSER_BACK = 166
|
||||
BROWSER_FORWARD = 167
|
||||
BROWSER_REFRESH = 168
|
||||
BROWSER_STOP = 169
|
||||
BROWSER_SEARCH = 170
|
||||
BROWSER_FAVORITES = 171
|
||||
BROWSER_HOME = 172
|
||||
VOLUME_MUTE = 173
|
||||
VOLUME_DOWN = 174
|
||||
VOLUME_UP = 175
|
||||
MEDIA_NEXT_TRACK = 176
|
||||
MEDIA_PREV_TRACK = 177
|
||||
MEDIA_STOP = 178
|
||||
MEDIA_PLAY_PAUSE = 179
|
||||
LAUNCH_MAIL = 180
|
||||
LAUNCH_MEDIA_SELECT = 181
|
||||
LAUNCH_APP1 = 182
|
||||
LAUNCH_APP2 = 183
|
||||
OEM_1 = 186
|
||||
OEM_PLUS = 187
|
||||
OEM_COMMA = 188
|
||||
OEM_MINUS = 189
|
||||
OEM_PERIOD = 190
|
||||
OEM_2 = 191
|
||||
OEM_3 = 192
|
||||
OEM_4 = 219
|
||||
OEM_5 = 220
|
||||
OEM_6 = 221
|
||||
OEM_7 = 222
|
||||
OEM_8 = 223
|
||||
OEM_AX = 225
|
||||
OEM_102 = 226
|
||||
ICO_HELP = 227
|
||||
ICO_00 = 228
|
||||
PROCESSKEY = 229
|
||||
ICO_CLEAR = 230
|
||||
PACKET = 231
|
||||
OEM_RESET = 233
|
||||
OEM_JUMP = 234
|
||||
OEM_PA1 = 235
|
||||
OEM_PA2 = 236
|
||||
OEM_PA3 = 237
|
||||
OEM_WSCTRL = 238
|
||||
OEM_CUSEL = 239
|
||||
OEM_ATTN = 240
|
||||
OEM_FINISH = 241
|
||||
OEM_COPY = 242
|
||||
OEM_AUTO = 243
|
||||
OEM_ENLW = 244
|
||||
OEM_BACKTAB = 245
|
||||
ATTN = 246
|
||||
CRSEL = 247
|
||||
EXSEL = 248
|
||||
EREOF = 249
|
||||
PLAY = 250
|
||||
ZOOM = 251
|
||||
NONAME = 252
|
||||
PA1 = 253
|
||||
OEM_CLEAR = 254
|
||||
496
myenv/lib/python3.10/site-packages/pynput/_util/xorg.py
Normal file
496
myenv/lib/python3.10/site-packages/pynput/_util/xorg.py
Normal file
@@ -0,0 +1,496 @@
|
||||
# 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/>.
|
||||
"""
|
||||
Utility functions and classes for the *Xorg* backend.
|
||||
"""
|
||||
|
||||
# pylint: disable=R0903
|
||||
# We implement stubs
|
||||
|
||||
import contextlib
|
||||
import functools
|
||||
import itertools
|
||||
import operator
|
||||
import Xlib.display
|
||||
import Xlib.keysymdef
|
||||
import Xlib.threaded
|
||||
import Xlib.XK
|
||||
|
||||
from . import AbstractListener
|
||||
from .xorg_keysyms import SYMBOLS
|
||||
|
||||
|
||||
# Create a display to verify that we have an X connection
|
||||
def _check_and_initialize():
|
||||
display = Xlib.display.Display()
|
||||
display.close()
|
||||
|
||||
for group in Xlib.keysymdef.__all__:
|
||||
Xlib.XK.load_keysym_group(group)
|
||||
_check_and_initialize()
|
||||
del _check_and_initialize
|
||||
|
||||
|
||||
class X11Error(Exception):
|
||||
"""An error that is thrown at the end of a code block managed by a
|
||||
:func:`display_manager` if an *X11* error occurred.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def display_manager(display):
|
||||
"""Traps *X* errors and raises an :class:``X11Error`` at the end if any
|
||||
error occurred.
|
||||
|
||||
This handler also ensures that the :class:`Xlib.display.Display` being
|
||||
managed is sync'd.
|
||||
|
||||
:param Xlib.display.Display display: The *X* display.
|
||||
|
||||
:return: the display
|
||||
:rtype: Xlib.display.Display
|
||||
"""
|
||||
errors = []
|
||||
|
||||
def handler(*args):
|
||||
"""The *Xlib* error handler.
|
||||
"""
|
||||
errors.append(args)
|
||||
|
||||
old_handler = display.set_error_handler(handler)
|
||||
try:
|
||||
yield display
|
||||
display.sync()
|
||||
finally:
|
||||
display.set_error_handler(old_handler)
|
||||
if errors:
|
||||
raise X11Error(errors)
|
||||
|
||||
|
||||
def _find_mask(display, symbol):
|
||||
"""Returns the mode flags to use for a modifier symbol.
|
||||
|
||||
:param Xlib.display.Display display: The *X* display.
|
||||
|
||||
:param str symbol: The name of the symbol.
|
||||
|
||||
:return: the modifier mask
|
||||
"""
|
||||
# Get the key code for the symbol
|
||||
modifier_keycode = display.keysym_to_keycode(
|
||||
Xlib.XK.string_to_keysym(symbol))
|
||||
|
||||
for index, keycodes in enumerate(display.get_modifier_mapping()):
|
||||
for keycode in keycodes:
|
||||
if keycode == modifier_keycode:
|
||||
return 1 << index
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
def alt_mask(display):
|
||||
"""Returns the *alt* mask flags.
|
||||
|
||||
The first time this function is called for a display, the value is cached.
|
||||
Subsequent calls will return the cached value.
|
||||
|
||||
:param Xlib.display.Display display: The *X* display.
|
||||
|
||||
:return: the modifier mask
|
||||
"""
|
||||
if not hasattr(display, '__alt_mask'):
|
||||
display.__alt_mask = _find_mask(display, 'Alt_L')
|
||||
return display.__alt_mask
|
||||
|
||||
|
||||
def alt_gr_mask(display):
|
||||
"""Returns the *alt* mask flags.
|
||||
|
||||
The first time this function is called for a display, the value is cached.
|
||||
Subsequent calls will return the cached value.
|
||||
|
||||
:param Xlib.display.Display display: The *X* display.
|
||||
|
||||
:return: the modifier mask
|
||||
"""
|
||||
if not hasattr(display, '__altgr_mask'):
|
||||
display.__altgr_mask = _find_mask(display, 'Mode_switch')
|
||||
return display.__altgr_mask
|
||||
|
||||
|
||||
def numlock_mask(display):
|
||||
"""Returns the *numlock* mask flags.
|
||||
|
||||
The first time this function is called for a display, the value is cached.
|
||||
Subsequent calls will return the cached value.
|
||||
|
||||
:param Xlib.display.Display display: The *X* display.
|
||||
|
||||
:return: the modifier mask
|
||||
"""
|
||||
if not hasattr(display, '__numlock_mask'):
|
||||
display.__numlock_mask = _find_mask(display, 'Num_Lock')
|
||||
return display.__numlock_mask
|
||||
|
||||
|
||||
def keysym_is_latin_upper(keysym):
|
||||
"""Determines whether a *keysym* is an upper case *latin* character.
|
||||
|
||||
This is true only if ``XK_A`` <= ``keysym`` <= ` XK_Z``.
|
||||
|
||||
:param in keysym: The *keysym* to check.
|
||||
"""
|
||||
return Xlib.XK.XK_A <= keysym <= Xlib.XK.XK_Z
|
||||
|
||||
|
||||
def keysym_is_latin_lower(keysym):
|
||||
"""Determines whether a *keysym* is a lower case *latin* character.
|
||||
|
||||
This is true only if ``XK_a`` <= ``keysym`` <= ` XK_z``.
|
||||
|
||||
:param in keysym: The *keysym* to check.
|
||||
"""
|
||||
return Xlib.XK.XK_a <= keysym <= Xlib.XK.XK_z
|
||||
|
||||
|
||||
def keysym_group(ks1, ks2):
|
||||
"""Generates a group from two *keysyms*.
|
||||
|
||||
The implementation of this function comes from:
|
||||
|
||||
Within each group, if the second element of the group is ``NoSymbol``,
|
||||
then the group should be treated as if the second element were the same
|
||||
as the first element, except when the first element is an alphabetic
|
||||
*KeySym* ``K`` for which both lowercase and uppercase forms are
|
||||
defined.
|
||||
|
||||
In that case, the group should be treated as if the first element were
|
||||
the lowercase form of ``K`` and the second element were the uppercase
|
||||
form of ``K``.
|
||||
|
||||
This function assumes that *alphabetic* means *latin*; this assumption
|
||||
appears to be consistent with observations of the return values from
|
||||
``XGetKeyboardMapping``.
|
||||
|
||||
:param ks1: The first *keysym*.
|
||||
|
||||
:param ks2: The second *keysym*.
|
||||
|
||||
:return: a tuple conforming to the description above
|
||||
"""
|
||||
if ks2 == Xlib.XK.NoSymbol:
|
||||
if keysym_is_latin_upper(ks1):
|
||||
return (Xlib.XK.XK_a + ks1 - Xlib.XK.XK_A, ks1)
|
||||
elif keysym_is_latin_lower(ks1):
|
||||
return (ks1, Xlib.XK.XK_A + ks1 - Xlib.XK.XK_a)
|
||||
else:
|
||||
return (ks1, ks1)
|
||||
else:
|
||||
return (ks1, ks2)
|
||||
|
||||
|
||||
def keysym_normalize(keysym):
|
||||
"""Normalises a list of *keysyms*.
|
||||
|
||||
The implementation of this function comes from:
|
||||
|
||||
If the list (ignoring trailing ``NoSymbol`` entries) is a single
|
||||
*KeySym* ``K``, then the list is treated as if it were the list
|
||||
``K NoSymbol K NoSymbol``.
|
||||
|
||||
If the list (ignoring trailing ``NoSymbol`` entries) is a pair of
|
||||
*KeySyms* ``K1 K2``, then the list is treated as if it were the list
|
||||
``K1 K2 K1 K2``.
|
||||
|
||||
If the list (ignoring trailing ``NoSymbol`` entries) is a triple of
|
||||
*KeySyms* ``K1 K2 K3``, then the list is treated as if it were the list
|
||||
``K1 K2 K3 NoSymbol``.
|
||||
|
||||
This function will also group the *keysyms* using :func:`keysym_group`.
|
||||
|
||||
:param keysyms: A list of keysyms.
|
||||
|
||||
:return: the tuple ``(group_1, group_2)`` or ``None``
|
||||
"""
|
||||
# Remove trailing NoSymbol
|
||||
stripped = list(reversed(list(
|
||||
itertools.dropwhile(
|
||||
lambda n: n == Xlib.XK.NoSymbol,
|
||||
reversed(keysym)))))
|
||||
|
||||
if not stripped:
|
||||
return
|
||||
|
||||
elif len(stripped) == 1:
|
||||
return (
|
||||
keysym_group(stripped[0], Xlib.XK.NoSymbol),
|
||||
keysym_group(stripped[0], Xlib.XK.NoSymbol))
|
||||
|
||||
elif len(stripped) == 2:
|
||||
return (
|
||||
keysym_group(stripped[0], stripped[1]),
|
||||
keysym_group(stripped[0], stripped[1]))
|
||||
|
||||
elif len(stripped) == 3:
|
||||
return (
|
||||
keysym_group(stripped[0], stripped[1]),
|
||||
keysym_group(stripped[2], Xlib.XK.NoSymbol))
|
||||
|
||||
elif len(stripped) >= 6:
|
||||
# TODO: Find out why this is necessary; using only the documented
|
||||
# behaviour may lead to only a US layout being used?
|
||||
return (
|
||||
keysym_group(stripped[0], stripped[1]),
|
||||
keysym_group(stripped[4], stripped[5]))
|
||||
|
||||
else:
|
||||
return (
|
||||
keysym_group(stripped[0], stripped[1]),
|
||||
keysym_group(stripped[2], stripped[3]))
|
||||
|
||||
|
||||
def index_to_shift(display, index):
|
||||
"""Converts an index in a *key code* list to the corresponding shift state.
|
||||
|
||||
:param Xlib.display.Display display: The display for which to retrieve the
|
||||
shift mask.
|
||||
|
||||
:param int index: The keyboard mapping *key code* index.
|
||||
|
||||
:return: a shift mask
|
||||
"""
|
||||
return (
|
||||
(1 << 0 if index & 1 else 0) |
|
||||
(alt_gr_mask(display) if index & 2 else 0))
|
||||
|
||||
|
||||
def shift_to_index(display, shift):
|
||||
"""Converts an index in a *key code* list to the corresponding shift state.
|
||||
|
||||
:param Xlib.display.Display display: The display for which to retrieve the
|
||||
shift mask.
|
||||
|
||||
:param int index: The keyboard mapping *key code* index.
|
||||
|
||||
:return: a shift mask
|
||||
"""
|
||||
return (
|
||||
(1 if shift & 1 else 0) +
|
||||
(2 if shift & alt_gr_mask(display) else 0))
|
||||
|
||||
|
||||
def keyboard_mapping(display):
|
||||
"""Generates a mapping from *keysyms* to *key codes* and required
|
||||
modifier shift states.
|
||||
|
||||
:param Xlib.display.Display display: The display for which to retrieve the
|
||||
keyboard mapping.
|
||||
|
||||
:return: the keyboard mapping
|
||||
"""
|
||||
mapping = {}
|
||||
|
||||
shift_mask = 1 << 0
|
||||
group_mask = alt_gr_mask(display)
|
||||
|
||||
# Iterate over all keysym lists in the keyboard mapping
|
||||
min_keycode = display.display.info.min_keycode
|
||||
keycode_count = display.display.info.max_keycode - min_keycode + 1
|
||||
for index, keysyms in enumerate(display.get_keyboard_mapping(
|
||||
min_keycode, keycode_count)):
|
||||
key_code = index + min_keycode
|
||||
|
||||
# Normalise the keysym list to yield a tuple containing the two groups
|
||||
normalized = keysym_normalize(keysyms)
|
||||
if not normalized:
|
||||
continue
|
||||
|
||||
# Iterate over the groups to extract the shift and modifier state
|
||||
for groups, group in zip(normalized, (False, True)):
|
||||
for keysym, shift in zip(groups, (False, True)):
|
||||
if not keysym:
|
||||
continue
|
||||
shift_state = 0 \
|
||||
| (shift_mask if shift else 0) \
|
||||
| (group_mask if group else 0)
|
||||
|
||||
# Prefer already known lesser shift states
|
||||
if keysym in mapping and mapping[keysym][1] < shift_state:
|
||||
continue
|
||||
mapping[keysym] = (key_code, shift_state)
|
||||
|
||||
return mapping
|
||||
|
||||
|
||||
def char_to_keysym(char):
|
||||
"""Converts a unicode character to a *keysym*.
|
||||
|
||||
:param str char: The unicode character.
|
||||
|
||||
:return: the corresponding *keysym*, or ``0`` if it cannot be found
|
||||
"""
|
||||
ordinal = ord(char)
|
||||
if ordinal < 0x100:
|
||||
return ordinal
|
||||
else:
|
||||
return ordinal | 0x01000000
|
||||
|
||||
|
||||
def symbol_to_keysym(symbol):
|
||||
"""Converts a symbol name to a *keysym*.
|
||||
|
||||
:param str symbol: The name of the symbol.
|
||||
|
||||
:return: the corresponding *keysym*, or ``0`` if it cannot be found
|
||||
"""
|
||||
# First try simple translation, the try a module attribute of
|
||||
# Xlib.keysymdef.xkb and fall back on our pre-generated table
|
||||
return (0
|
||||
or Xlib.XK.string_to_keysym(symbol)
|
||||
or getattr(Xlib.keysymdef.xkb, "XK_" + symbol, 0)
|
||||
or SYMBOLS.get(symbol, (0,))[0])
|
||||
|
||||
|
||||
class ListenerMixin(object):
|
||||
"""A mixin for *X* event listeners.
|
||||
|
||||
Subclasses should set a value for :attr:`_EVENTS` and implement
|
||||
:meth:`_handle_message`.
|
||||
"""
|
||||
#: The events for which to listen
|
||||
_EVENTS = tuple()
|
||||
|
||||
#: We use this instance for parsing the binary data
|
||||
_EVENT_PARSER = Xlib.protocol.rq.EventField(None)
|
||||
|
||||
def _run(self):
|
||||
self._display_stop = Xlib.display.Display()
|
||||
self._display_record = Xlib.display.Display()
|
||||
self._stopped = False
|
||||
with display_manager(self._display_record) as dm:
|
||||
self._context = dm.record_create_context(
|
||||
0,
|
||||
[Xlib.ext.record.AllClients],
|
||||
[{
|
||||
'core_requests': (0, 0),
|
||||
'core_replies': (0, 0),
|
||||
'ext_requests': (0, 0, 0, 0),
|
||||
'ext_replies': (0, 0, 0, 0),
|
||||
'delivered_events': (0, 0),
|
||||
'device_events': self._EVENTS,
|
||||
'errors': (0, 0),
|
||||
'client_started': False,
|
||||
'client_died': False}])
|
||||
|
||||
# pylint: disable=W0702; we want to silence errors
|
||||
try:
|
||||
self._initialize(self._display_stop)
|
||||
self._mark_ready()
|
||||
if self.suppress:
|
||||
with display_manager(self._display_stop) as dm:
|
||||
self._suppress_start(dm)
|
||||
self._display_record.record_enable_context(
|
||||
self._context, self._handler)
|
||||
except:
|
||||
# This exception will have been passed to the main thread
|
||||
pass
|
||||
finally:
|
||||
if self.suppress:
|
||||
with display_manager(self._display_stop) as dm:
|
||||
self._suppress_stop(dm)
|
||||
self._display_stop.record_disable_context(self._context)
|
||||
self._display_stop.flush()
|
||||
self._display_record.record_free_context(self._context)
|
||||
self._display_stop.close()
|
||||
self._display_record.close()
|
||||
# pylint: enable=W0702
|
||||
|
||||
def _stop_platform(self):
|
||||
if not hasattr(self, '_context'):
|
||||
self.wait()
|
||||
|
||||
# Do this asynchronously to avoid deadlocks
|
||||
self._display_record.record_disable_context(self._context)
|
||||
|
||||
def _suppress_start(self, display):
|
||||
"""Starts suppressing events.
|
||||
|
||||
:param Xlib.display.Display display: The display for which to suppress
|
||||
events.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
def _suppress_stop(self, display):
|
||||
"""Starts suppressing events.
|
||||
|
||||
:param Xlib.display.Display display: The display for which to suppress
|
||||
events.
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
@property
|
||||
def _event_mask(self):
|
||||
"""The event mask.
|
||||
"""
|
||||
return functools.reduce(operator.__or__, self._EVENTS, 0)
|
||||
|
||||
@AbstractListener._emitter
|
||||
def _handler(self, events):
|
||||
"""The callback registered with *X* for mouse events.
|
||||
|
||||
This method will parse the response and call the callbacks registered
|
||||
on initialisation.
|
||||
|
||||
:param events: The events passed by *X*. This is a binary block
|
||||
parsable by :attr:`_EVENT_PARSER`.
|
||||
"""
|
||||
if not self.running:
|
||||
raise self.StopException()
|
||||
|
||||
data = events.data
|
||||
|
||||
while data and len(data):
|
||||
event, data = self._EVENT_PARSER.parse_binary_value(
|
||||
data, self._display_record.display, None, None)
|
||||
|
||||
injected = event.send_event
|
||||
self._handle_message(self._display_stop, event, injected)
|
||||
|
||||
def _initialize(self, display):
|
||||
"""Initialises this listener.
|
||||
|
||||
This method is called immediately before the event loop, from the
|
||||
handler thread.
|
||||
|
||||
:param display: The display being used.
|
||||
"""
|
||||
pass
|
||||
|
||||
def _handle_message(self, display, event, injected):
|
||||
"""The device specific callback handler.
|
||||
|
||||
This method calls the appropriate callback registered when this
|
||||
listener was created based on the event.
|
||||
|
||||
:param display: The display being used.
|
||||
|
||||
:param event: The event.
|
||||
|
||||
:param bool injected: Whether the event was injected.
|
||||
"""
|
||||
pass
|
||||
1715
myenv/lib/python3.10/site-packages/pynput/_util/xorg_keysyms.py
Normal file
1715
myenv/lib/python3.10/site-packages/pynput/_util/xorg_keysyms.py
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user