pax_global_header 0000666 0000000 0000000 00000000064 14164131047 0014513 g ustar 00root root 0000000 0000000 52 comment=57504699b4b9a889bf6e15a0c0b9ed654a5677e1
pynput-1.7.6/ 0000775 0000000 0000000 00000000000 14164131047 0013065 5 ustar 00root root 0000000 0000000 pynput-1.7.6/.github/ 0000775 0000000 0000000 00000000000 14164131047 0014425 5 ustar 00root root 0000000 0000000 pynput-1.7.6/.github/ISSUE_TEMPLATE/ 0000775 0000000 0000000 00000000000 14164131047 0016610 5 ustar 00root root 0000000 0000000 pynput-1.7.6/.github/ISSUE_TEMPLATE/bug_report.md 0000664 0000000 0000000 00000001031 14164131047 0021275 0 ustar 00root root 0000000 0000000 ---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Description**
A clear and concise description of what the bug is.
**Platform and pynput version**
Your operating system and version, and the version of *pynput*.
**To Reproduce**
If possible, please include a short standalone code sample that reproduces the bug. Remember to surround it with [code block markers](https://docs.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks) to maintain indentation!
pynput-1.7.6/.gitignore 0000664 0000000 0000000 00000000111 14164131047 0015046 0 ustar 00root root 0000000 0000000 *.egg
*.egg-info/
*.eggs/
*.pyc
*.sublime-*
*.swo
*.swp
build/*
dist/*
pynput-1.7.6/CHANGES.rst 0000664 0000000 0000000 00000036242 14164131047 0014676 0 ustar 00root root 0000000 0000000 Release Notes
=============
v1.7.6 (2022-01-01) - Various fixes
-----------------------------------
* Allow passing virtual key codes to the parser for global hot keys.
* Stop the recording context asynchronously on *Xorg*.
* Do not pass ``None`` to ``objc.objc_object``. Thanks to *yejunxi*!
* Do not crash when pressing the *alt* key on *uinput*. Thanks to *Caldas
Lopes*!
* Use the correct option prefix for listeners derived from the backend
implementations. Thanks to *Yu Wang*!
v1.7.5 (2021-11-19) - Various fixes
-----------------------------------
* Corrected crashes on *Xorg* when a listener was configured to suppress
system events. Thanks to *jpramosi*!
* Improved handling of keyboard controller on *Windows*. The controller now
has a greater change of working with applications using lower level events.
Thanks to *bhudax*!
* Updated *macOS* implementation to use new version of *pyobjc*.
v1.7.4 (2021-10-10) - Various fixes
-----------------------------------
* Detect whether permissions are lacking on *macOS*. Thanks to *Dane Finlay*!
* Eagerly import symbols from ``CoreFoundation`` and ``Quartz``. Thanks to
*Ronald Oussoren*!
* Improved handling of ``dumpkeys`` utility. Thanks to *Markus Niedermann*!
* Removed ambiguous license file.
v1.7.3 (2021-02-10) - Various fixes
-----------------------------------
* Corrected *keysym* handling on *Xorg*; not all groups were loaded, and the
fallback to our internal tables was never triggered. Thanks to *Philipp
Klaus*!
* Updated the version of *Quartz* used for the *macOS* backend to allow
*pynput* to be installed on *Big Sur*. Thanks to *Michael Madden*!
* Added missing function keys on *Windows*. Thanks to *Dave Atkinson*!
* Corrected scroll speed for mouse controller on *macOS*. Thanks to *Albert
Zeyer*!
* Corrected media keys for *Xorg*. Thanks to *Gabriele N. Tornetta*!
* Corrected parameter name in documentation. Thanks to *Jinesi Yelizati*!
v1.7.2 (2020-12-21) - Corrected uinput key mapping
--------------------------------------------------
* Corrected mapping of virtual key codes to characters for the *uinput*
backend.
* Corrected spelling errors. Thanks to *Martin Michlmayr*!
* Corrected and improved documentation.
v1.7.1 (2020-08-30) - Corrected release notes
---------------------------------------------
* Corrected thanks for arbitrary unicode character support for *Xorg*.
v1.7.0 (2020-08-30) - A new backend and many new features and bug fixes
-----------------------------------------------------------------------
* Added a new *uinput* based keyboard backend for *Linux*, when no *X* server
is available.
* Allow typing arbitrary unicode characters on *Xorg* backend. Thanks to
*gdiShun*!
* Allow overriding the automatically selected backend with an environment
variable, and added a dummy backend.
* Added support for mouse side button on *Windows*. Thanks to *danielkovarik*!
* Added convenience method to tap keys.
* Allow specifying raw virtual key codes in hotkeys.
* Improved error messages when a backend cannot be loaded.
* Include more information in stringification of events.
* Corrected return value of ``Events.get`` to that specified by the
documentation.
* Corrected keyboard listener not to type random characters on certain
keyboard layouts.
* Corrected errors when pressing certain keys on *Windows*, where the
operating system reports that they are dead but no combining version exists.
* Improved documentation.
v1.6.8 (2020-02-28) - Various fixes
-----------------------------------
* Updated documentation.
* Corrected lint warnings and tests.
* Do not use internal types in ``argtypes`` for ``win32`` functions; this
renders them uncallable for other code running in the same runtime.
* Include scan codes in events on *Windows*. Thanks to *bhudax*!
* Correctly apply transformation to scroll event values on *Windows*. Thanks
to *DOCCA0*!
v1.6.7 (2020-02-17) - Various fixes
-----------------------------------
* Corrected infinite scrolling on *macOS* when providing non-integer deltas.
Thanks to *Iván Munsuri Ibáñez*!
* Corrected controller and listener handling of media keys on *macOS*. Thanks
to *Iván Munsuri Ibáñez*!
v1.6.6 (2020-01-23) - Corrected hot key documentation
-----------------------------------------------------
* The code examples for the simple ``pynput.keyboard.HotKey`` now work. Thanks
to *jfongattw*!
v1.6.5 (2020-01-08) - Corrected media key mappings
--------------------------------------------------
* Corrected media key mappings on *macOS*. Thanks to *Luis Nachtigall*!
v1.6.4 (2020-01-03) - Corrected imports yet again
-------------------------------------------------
* Corrected imports for keyboard Controller. Thanks to *rhystedstone*!
v1.6.3 (2019-12-28) - Corrected imports again
---------------------------------------------
* Corrected imports for keyboard Controller. Thanks to *Matt Iversen*!
v1.6.2 (2019-12-28) - Corrected imports
---------------------------------------
* Corrected imports for keyboard Controller. Thanks to *Matt Iversen*!
v1.6.1 (2019-12-27) - Corrections for *Windows*
-----------------------------------------------
* Corrected global hotkeys on *Windows*.
* Corrected pressed / released state for keyboard listener on *Windows*.
Thanks to *segalion*!
v1.6.0 (2019-12-11) - Global Hotkeys
------------------------------------
* Added support for global hotkeys.
* Added support for streaming listener events synchronously.
v1.5.2 (2019-12-06) - Corrected media key names for *Xorg*
----------------------------------------------------------
* Removed media flag from *Xorg* keys.
v1.5.1 (2019-12-06) - Corrected media key names for *macOS*
-----------------------------------------------------------
* Corrected attribute names for media keys on *macOS*. Thanks to *ah3243*!
v1.5.0 (2019-12-04) - Various improvements
------------------------------------------
* Corrected keyboard listener on *Windows*. Thanks to *akiratakasaki*,
*segalion*, *SpecialCharacter*!
* Corrected handling of some special keys, including arrow keys, when combined
with modifiers on *Windows*. Thanks to *tuessetr*!
* Updated documentation to include information about DPI scaling on *Windows*.
Thanks to *david-szarka*!
* Added experimental support for media keys. Thanks to *ShivamJoker*,
*StormTersteeg*!
v1.4.5 (2019-11-05) - Corrected errors on *Python 3.8*
------------------------------------------------------
* Corrected errors about using `in` operator for enums on *Python 3.8* on
*macOS*.
v1.4.4 (2019-09-24) - Actually corrected keyboard listener on macOS
-------------------------------------------------------------------
* Included commit to correctly fall back on
``CGEventKeyboardGetUnicodeString``.
* Corrected deprecation warnings about ``Enum`` usage on *Python 3.8*.
v1.4.3 (2019-09-24) - Corrected keyboard listener on macOS again
----------------------------------------------------------------
* Correctly fall back on ``CGEventKeyboardGetUnicodeString``.
* Updated documentation.
v1.4.2 (2019-03-22) - Corrected keyboard listener on macOS
----------------------------------------------------------
* Use ``CGEventKeyboardGetUnicodeString`` in *macOS* keyboard listener to send
correct characters.
* Include keysym instead of key code in *Xorg* keyboard listener.
* Corrected logging to not include expected ``StopException``.
* Updated and corrected documentation.
v1.4.1 (2018-09-07) - Logging
-----------------------------
* Log unhandled exceptions raised by listener callbacks.
v1.4 (2018-07-03) - Event suppression
-------------------------------------
* Added possibility to fully suppress events when listening.
* Added support for typing some control characters.
* Added support for mouse drag events on *OSX*. Thanks to *jungledrum*!
* Include the key code in keyboard listener events.
* Correctly handle the numeric key pad on *Xorg* with *num lock* active.
Thanks to *TheoRet*!
* Corrected handling of current thread keyboard layout on *Windows*. Thanks to
*Schmettaling*!
* Corrected stopping of listeners on *Xorg*.
* Corrected import of ``Xlib.keysymdef.xkb`` on *Xorg*. Thanks to *Glandos*!
v1.3.10 (2018-02-05) - Do not crash under *Xephyr*
--------------------------------------------------
* Do not crash when ``Xlib.display.Display.get_input_focus`` returns an
integer, as it may when running under *Xephyr*. Thanks to *Eli Skeggs*!
v1.3.9 (2018-01-12) - Correctly handle the letter *A* on *OSX*
--------------------------------------------------------------
* Corrected check for virtual key code when generating keyboard events on
*OSX*. This fixes an issue where pressing *A* with *shift* explicitly pressed
would still type a minuscule letter.
v1.3.8 (2017-12-08) - Do not crash on some keyboard layouts on *OSX*
--------------------------------------------------------------------
* Fall back on a different method to retrieve the keyboard layout on *OSX*.
This helps for some keyboard layouts, such as *Chinese*. Thanks to
*haoflynet*!
v1.3.7 (2017-08-23) - *Xorg* corrections
----------------------------------------
* Include mouse buttons up to *30* for *Xorg*.
v1.3.6 (2017-08-13) - *win32* corrections
-----------------------------------------
* Corrected double delivery of fake keyboard events on *Windows*.
* Corrected handling of synthetic unicode keys on *Windows*.
v1.3.5 (2017-06-07) - Corrected dependencies again
--------------------------------------------------
* Reverted changes in *1.3.3*.
* Corrected platform specifier for *Python 2* on *Linux*.
v1.3.4 (2017-06-05) - *Xorg* corrections
----------------------------------------
* Corrected bounds check for values on *Xorg*.
v1.3.3 (2017-06-05) - Make dependencies non-optional
----------------------------------------------------
* Made platform dependencies non-optional.
v1.3.2 (2017-05-15) - Fix for button click on Mac
-------------------------------------------------
* Corrected regression from previous release where button clicks would
crash the *Mac* mouse listener.
v1.3.1 (2017-05-12) - Fixes for unknown buttons on Linux
--------------------------------------------------------
* Fall back on `Button.unknown` for unknown mouse buttons in *Xorg* mouse
listener.
v1.3 (2017-04-10) - Platform specific features
----------------------------------------------
* Added ability to stop event propagation on *Windows*. This will prevent
events from reaching other applications.
* Added ability to ignore events on *Windows*. This is a workaround for systems
where the keyboard monitor interferes with normal keyboard events.
* Added ability to modify events on *OSX*. This allows intercepting and
altering input events before they reach other applications.
* Corrected crash on *OSX* when some types of third party input sources are
installed.
v1.2 (2017-01-06) - Improved error handling
-------------------------------------------
* Allow catching exceptions thrown from listener callbacks. This changes the
API, as joining a listener now potentially raises unhandled exceptions,
and unhandled exceptions will stop listeners.
* Added support for the numeric keypad on *Linux*.
* Improved documentation.
* Thanks to *jollysean* and *gilleswijnker* for their input!
v1.1.7 (2017-01-02) - Handle middle button on Windows
-----------------------------------------------------
* Listen for and dispatch middle button mouse clicks on *Windows*.
v1.1.6 (2016-11-24) - Corrected context manager for pressing keys
-----------------------------------------------------------------
* Corrected bug in ``pynput.keyboard.Controller.pressed`` which caused it to
never release the key. Many thanks to Toby Southwell!
v1.1.5 (2016-11-17) - Corrected modifier key combinations on Linux
------------------------------------------------------------------
* Corrected handling of modifier keys to allow them to be composable on
*Linux*.
v1.1.4 (2016-10-30) - Small bugfixes
------------------------------------
* Corrected error generation when ``GetKeyboardState`` fails.
* Make sure to apply shift state to borrowed keys on *X*.
* Use *pylint*.
v1.1.3 (2016-09-27) - Changed Xlib backend library
--------------------------------------------------
* Changed *Xlib* library.
v1.1.2 (2016-09-26) - Added missing type for Python 2
-----------------------------------------------------
* Added missing ``LPDWORD`` for *Python 2* on *Windows*.
v1.1.1 (2016-09-26) - Fixes for listeners and controllers on Windows
--------------------------------------------------------------------
* Corrected keyboard listener on *Windows*. Modifier keys and other keys
changing the state of the keyboard are now handled correctly.
* Corrected mouse click and release on *Windows*.
* Corrected code samples.
v1.1 (2016-06-22) - Simplified usage on Linux
---------------------------------------------
* Propagate import errors raised on Linux to help troubleshoot missing
``Xlib`` module.
* Declare ``python3-xlib`` as dependency on *Linux* for *Python 3*.
v1.0.6 (2016-04-19) - Universal wheel
-------------------------------------
* Make sure to build a universal wheel for all python versions.
v1.0.5 (2016-04-11) - Fixes for dragging on OSX
-----------------------------------------------
* Corrected dragging on *OSX*.
* Added scroll speed constant for *OSX* to correct slow scroll speed.
v1.0.4 (2016-04-11) - Fixes for clicking and scrolling on Windows
-----------------------------------------------------------------
* Corrected name of mouse input field when sending click and scroll events.
v1.0.3 (2016-04-05) - Fixes for Python 3 on Windows
---------------------------------------------------
* Corrected use of ``ctypes`` on Windows.
v1.0.2 (2016-04-03) - Fixes for thread identifiers
--------------------------------------------------
* Use thread identifiers to identify threads, not Thread instances.
v1.0.1 (2016-04-03) - Fixes for Python 3
----------------------------------------
* Corrected bugs which prevented the library from being used on *Python 3*.
v1.0 (2016-02-28) - Stable Release
----------------------------------
* Changed license to *LGPL*.
* Corrected minor bugs and inconsistencies.
* Corrected and extended documentation.
v0.6 (2016-02-08) - Keyboard Monitor
------------------------------------
* Added support for monitoring the keyboard.
* Corrected wheel packaging.
* Corrected deadlock when stopping a listener in some cases on *X*.
* Corrected key code constants on *Mac OSX*.
* Do not intercept events on *Mac OSX*.
v0.5.1 (2016-01-26) - Do not die on dead keys
---------------------------------------------
* Corrected handling of dead keys.
* Corrected documentation.
v0.5 (2016-01-18) - Keyboard Modifiers
--------------------------------------
* Added support for modifiers.
v0.4 (2015-12-22) - Keyboard Controller
---------------------------------------
* Added keyboard controller.
v0.3 (2015-12-22) - Cleanup
---------------------------
* Moved ``pynput.mouse.Controller.Button`` to top-level.
v0.2 (2015-10-28) - Initial Release
-----------------------------------
* Support for controlling the mouse on *Linux*, *Mac OSX* and *Windows*.
* Support for monitoring the mouse on *Linux*, *Mac OSX* and *Windows*.
pynput-1.7.6/COPYING.LGPL 0000664 0000000 0000000 00000016750 14164131047 0014666 0 ustar 00root root 0000000 0000000 GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007-2022 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
pynput-1.7.6/README.rst 0000664 0000000 0000000 00000000344 14164131047 0014555 0 ustar 00root root 0000000 0000000 pynput
======
This library allows you to control and monitor input devices.
Currently, mouse and keyboard input and monitoring are supported.
See `here `_ for the full
documentation.
pynput-1.7.6/docs/ 0000775 0000000 0000000 00000000000 14164131047 0014015 5 ustar 00root root 0000000 0000000 pynput-1.7.6/docs/conf.py 0000664 0000000 0000000 00000003745 14164131047 0015325 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
import datetime
import sys
import os
# Make sure we can import the package
sys.path.insert(
0,
os.path.join(
os.path.dirname(__file__),
os.path.pardir,
'lib'))
os.environ['PYNPUT_BACKEND'] = 'dummy'
import pynput as package
import pynput._info as INFO
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = package.__package__
original_year = 2015
current_year = datetime.date.today().year
if original_year == current_year:
copyright = u'%d, %s' % (
current_year,
INFO.__author__)
else:
copyright = u'%d-%d, %s' % (
original_year,
current_year,
INFO.__author__)
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
# The short X.Y version.
version = '.'.join(str(v) for v in INFO.__version__)
# The full version, including alpha/beta/rc tags.
release = version
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'alabaster'
# Output file base name for HTML help builder.
htmlhelp_basename = '%sdoc' % package.__package__
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(
'index',
package.__package__,
u'%s Documentation' % package.__package__,
[package._info.__author__],
1)]
pynput-1.7.6/docs/faq.rst 0000664 0000000 0000000 00000006707 14164131047 0015330 0 ustar 00root root 0000000 0000000 Frequently asked question
-------------------------
How do I suppress specific events only?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Passing the ``suppress=True`` flag to listeners will suppress all events
system-wide. If this is not what you want, you will have to employ different
solutions for different backends.
If your backend of choice is not listed below, it does not support suppression
of specific events.
macOS
^^^^^
For *macOS*, pass the named argument ``darwin_intercept`` to the listener
constructor. This argument should be a callable taking the arguments
``(event_type, event)``, where ``event_type`` is any mouse related event type
constant, and ``event`` is a `CGEventRef`_. The ``event`` argument can be
manipulated by the functions found on the `Apple documentation`_.
If the interceptor function determines that the event should be suppressed,
return ``None``, otherwise return the ``event``, which you may modify.
Here is a keyboard example::
def darwin_intercept(event_type, event):
import Quartz
length, chars = Quartz.CGEventKeyboardGetUnicodeString(
event, 100, None, None)
if length > 0 and chars == 'x':
# Suppress x
return None
elif length > 0 and chars == 'a':
# Transform a to b
Quartz.CGEventKeyboardSetUnicodeString(event, 1, 'b')
else:
return event
.. _CGEventRef: https://developer.apple.com/documentation/coregraphics/cgeventref?language=objc
.. _Apple documentation: https://developer.apple.com/documentation/coregraphics/quartz_event_services?language=objc
Windows
^^^^^^^
For *Windows*, pass the argument named ``win32_event_filter`` to the listener
constructor. This argument should be a callable taking the arguments
``(msg, data)``, where ``msg`` is the current message, and ``data`` associated
data as a `MSLLHOOKSTRUCT`_ or a `KBDLLHOOKSTRUCT`, depending on whether you
are creating a mouse or keyboard listener.
If the filter function determines that the event should be suppressed, call
``suppress_event`` on the listener. If you return ``False``, the event will be
hidden from other listener callbacks.
Here is a keyboard example::
# Values for MSLLHOOKSTRUCT.vkCode can be found here:
# https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
def win32_event_filter(msg, data):
if data.vkCode == 0x58:
# Suppress x
listener.suppress_event()
.. _MSLLHOOKSTRUCT: https://docs.microsoft.com/en-gb/windows/win32/api/winuser/ns-winuser-msllhookstruct
.. _KBDLLHOOKSTRUCT: https://docs.microsoft.com/en-gb/windows/win32/api/winuser/ns-winuser-kbdllhookstruct
When using a packager I get an ``ImportError`` on startup
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This happens when using a packager, such as *PyInstaller*, to package your
application.
The reason for the error is that the packager attempts to build a dependency
tree of the modules used by inspecting ``import`` statements, and *pynput*
finds the platform dependent backend modules at runtime using ``importlib``.
To solve this problem, please consult the documentation of your tool to find
how to explicitly add modules.
Which modules to add depends on your distribution platform. The backend modules
are those starting with an underscore (``'_'``) in the ``pynput.keyboard`` and
``pynput.mouse`` packages. Additionally, you will need modules with
corresponding names from the ``pynput._util`` package.
pynput-1.7.6/docs/index.rst 0000664 0000000 0000000 00000003022 14164131047 0015653 0 ustar 00root root 0000000 0000000 pynput Package Documentation
============================
This library allows you to control and monitor input devices.
It contains subpackages for each type of input device supported:
:mod:`pynput.mouse`
Contains classes for controlling and monitoring a mouse or trackpad.
:mod:`pynput.keyboard`
Contains classes for controlling and monitoring the keyboard.
All modules mentioned above are automatically imported into the :mod:`pynput`
package. To use any of them, import them from the main package::
from pynput import mouse, keyboard
Forcing a specific backend
--------------------------
*pynput* attempts to use the backend suitable for the current platform, but
this automatic choice is possible to override.
If the environment variables ``$PYNPUT_BACKEND_KEYBOARD`` or
``$PYNPUT_BACKEND`` are set, their value will be used as backend name for the
keyboard classes, and if ``$PYNPUT_BACKEND_MOUSE`` or ``$PYNPUT_BACKEND``
are set, their value will be used as backend name for the mouse classes.
Available backends are:
* ``darwin``, the default for *macOS*.
* ``win32``, the default for *Windows*.
* ``uinput``, an optional backend for *Linux* requiring *root* privileges and
supporting only keyboards.
* ``xorg``, the default for other operating systems.
* ``dummy``, a non-functional, but importable, backend. This is useful as
mouse backend when using the ``uinput`` backend.
Table of contents
-----------------
.. toctree::
:maxdepth: 2
mouse
keyboard
faq
limitations
* :ref:`genindex`
pynput-1.7.6/docs/keyboard-usage.rst 0000664 0000000 0000000 00000015702 14164131047 0017456 0 ustar 00root root 0000000 0000000 Controlling the keyboard
------------------------
Use ``pynput.keyboard.Controller`` like this::
from pynput.keyboard import Key, Controller
keyboard = Controller()
# Press and release space
keyboard.press(Key.space)
keyboard.release(Key.space)
# Type a lower case A; this will work even if no key on the
# physical keyboard is labelled 'A'
keyboard.press('a')
keyboard.release('a')
# Type two upper case As
keyboard.press('A')
keyboard.release('A')
with keyboard.pressed(Key.shift):
keyboard.press('a')
keyboard.release('a')
# Type 'Hello World' using the shortcut type method
keyboard.type('Hello World')
Monitoring the keyboard
-----------------------
Use ``pynput.keyboard.Listener`` like this::
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
# ...or, in a non-blocking fashion:
listener = keyboard.Listener(
on_press=on_press,
on_release=on_release)
listener.start()
A keyboard listener is a ``threading.Thread``, and all callbacks will be
invoked from the thread.
Call ``pynput.keyboard.Listener.stop`` from anywhere, raise ``StopException``
or return ``False`` from a callback to stop the listener.
The ``key`` parameter passed to callbacks is a ``pynput.keyboard.Key``, for
special keys, a ``pynput.keyboard.KeyCode`` for normal alphanumeric keys, or
just ``None`` for unknown keys.
When using the non-blocking version above, the current thread will continue
executing. This might be necessary when integrating with other GUI frameworks
that incorporate a main-loop, but when run from a script, this will cause the
program to terminate immediately.
The keyboard listener thread
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The listener callbacks are invoked directly from an operating thread on some
platforms, notably *Windows*.
This means that long running procedures and blocking operations should not be
invoked from the callback, as this risks freezing input for all processes.
A possible workaround is to just dispatch incoming messages to a queue, and let
a separate thread handle them.
Handling keyboard listener errors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If a callback handler raises an exception, the listener will be stopped. Since
callbacks run in a dedicated thread, the exceptions will not automatically be
reraised.
To be notified about callback errors, call ``Thread.join`` on the listener
instance::
from pynput import keyboard
class MyException(Exception): pass
def on_press(key):
if key == keyboard.Key.esc:
raise MyException(key)
# Collect events until released
with keyboard.Listener(
on_press=on_press) as listener:
try:
listener.join()
except MyException as e:
print('{0} was pressed'.format(e.args[0]))
Toggling event listening for the keyboard listener
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Once ``pynput.keyboard.Listener.stop`` has been called, the listener cannot be
restarted, since listeners are instances of ``threading.Thread``.
If your application requires toggling listening events, you must either add an
internal flag to ignore events when not required, or create a new listener when
resuming listening.
Synchronous event listening for the keyboard listener
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To simplify scripting, synchronous event listening is supported through the
utility class ``pynput.keyboard.Events``. This class supports reading single
events in a non-blocking fashion, as well as iterating over all events.
To read a single event, use the following code::
from pynput import keyboard
# The event listener will be running in this block
with keyboard.Events() as events:
# Block at most one second
event = events.get(1.0)
if event is None:
print('You did not press a key within one second')
else:
print('Received event {}'.format(event))
To iterate over keyboard events, use the following code::
from pynput import keyboard
# The event listener will be running in this block
with keyboard.Events() as events:
for event in events:
if event.key == keyboard.Key.esc:
break
else:
print('Received event {}'.format(event))
Please note that the iterator method does not support non-blocking operation,
so it will wait for at least one keyboard event.
The events will be instances of the inner classes found in
``pynput.keyboard.Events``.
Global hotkeys
~~~~~~~~~~~~~~
A common use case for keyboard monitors is reacting to global hotkeys. Since a
listener does not maintain any state, hotkeys involving multiple keys must
store this state somewhere.
*pynput* provides the class ``pynput.keyboard.HotKey`` for this purpose. It
contains two methods to update the state, designed to be easily interoperable
with a keyboard listener: ``pynput.keyboard.HotKey.press`` and
``pynput.keyboard.HotKey.release`` which can be directly passed as listener
callbacks.
The intended usage is as follows::
from pynput import keyboard
def on_activate():
print('Global hotkey activated!')
def for_canonical(f):
return lambda k: f(l.canonical(k))
hotkey = keyboard.HotKey(
keyboard.HotKey.parse('++h'),
on_activate)
with keyboard.Listener(
on_press=for_canonical(hotkey.press),
on_release=for_canonical(hotkey.release)) as l:
l.join()
This will create a hotkey, and then use a listener to update its state. Once
all the specified keys are pressed simultaneously, ``on_activate`` will be
invoked.
Note that keys are passed through ``pynput.keyboard.Listener.canonical`` before
being passed to the ``HotKey`` instance. This is to remove any modifier state
from the key events, and to normalise modifiers with more than one physical
button.
The method ``pynput.keyboard.HotKey.parse`` is a convenience function to
transform shortcut strings to key collections. Please see its documentation for
more information.
To register a number of global hotkeys, use the convenience class
``pynput.keyboard.GlobalHotKeys``::
from pynput import keyboard
def on_activate_h():
print('++h pressed')
def on_activate_i():
print('++i pressed')
with keyboard.GlobalHotKeys({
'++h': on_activate_h,
'++i': on_activate_i}) as h:
h.join()
pynput-1.7.6/docs/keyboard.rst 0000664 0000000 0000000 00000000705 14164131047 0016351 0 ustar 00root root 0000000 0000000 Handling the keyboard
=====================
The package :mod:`pynput.keyboard` contains classes for controlling and
monitoring the keyboard.
.. include:: ./keyboard-usage.rst
Reference
---------
.. autoclass:: pynput.keyboard.Controller
:members:
.. autoclass:: pynput.keyboard.Listener
:members: __init__, running, start, stop, wait
.. autoclass:: pynput.keyboard.Key
:members:
.. autoclass:: pynput.keyboard.KeyCode
:members:
pynput-1.7.6/docs/limitations.rst 0000664 0000000 0000000 00000004700 14164131047 0017104 0 ustar 00root root 0000000 0000000 Platform limitations
--------------------
*pynput* aims at providing a unified *API* for all supported platforms. In some
cases, however, that is not entirely possible.
Linux
~~~~~
On *Linux*, *pynput* uses *X* or *uinput*.
When running under *X*, the following must be true:
* An *X server* must be running.
* The environment variable ``$DISPLAY`` must be set.
When running under *uinput*, the following must be true:
* You must run your script as root, to that is has the required permissions
for *uinput*.
The latter requirement for *X* means that running *pynput* over *SSH* generally
will not work. To work around that, make sure to set ``$DISPLAY``:
.. code-block:: bash
$ DISPLAY=:0 python -c 'import pynput'
Please note that the value ``DISPLAY=:0`` is just an example. To find the
actual value, please launch a terminal application from your desktop
environment and issue the command ``echo $DISPLAY``.
When running under *Wayland*, the *X server* emulator ``Xwayland`` will usually
run, providing limited functionality. Notably, you will only receive input
events from applications running under this emulator.
macOS
~~~~~
Recent versions of *macOS* restrict monitoring of the keyboard for security
reasons. For that reason, one of the following must be true:
* The process must run as root.
* Your application must be white listed under *Enable access for assistive
devices*. Note that this might require that you package your application,
since otherwise the entire *Python* installation must be white listed.
* On versions after *Mojave*, you may also need to whitelist your terminal
application if running your script from a terminal.
Please note that this does not apply to monitoring of the mouse or trackpad.
All listener classes have the additional attribute ``IS_TRUSTED``, which is
``True`` if no permissions are lacking.
Windows
~~~~~~~
On *Windows*, virtual events sent by *other* processes may not be received.
This library takes precautions, however, to dispatch any virtual events
generated to all currently running listeners of the current process.
Furthermore, sending key press events will properly propagate to the rest of
the system, but the operating system does not consider the buttons to be truly
*pressed*. This means that key press events will not be continuously emitted as
when holding down a physical key, and certain key sequences, such as *shift*
pressed while pressing arrow keys, do not work as expected.
pynput-1.7.6/docs/mouse-usage.rst 0000664 0000000 0000000 00000013541 14164131047 0017005 0 ustar 00root root 0000000 0000000 Controlling the mouse
---------------------
Use ``pynput.mouse.Controller`` like this::
from pynput.mouse import Button, Controller
mouse = Controller()
# Read pointer position
print('The current pointer position is {0}'.format(
mouse.position))
# Set pointer position
mouse.position = (10, 20)
print('Now we have moved it to {0}'.format(
mouse.position))
# Move pointer relative to current position
mouse.move(5, -5)
# Press and release
mouse.press(Button.left)
mouse.release(Button.left)
# Double click; this is different from pressing and releasing
# twice on macOS
mouse.click(Button.left, 2)
# Scroll two steps down
mouse.scroll(0, 2)
Monitoring the mouse
--------------------
Use ``pynput.mouse.Listener`` like this::
from pynput import mouse
def on_move(x, y):
print('Pointer moved to {0}'.format(
(x, y)))
def on_click(x, y, button, pressed):
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
if not pressed:
# Stop listener
return False
def on_scroll(x, y, dx, dy):
print('Scrolled {0} at {1}'.format(
'down' if dy < 0 else 'up',
(x, y)))
# Collect events until released
with mouse.Listener(
on_move=on_move,
on_click=on_click,
on_scroll=on_scroll) as listener:
listener.join()
# ...or, in a non-blocking fashion:
listener = mouse.Listener(
on_move=on_move,
on_click=on_click,
on_scroll=on_scroll)
listener.start()
A mouse listener is a ``threading.Thread``, and all callbacks will be invoked
from the thread.
Call ``pynput.mouse.Listener.stop`` from anywhere, raise ``StopException`` or
return ``False`` from a callback to stop the listener.
When using the non-blocking version above, the current thread will continue
executing. This might be necessary when integrating with other GUI frameworks
that incorporate a main-loop, but when run from a script, this will cause the
program to terminate immediately.
The mouse listener thread
~~~~~~~~~~~~~~~~~~~~~~~~~
The listener callbacks are invoked directly from an operating thread on some
platforms, notably *Windows*.
This means that long running procedures and blocking operations should not be
invoked from the callback, as this risks freezing input for all processes.
A possible workaround is to just dispatch incoming messages to a queue, and let
a separate thread handle them.
Handling mouse listener errors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If a callback handler raises an exception, the listener will be stopped. Since
callbacks run in a dedicated thread, the exceptions will not automatically be
reraised.
To be notified about callback errors, call ``Thread.join`` on the listener
instance::
from pynput import mouse
class MyException(Exception): pass
def on_click(x, y, button, pressed):
if button == mouse.Button.left:
raise MyException(button)
# Collect events until released
with mouse.Listener(
on_click=on_click) as listener:
try:
listener.join()
except MyException as e:
print('{0} was clicked'.format(e.args[0]))
Toggling event listening for the mouse listener
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Once ``pynput.mouse.Listener.stop`` has been called, the listener cannot be
restarted, since listeners are instances of ``threading.Thread``.
If your application requires toggling listening events, you must either add an
internal flag to ignore events when not required, or create a new listener when
resuming listening.
Synchronous event listening for the mouse listener
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To simplify scripting, synchronous event listening is supported through the
utility class ``pynput.mouse.Events``. This class supports reading single
events in a non-blocking fashion, as well as iterating over all events.
To read a single event, use the following code::
from pynput import mouse
# The event listener will be running in this block
with mouse.Events() as events:
# Block at most one second
event = events.get(1.0)
if event is None:
print('You did not interact with the mouse within one second')
else:
print('Received event {}'.format(event))
To iterate over mouse events, use the following code::
from pynput import mouse
# The event listener will be running in this block
with mouse.Events() as events:
for event in events:
if event.button == mouse.Button.right:
break
else:
print('Received event {}'.format(event))
Please note that the iterator method does not support non-blocking operation,
so it will wait for at least one mouse event.
The events will be instances of the inner classes found in
``pynput.mouse.Events``.
Ensuring consistent coordinates between listener and controller on Windows
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Recent versions of _Windows_ support running legacy applications scaled when
the system scaling has been increased beyond 100%. This allows old applications
to scale, albeit with a blurry look, and avoids tiny, unusable user interfaces.
This scaling is unfortunately inconsistently applied to a mouse listener and a
controller: the listener will receive physical coordinates, but the controller
has to work with scaled coordinates.
This can be worked around by telling Windows that your application is DPI
aware. This is a process global setting, so _pynput_ cannot do it
automatically. Do enable DPI awareness, run the following code::
import ctypes
PROCESS_PER_MONITOR_DPI_AWARE = 2
ctypes.windll.shcore.SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE)
pynput-1.7.6/docs/mouse.rst 0000664 0000000 0000000 00000000510 14164131047 0015673 0 ustar 00root root 0000000 0000000 Handling the mouse
==================
The package :mod:`pynput.mouse` contains classes for controlling and monitoring
the mouse.
.. include:: ./mouse-usage.rst
Reference
---------
.. autoclass:: pynput.mouse.Controller
:members:
.. autoclass:: pynput.mouse.Listener
:members: __init__, running, start, stop, wait
pynput-1.7.6/docs/private.rst 0000664 0000000 0000000 00000002373 14164131047 0016226 0 ustar 00root root 0000000 0000000 Private *pynput* API
====================
This is the *internal pynput API*. It is used internally by *pynput*, and its
interface is not stable.
This documentation will contain only the modules used on the current platform.
Utility Modules
---------------
.. automodule:: pynput._util
:members:
:private-members:
:special-members:
.. automodule:: pynput._util.darwin
:members:
:private-members:
:special-members:
.. automodule:: pynput._util.win32
:members:
:private-members:
:special-members:
.. automodule:: pynput._util.xorg
:members:
:private-members:
:special-members:
Mouse Modules
-------------
.. automodule:: pynput.mouse._darwin
:members:
:private-members:
:special-members:
.. automodule:: pynput.mouse._win32
:members:
:private-members:
:special-members:
.. automodule:: pynput.mouse._xorg
:members:
:private-members:
:special-members:
Keyboard Modules
----------------
.. automodule:: pynput.keyboard._darwin
:members:
:private-members:
:special-members:
.. automodule:: pynput.keyboard._win32
:members:
:private-members:
:special-members:
.. automodule:: pynput.keyboard._xorg
:members:
:private-members:
:special-members:
pynput-1.7.6/lib/ 0000775 0000000 0000000 00000000000 14164131047 0013633 5 ustar 00root root 0000000 0000000 pynput-1.7.6/lib/pynput/ 0000775 0000000 0000000 00000000000 14164131047 0015172 5 ustar 00root root 0000000 0000000 pynput-1.7.6/lib/pynput/__init__.py 0000664 0000000 0000000 00000002466 14164131047 0017313 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
The main *pynput* module.
This module imports ``keyboard`` and ``mouse``.
"""
def _logger(cls):
"""Creates a logger with a name suitable for a specific class.
This function takes into account that implementations for classes reside in
platform dependent modules, and thus removes the final part of the module
name.
:param type cls: The class for which to create a logger.
:return: a logger
"""
import logging
return logging.getLogger('{}.{}'.format(
'.'.join(cls.__module__.split('.', 2)[:2]),
cls.__name__))
from . import keyboard
from . import mouse
pynput-1.7.6/lib/pynput/_info.py 0000664 0000000 0000000 00000001407 14164131047 0016640 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pystray
# Copyright (C) 2015-2022 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 .
__author__ = u'Moses Palmér'
__version__ = (1, 7, 6)
pynput-1.7.6/lib/pynput/_util/ 0000775 0000000 0000000 00000000000 14164131047 0016306 5 ustar 00root root 0000000 0000000 pynput-1.7.6/lib/pynput/_util/__init__.py 0000664 0000000 0000000 00000033767 14164131047 0020437 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
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 os
import sys
import threading
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 or (lambda *a: None)))
@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 join(self, *args):
super(AbstractListener, self).join(*args)
# Reraise any exceptions
try:
exc_type, exc_value, exc_traceback = self._queue.get()
except TypeError:
return
six.reraise(exc_type, exc_value, exc_traceback)
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)
pynput-1.7.6/lib/pynput/_util/darwin.py 0000664 0000000 0000000 00000020716 14164131047 0020152 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
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 CoreFoundation
import HIServices
import Quartz
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:
CoreFoundation.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`.
"""
#: 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 = Quartz.CFMachPortCreateRunLoopSource(
None, tap, 0)
self._loop = Quartz.CFRunLoopGetCurrent()
Quartz.CFRunLoopAddSource(
self._loop, loop_source, Quartz.kCFRunLoopDefaultMode)
Quartz.CGEventTapEnable(tap, True)
self._mark_ready()
# pylint: disable=W0702; we want to silence errors
try:
while self.running:
result = Quartz.CFRunLoopRunInMode(
Quartz.kCFRunLoopDefaultMode, 1, False)
try:
if result != Quartz.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:
Quartz.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 Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap,
Quartz.kCGHeadInsertEventTap,
Quartz.kCGEventTapOptionListenOnly if (
True
and not self.suppress
and self._intercept is None)
else Quartz.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.
"""
self._handle(proxy, event_type, event, refcon)
if self._intercept is not None:
return self._intercept(event_type, event)
elif self.suppress:
return None
def _handle(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()
pynput-1.7.6/lib/pynput/_util/darwin_vks.py 0000664 0000000 0000000 00000002750 14164131047 0021033 0 ustar 00root root 0000000 0000000 # coding: utf-8
# pynput
# Copyright (C) 2015-2022 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 .
# 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',
}
pynput-1.7.6/lib/pynput/_util/uinput.py 0000664 0000000 0000000 00000005375 14164131047 0020216 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
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`.
"""
#: 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(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(self, event):
"""Handles a single event.
This method should call one of the registered event callbacks.
:param event: The event.
"""
raise NotImplementedError()
pynput-1.7.6/lib/pynput/_util/win32.py 0000664 0000000 0000000 00000043276 14164131047 0017636 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
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`.
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_HANDLE` 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(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(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()
pynput-1.7.6/lib/pynput/_util/win32_vks.py 0000664 0000000 0000000 00000005516 14164131047 0020514 0 ustar 00root root 0000000 0000000 # coding: utf-8
# pynput
# Copyright (C) 2015-2022 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 .
# 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
pynput-1.7.6/lib/pynput/_util/xorg.py 0000664 0000000 0000000 00000035377 14164131047 0017656 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
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`.
"""
#: 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)
self._handle(self._display_stop, event)
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(self, display, event):
"""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.
"""
pass
pynput-1.7.6/lib/pynput/_util/xorg_keysyms.py 0000664 0000000 0000000 00000207332 14164131047 0021432 0 ustar 00root root 0000000 0000000 # coding: utf-8
# pynput
# Copyright (C) 2015-2022 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 .
# pylint: disable=C0111,C0302
SYMBOLS = {
'0': (0x0030, u'\u0030'),
'1': (0x0031, u'\u0031'),
'2': (0x0032, u'\u0032'),
'3': (0x0033, u'\u0033'),
'4': (0x0034, u'\u0034'),
'5': (0x0035, u'\u0035'),
'6': (0x0036, u'\u0036'),
'7': (0x0037, u'\u0037'),
'8': (0x0038, u'\u0038'),
'9': (0x0039, u'\u0039'),
'A': (0x0041, u'\u0041'),
'AE': (0x00c6, u'\u00C6'),
'Aacute': (0x00c1, u'\u00C1'),
'Abelowdot': (0x1001ea0, u'\u1EA0'),
'Abreve': (0x01c3, u'\u0102'),
'Abreveacute': (0x1001eae, u'\u1EAE'),
'Abrevebelowdot': (0x1001eb6, u'\u1EB6'),
'Abrevegrave': (0x1001eb0, u'\u1EB0'),
'Abrevehook': (0x1001eb2, u'\u1EB2'),
'Abrevetilde': (0x1001eb4, u'\u1EB4'),
'Acircumflex': (0x00c2, u'\u00C2'),
'Acircumflexacute': (0x1001ea4, u'\u1EA4'),
'Acircumflexbelowdot': (0x1001eac, u'\u1EAC'),
'Acircumflexgrave': (0x1001ea6, u'\u1EA6'),
'Acircumflexhook': (0x1001ea8, u'\u1EA8'),
'Acircumflextilde': (0x1001eaa, u'\u1EAA'),
'Adiaeresis': (0x00c4, u'\u00C4'),
'Agrave': (0x00c0, u'\u00C0'),
'Ahook': (0x1001ea2, u'\u1EA2'),
'Amacron': (0x03c0, u'\u0100'),
'Aogonek': (0x01a1, u'\u0104'),
'Arabic_0': (0x1000660, u'\u0660'),
'Arabic_1': (0x1000661, u'\u0661'),
'Arabic_2': (0x1000662, u'\u0662'),
'Arabic_3': (0x1000663, u'\u0663'),
'Arabic_4': (0x1000664, u'\u0664'),
'Arabic_5': (0x1000665, u'\u0665'),
'Arabic_6': (0x1000666, u'\u0666'),
'Arabic_7': (0x1000667, u'\u0667'),
'Arabic_8': (0x1000668, u'\u0668'),
'Arabic_9': (0x1000669, u'\u0669'),
'Arabic_ain': (0x05d9, u'\u0639'),
'Arabic_alef': (0x05c7, u'\u0627'),
'Arabic_alefmaksura': (0x05e9, u'\u0649'),
'Arabic_beh': (0x05c8, u'\u0628'),
'Arabic_comma': (0x05ac, u'\u060C'),
'Arabic_dad': (0x05d6, u'\u0636'),
'Arabic_dal': (0x05cf, u'\u062F'),
'Arabic_damma': (0x05ef, u'\u064F'),
'Arabic_dammatan': (0x05ec, u'\u064C'),
'Arabic_ddal': (0x1000688, u'\u0688'),
'Arabic_farsi_yeh': (0x10006cc, u'\u06CC'),
'Arabic_fatha': (0x05ee, u'\u064E'),
'Arabic_fathatan': (0x05eb, u'\u064B'),
'Arabic_feh': (0x05e1, u'\u0641'),
'Arabic_fullstop': (0x10006d4, u'\u06D4'),
'Arabic_gaf': (0x10006af, u'\u06AF'),
'Arabic_ghain': (0x05da, u'\u063A'),
'Arabic_ha': (0x05e7, u'\u0647'),
'Arabic_hah': (0x05cd, u'\u062D'),
'Arabic_hamza': (0x05c1, u'\u0621'),
'Arabic_hamza_above': (0x1000654, u'\u0654'),
'Arabic_hamza_below': (0x1000655, u'\u0655'),
'Arabic_hamzaonalef': (0x05c3, u'\u0623'),
'Arabic_hamzaonwaw': (0x05c4, u'\u0624'),
'Arabic_hamzaonyeh': (0x05c6, u'\u0626'),
'Arabic_hamzaunderalef': (0x05c5, u'\u0625'),
'Arabic_heh_doachashmee': (0x10006be, u'\u06BE'),
'Arabic_heh_goal': (0x10006c1, u'\u06C1'),
'Arabic_jeem': (0x05cc, u'\u062C'),
'Arabic_jeh': (0x1000698, u'\u0698'),
'Arabic_kaf': (0x05e3, u'\u0643'),
'Arabic_kasra': (0x05f0, u'\u0650'),
'Arabic_kasratan': (0x05ed, u'\u064D'),
'Arabic_keheh': (0x10006a9, u'\u06A9'),
'Arabic_khah': (0x05ce, u'\u062E'),
'Arabic_lam': (0x05e4, u'\u0644'),
'Arabic_madda_above': (0x1000653, u'\u0653'),
'Arabic_maddaonalef': (0x05c2, u'\u0622'),
'Arabic_meem': (0x05e5, u'\u0645'),
'Arabic_noon': (0x05e6, u'\u0646'),
'Arabic_noon_ghunna': (0x10006ba, u'\u06BA'),
'Arabic_peh': (0x100067e, u'\u067E'),
'Arabic_percent': (0x100066a, u'\u066A'),
'Arabic_qaf': (0x05e2, u'\u0642'),
'Arabic_question_mark': (0x05bf, u'\u061F'),
'Arabic_ra': (0x05d1, u'\u0631'),
'Arabic_rreh': (0x1000691, u'\u0691'),
'Arabic_sad': (0x05d5, u'\u0635'),
'Arabic_seen': (0x05d3, u'\u0633'),
'Arabic_semicolon': (0x05bb, u'\u061B'),
'Arabic_shadda': (0x05f1, u'\u0651'),
'Arabic_sheen': (0x05d4, u'\u0634'),
'Arabic_sukun': (0x05f2, u'\u0652'),
'Arabic_superscript_alef': (0x1000670, u'\u0670'),
'Arabic_tah': (0x05d7, u'\u0637'),
'Arabic_tatweel': (0x05e0, u'\u0640'),
'Arabic_tcheh': (0x1000686, u'\u0686'),
'Arabic_teh': (0x05ca, u'\u062A'),
'Arabic_tehmarbuta': (0x05c9, u'\u0629'),
'Arabic_thal': (0x05d0, u'\u0630'),
'Arabic_theh': (0x05cb, u'\u062B'),
'Arabic_tteh': (0x1000679, u'\u0679'),
'Arabic_veh': (0x10006a4, u'\u06A4'),
'Arabic_waw': (0x05e8, u'\u0648'),
'Arabic_yeh': (0x05ea, u'\u064A'),
'Arabic_yeh_baree': (0x10006d2, u'\u06D2'),
'Arabic_zah': (0x05d8, u'\u0638'),
'Arabic_zain': (0x05d2, u'\u0632'),
'Aring': (0x00c5, u'\u00C5'),
'Armenian_AT': (0x1000538, u'\u0538'),
'Armenian_AYB': (0x1000531, u'\u0531'),
'Armenian_BEN': (0x1000532, u'\u0532'),
'Armenian_CHA': (0x1000549, u'\u0549'),
'Armenian_DA': (0x1000534, u'\u0534'),
'Armenian_DZA': (0x1000541, u'\u0541'),
'Armenian_E': (0x1000537, u'\u0537'),
'Armenian_FE': (0x1000556, u'\u0556'),
'Armenian_GHAT': (0x1000542, u'\u0542'),
'Armenian_GIM': (0x1000533, u'\u0533'),
'Armenian_HI': (0x1000545, u'\u0545'),
'Armenian_HO': (0x1000540, u'\u0540'),
'Armenian_INI': (0x100053b, u'\u053B'),
'Armenian_JE': (0x100054b, u'\u054B'),
'Armenian_KE': (0x1000554, u'\u0554'),
'Armenian_KEN': (0x100053f, u'\u053F'),
'Armenian_KHE': (0x100053d, u'\u053D'),
'Armenian_LYUN': (0x100053c, u'\u053C'),
'Armenian_MEN': (0x1000544, u'\u0544'),
'Armenian_NU': (0x1000546, u'\u0546'),
'Armenian_O': (0x1000555, u'\u0555'),
'Armenian_PE': (0x100054a, u'\u054A'),
'Armenian_PYUR': (0x1000553, u'\u0553'),
'Armenian_RA': (0x100054c, u'\u054C'),
'Armenian_RE': (0x1000550, u'\u0550'),
'Armenian_SE': (0x100054d, u'\u054D'),
'Armenian_SHA': (0x1000547, u'\u0547'),
'Armenian_TCHE': (0x1000543, u'\u0543'),
'Armenian_TO': (0x1000539, u'\u0539'),
'Armenian_TSA': (0x100053e, u'\u053E'),
'Armenian_TSO': (0x1000551, u'\u0551'),
'Armenian_TYUN': (0x100054f, u'\u054F'),
'Armenian_VEV': (0x100054e, u'\u054E'),
'Armenian_VO': (0x1000548, u'\u0548'),
'Armenian_VYUN': (0x1000552, u'\u0552'),
'Armenian_YECH': (0x1000535, u'\u0535'),
'Armenian_ZA': (0x1000536, u'\u0536'),
'Armenian_ZHE': (0x100053a, u'\u053A'),
'Armenian_accent': (0x100055b, u'\u055B'),
'Armenian_amanak': (0x100055c, u'\u055C'),
'Armenian_apostrophe': (0x100055a, u'\u055A'),
'Armenian_at': (0x1000568, u'\u0568'),
'Armenian_ayb': (0x1000561, u'\u0561'),
'Armenian_ben': (0x1000562, u'\u0562'),
'Armenian_but': (0x100055d, u'\u055D'),
'Armenian_cha': (0x1000579, u'\u0579'),
'Armenian_da': (0x1000564, u'\u0564'),
'Armenian_dza': (0x1000571, u'\u0571'),
'Armenian_e': (0x1000567, u'\u0567'),
'Armenian_exclam': (0x100055c, u'\u055C'),
'Armenian_fe': (0x1000586, u'\u0586'),
'Armenian_full_stop': (0x1000589, u'\u0589'),
'Armenian_ghat': (0x1000572, u'\u0572'),
'Armenian_gim': (0x1000563, u'\u0563'),
'Armenian_hi': (0x1000575, u'\u0575'),
'Armenian_ho': (0x1000570, u'\u0570'),
'Armenian_hyphen': (0x100058a, u'\u058A'),
'Armenian_ini': (0x100056b, u'\u056B'),
'Armenian_je': (0x100057b, u'\u057B'),
'Armenian_ke': (0x1000584, u'\u0584'),
'Armenian_ken': (0x100056f, u'\u056F'),
'Armenian_khe': (0x100056d, u'\u056D'),
'Armenian_ligature_ew': (0x1000587, u'\u0587'),
'Armenian_lyun': (0x100056c, u'\u056C'),
'Armenian_men': (0x1000574, u'\u0574'),
'Armenian_nu': (0x1000576, u'\u0576'),
'Armenian_o': (0x1000585, u'\u0585'),
'Armenian_paruyk': (0x100055e, u'\u055E'),
'Armenian_pe': (0x100057a, u'\u057A'),
'Armenian_pyur': (0x1000583, u'\u0583'),
'Armenian_question': (0x100055e, u'\u055E'),
'Armenian_ra': (0x100057c, u'\u057C'),
'Armenian_re': (0x1000580, u'\u0580'),
'Armenian_se': (0x100057d, u'\u057D'),
'Armenian_separation_mark': (0x100055d, u'\u055D'),
'Armenian_sha': (0x1000577, u'\u0577'),
'Armenian_shesht': (0x100055b, u'\u055B'),
'Armenian_tche': (0x1000573, u'\u0573'),
'Armenian_to': (0x1000569, u'\u0569'),
'Armenian_tsa': (0x100056e, u'\u056E'),
'Armenian_tso': (0x1000581, u'\u0581'),
'Armenian_tyun': (0x100057f, u'\u057F'),
'Armenian_verjaket': (0x1000589, u'\u0589'),
'Armenian_vev': (0x100057e, u'\u057E'),
'Armenian_vo': (0x1000578, u'\u0578'),
'Armenian_vyun': (0x1000582, u'\u0582'),
'Armenian_yech': (0x1000565, u'\u0565'),
'Armenian_yentamna': (0x100058a, u'\u058A'),
'Armenian_za': (0x1000566, u'\u0566'),
'Armenian_zhe': (0x100056a, u'\u056A'),
'Atilde': (0x00c3, u'\u00C3'),
'B': (0x0042, u'\u0042'),
'Babovedot': (0x1001e02, u'\u1E02'),
'Byelorussian_SHORTU': (0x06be, u'\u040E'),
'Byelorussian_shortu': (0x06ae, u'\u045E'),
'C': (0x0043, u'\u0043'),
'Cabovedot': (0x02c5, u'\u010A'),
'Cacute': (0x01c6, u'\u0106'),
'Ccaron': (0x01c8, u'\u010C'),
'Ccedilla': (0x00c7, u'\u00C7'),
'Ccircumflex': (0x02c6, u'\u0108'),
'ColonSign': (0x10020a1, u'\u20A1'),
'CruzeiroSign': (0x10020a2, u'\u20A2'),
'Cyrillic_A': (0x06e1, u'\u0410'),
'Cyrillic_BE': (0x06e2, u'\u0411'),
'Cyrillic_CHE': (0x06fe, u'\u0427'),
'Cyrillic_CHE_descender': (0x10004b6, u'\u04B6'),
'Cyrillic_CHE_vertstroke': (0x10004b8, u'\u04B8'),
'Cyrillic_DE': (0x06e4, u'\u0414'),
'Cyrillic_DZHE': (0x06bf, u'\u040F'),
'Cyrillic_E': (0x06fc, u'\u042D'),
'Cyrillic_EF': (0x06e6, u'\u0424'),
'Cyrillic_EL': (0x06ec, u'\u041B'),
'Cyrillic_EM': (0x06ed, u'\u041C'),
'Cyrillic_EN': (0x06ee, u'\u041D'),
'Cyrillic_EN_descender': (0x10004a2, u'\u04A2'),
'Cyrillic_ER': (0x06f2, u'\u0420'),
'Cyrillic_ES': (0x06f3, u'\u0421'),
'Cyrillic_GHE': (0x06e7, u'\u0413'),
'Cyrillic_GHE_bar': (0x1000492, u'\u0492'),
'Cyrillic_HA': (0x06e8, u'\u0425'),
'Cyrillic_HARDSIGN': (0x06ff, u'\u042A'),
'Cyrillic_HA_descender': (0x10004b2, u'\u04B2'),
'Cyrillic_I': (0x06e9, u'\u0418'),
'Cyrillic_IE': (0x06e5, u'\u0415'),
'Cyrillic_IO': (0x06b3, u'\u0401'),
'Cyrillic_I_macron': (0x10004e2, u'\u04E2'),
'Cyrillic_JE': (0x06b8, u'\u0408'),
'Cyrillic_KA': (0x06eb, u'\u041A'),
'Cyrillic_KA_descender': (0x100049a, u'\u049A'),
'Cyrillic_KA_vertstroke': (0x100049c, u'\u049C'),
'Cyrillic_LJE': (0x06b9, u'\u0409'),
'Cyrillic_NJE': (0x06ba, u'\u040A'),
'Cyrillic_O': (0x06ef, u'\u041E'),
'Cyrillic_O_bar': (0x10004e8, u'\u04E8'),
'Cyrillic_PE': (0x06f0, u'\u041F'),
'Cyrillic_SCHWA': (0x10004d8, u'\u04D8'),
'Cyrillic_SHA': (0x06fb, u'\u0428'),
'Cyrillic_SHCHA': (0x06fd, u'\u0429'),
'Cyrillic_SHHA': (0x10004ba, u'\u04BA'),
'Cyrillic_SHORTI': (0x06ea, u'\u0419'),
'Cyrillic_SOFTSIGN': (0x06f8, u'\u042C'),
'Cyrillic_TE': (0x06f4, u'\u0422'),
'Cyrillic_TSE': (0x06e3, u'\u0426'),
'Cyrillic_U': (0x06f5, u'\u0423'),
'Cyrillic_U_macron': (0x10004ee, u'\u04EE'),
'Cyrillic_U_straight': (0x10004ae, u'\u04AE'),
'Cyrillic_U_straight_bar': (0x10004b0, u'\u04B0'),
'Cyrillic_VE': (0x06f7, u'\u0412'),
'Cyrillic_YA': (0x06f1, u'\u042F'),
'Cyrillic_YERU': (0x06f9, u'\u042B'),
'Cyrillic_YU': (0x06e0, u'\u042E'),
'Cyrillic_ZE': (0x06fa, u'\u0417'),
'Cyrillic_ZHE': (0x06f6, u'\u0416'),
'Cyrillic_ZHE_descender': (0x1000496, u'\u0496'),
'Cyrillic_a': (0x06c1, u'\u0430'),
'Cyrillic_be': (0x06c2, u'\u0431'),
'Cyrillic_che': (0x06de, u'\u0447'),
'Cyrillic_che_descender': (0x10004b7, u'\u04B7'),
'Cyrillic_che_vertstroke': (0x10004b9, u'\u04B9'),
'Cyrillic_de': (0x06c4, u'\u0434'),
'Cyrillic_dzhe': (0x06af, u'\u045F'),
'Cyrillic_e': (0x06dc, u'\u044D'),
'Cyrillic_ef': (0x06c6, u'\u0444'),
'Cyrillic_el': (0x06cc, u'\u043B'),
'Cyrillic_em': (0x06cd, u'\u043C'),
'Cyrillic_en': (0x06ce, u'\u043D'),
'Cyrillic_en_descender': (0x10004a3, u'\u04A3'),
'Cyrillic_er': (0x06d2, u'\u0440'),
'Cyrillic_es': (0x06d3, u'\u0441'),
'Cyrillic_ghe': (0x06c7, u'\u0433'),
'Cyrillic_ghe_bar': (0x1000493, u'\u0493'),
'Cyrillic_ha': (0x06c8, u'\u0445'),
'Cyrillic_ha_descender': (0x10004b3, u'\u04B3'),
'Cyrillic_hardsign': (0x06df, u'\u044A'),
'Cyrillic_i': (0x06c9, u'\u0438'),
'Cyrillic_i_macron': (0x10004e3, u'\u04E3'),
'Cyrillic_ie': (0x06c5, u'\u0435'),
'Cyrillic_io': (0x06a3, u'\u0451'),
'Cyrillic_je': (0x06a8, u'\u0458'),
'Cyrillic_ka': (0x06cb, u'\u043A'),
'Cyrillic_ka_descender': (0x100049b, u'\u049B'),
'Cyrillic_ka_vertstroke': (0x100049d, u'\u049D'),
'Cyrillic_lje': (0x06a9, u'\u0459'),
'Cyrillic_nje': (0x06aa, u'\u045A'),
'Cyrillic_o': (0x06cf, u'\u043E'),
'Cyrillic_o_bar': (0x10004e9, u'\u04E9'),
'Cyrillic_pe': (0x06d0, u'\u043F'),
'Cyrillic_schwa': (0x10004d9, u'\u04D9'),
'Cyrillic_sha': (0x06db, u'\u0448'),
'Cyrillic_shcha': (0x06dd, u'\u0449'),
'Cyrillic_shha': (0x10004bb, u'\u04BB'),
'Cyrillic_shorti': (0x06ca, u'\u0439'),
'Cyrillic_softsign': (0x06d8, u'\u044C'),
'Cyrillic_te': (0x06d4, u'\u0442'),
'Cyrillic_tse': (0x06c3, u'\u0446'),
'Cyrillic_u': (0x06d5, u'\u0443'),
'Cyrillic_u_macron': (0x10004ef, u'\u04EF'),
'Cyrillic_u_straight': (0x10004af, u'\u04AF'),
'Cyrillic_u_straight_bar': (0x10004b1, u'\u04B1'),
'Cyrillic_ve': (0x06d7, u'\u0432'),
'Cyrillic_ya': (0x06d1, u'\u044F'),
'Cyrillic_yeru': (0x06d9, u'\u044B'),
'Cyrillic_yu': (0x06c0, u'\u044E'),
'Cyrillic_ze': (0x06da, u'\u0437'),
'Cyrillic_zhe': (0x06d6, u'\u0436'),
'Cyrillic_zhe_descender': (0x1000497, u'\u0497'),
'D': (0x0044, u'\u0044'),
'Dabovedot': (0x1001e0a, u'\u1E0A'),
'Dcaron': (0x01cf, u'\u010E'),
'DongSign': (0x10020ab, u'\u20AB'),
'Dstroke': (0x01d0, u'\u0110'),
'E': (0x0045, u'\u0045'),
'ENG': (0x03bd, u'\u014A'),
'ETH': (0x00d0, u'\u00D0'),
'EZH': (0x10001b7, u'\u01B7'),
'Eabovedot': (0x03cc, u'\u0116'),
'Eacute': (0x00c9, u'\u00C9'),
'Ebelowdot': (0x1001eb8, u'\u1EB8'),
'Ecaron': (0x01cc, u'\u011A'),
'Ecircumflex': (0x00ca, u'\u00CA'),
'Ecircumflexacute': (0x1001ebe, u'\u1EBE'),
'Ecircumflexbelowdot': (0x1001ec6, u'\u1EC6'),
'Ecircumflexgrave': (0x1001ec0, u'\u1EC0'),
'Ecircumflexhook': (0x1001ec2, u'\u1EC2'),
'Ecircumflextilde': (0x1001ec4, u'\u1EC4'),
'EcuSign': (0x10020a0, u'\u20A0'),
'Ediaeresis': (0x00cb, u'\u00CB'),
'Egrave': (0x00c8, u'\u00C8'),
'Ehook': (0x1001eba, u'\u1EBA'),
'Emacron': (0x03aa, u'\u0112'),
'Eogonek': (0x01ca, u'\u0118'),
'Etilde': (0x1001ebc, u'\u1EBC'),
'EuroSign': (0x20ac, u'\u20AC'),
'F': (0x0046, u'\u0046'),
'FFrancSign': (0x10020a3, u'\u20A3'),
'Fabovedot': (0x1001e1e, u'\u1E1E'),
'Farsi_0': (0x10006f0, u'\u06F0'),
'Farsi_1': (0x10006f1, u'\u06F1'),
'Farsi_2': (0x10006f2, u'\u06F2'),
'Farsi_3': (0x10006f3, u'\u06F3'),
'Farsi_4': (0x10006f4, u'\u06F4'),
'Farsi_5': (0x10006f5, u'\u06F5'),
'Farsi_6': (0x10006f6, u'\u06F6'),
'Farsi_7': (0x10006f7, u'\u06F7'),
'Farsi_8': (0x10006f8, u'\u06F8'),
'Farsi_9': (0x10006f9, u'\u06F9'),
'Farsi_yeh': (0x10006cc, u'\u06CC'),
'G': (0x0047, u'\u0047'),
'Gabovedot': (0x02d5, u'\u0120'),
'Gbreve': (0x02ab, u'\u011E'),
'Gcaron': (0x10001e6, u'\u01E6'),
'Gcedilla': (0x03ab, u'\u0122'),
'Gcircumflex': (0x02d8, u'\u011C'),
'Georgian_an': (0x10010d0, u'\u10D0'),
'Georgian_ban': (0x10010d1, u'\u10D1'),
'Georgian_can': (0x10010ea, u'\u10EA'),
'Georgian_char': (0x10010ed, u'\u10ED'),
'Georgian_chin': (0x10010e9, u'\u10E9'),
'Georgian_cil': (0x10010ec, u'\u10EC'),
'Georgian_don': (0x10010d3, u'\u10D3'),
'Georgian_en': (0x10010d4, u'\u10D4'),
'Georgian_fi': (0x10010f6, u'\u10F6'),
'Georgian_gan': (0x10010d2, u'\u10D2'),
'Georgian_ghan': (0x10010e6, u'\u10E6'),
'Georgian_hae': (0x10010f0, u'\u10F0'),
'Georgian_har': (0x10010f4, u'\u10F4'),
'Georgian_he': (0x10010f1, u'\u10F1'),
'Georgian_hie': (0x10010f2, u'\u10F2'),
'Georgian_hoe': (0x10010f5, u'\u10F5'),
'Georgian_in': (0x10010d8, u'\u10D8'),
'Georgian_jhan': (0x10010ef, u'\u10EF'),
'Georgian_jil': (0x10010eb, u'\u10EB'),
'Georgian_kan': (0x10010d9, u'\u10D9'),
'Georgian_khar': (0x10010e5, u'\u10E5'),
'Georgian_las': (0x10010da, u'\u10DA'),
'Georgian_man': (0x10010db, u'\u10DB'),
'Georgian_nar': (0x10010dc, u'\u10DC'),
'Georgian_on': (0x10010dd, u'\u10DD'),
'Georgian_par': (0x10010de, u'\u10DE'),
'Georgian_phar': (0x10010e4, u'\u10E4'),
'Georgian_qar': (0x10010e7, u'\u10E7'),
'Georgian_rae': (0x10010e0, u'\u10E0'),
'Georgian_san': (0x10010e1, u'\u10E1'),
'Georgian_shin': (0x10010e8, u'\u10E8'),
'Georgian_tan': (0x10010d7, u'\u10D7'),
'Georgian_tar': (0x10010e2, u'\u10E2'),
'Georgian_un': (0x10010e3, u'\u10E3'),
'Georgian_vin': (0x10010d5, u'\u10D5'),
'Georgian_we': (0x10010f3, u'\u10F3'),
'Georgian_xan': (0x10010ee, u'\u10EE'),
'Georgian_zen': (0x10010d6, u'\u10D6'),
'Georgian_zhar': (0x10010df, u'\u10DF'),
'Greek_ALPHA': (0x07c1, u'\u0391'),
'Greek_ALPHAaccent': (0x07a1, u'\u0386'),
'Greek_BETA': (0x07c2, u'\u0392'),
'Greek_CHI': (0x07d7, u'\u03A7'),
'Greek_DELTA': (0x07c4, u'\u0394'),
'Greek_EPSILON': (0x07c5, u'\u0395'),
'Greek_EPSILONaccent': (0x07a2, u'\u0388'),
'Greek_ETA': (0x07c7, u'\u0397'),
'Greek_ETAaccent': (0x07a3, u'\u0389'),
'Greek_GAMMA': (0x07c3, u'\u0393'),
'Greek_IOTA': (0x07c9, u'\u0399'),
'Greek_IOTAaccent': (0x07a4, u'\u038A'),
'Greek_IOTAdieresis': (0x07a5, u'\u03AA'),
'Greek_KAPPA': (0x07ca, u'\u039A'),
'Greek_LAMBDA': (0x07cb, u'\u039B'),
'Greek_LAMDA': (0x07cb, u'\u039B'),
'Greek_MU': (0x07cc, u'\u039C'),
'Greek_NU': (0x07cd, u'\u039D'),
'Greek_OMEGA': (0x07d9, u'\u03A9'),
'Greek_OMEGAaccent': (0x07ab, u'\u038F'),
'Greek_OMICRON': (0x07cf, u'\u039F'),
'Greek_OMICRONaccent': (0x07a7, u'\u038C'),
'Greek_PHI': (0x07d6, u'\u03A6'),
'Greek_PI': (0x07d0, u'\u03A0'),
'Greek_PSI': (0x07d8, u'\u03A8'),
'Greek_RHO': (0x07d1, u'\u03A1'),
'Greek_SIGMA': (0x07d2, u'\u03A3'),
'Greek_TAU': (0x07d4, u'\u03A4'),
'Greek_THETA': (0x07c8, u'\u0398'),
'Greek_UPSILON': (0x07d5, u'\u03A5'),
'Greek_UPSILONaccent': (0x07a8, u'\u038E'),
'Greek_UPSILONdieresis': (0x07a9, u'\u03AB'),
'Greek_XI': (0x07ce, u'\u039E'),
'Greek_ZETA': (0x07c6, u'\u0396'),
'Greek_accentdieresis': (0x07ae, u'\u0385'),
'Greek_alpha': (0x07e1, u'\u03B1'),
'Greek_alphaaccent': (0x07b1, u'\u03AC'),
'Greek_beta': (0x07e2, u'\u03B2'),
'Greek_chi': (0x07f7, u'\u03C7'),
'Greek_delta': (0x07e4, u'\u03B4'),
'Greek_epsilon': (0x07e5, u'\u03B5'),
'Greek_epsilonaccent': (0x07b2, u'\u03AD'),
'Greek_eta': (0x07e7, u'\u03B7'),
'Greek_etaaccent': (0x07b3, u'\u03AE'),
'Greek_finalsmallsigma': (0x07f3, u'\u03C2'),
'Greek_gamma': (0x07e3, u'\u03B3'),
'Greek_horizbar': (0x07af, u'\u2015'),
'Greek_iota': (0x07e9, u'\u03B9'),
'Greek_iotaaccent': (0x07b4, u'\u03AF'),
'Greek_iotaaccentdieresis': (0x07b6, u'\u0390'),
'Greek_iotadieresis': (0x07b5, u'\u03CA'),
'Greek_kappa': (0x07ea, u'\u03BA'),
'Greek_lambda': (0x07eb, u'\u03BB'),
'Greek_lamda': (0x07eb, u'\u03BB'),
'Greek_mu': (0x07ec, u'\u03BC'),
'Greek_nu': (0x07ed, u'\u03BD'),
'Greek_omega': (0x07f9, u'\u03C9'),
'Greek_omegaaccent': (0x07bb, u'\u03CE'),
'Greek_omicron': (0x07ef, u'\u03BF'),
'Greek_omicronaccent': (0x07b7, u'\u03CC'),
'Greek_phi': (0x07f6, u'\u03C6'),
'Greek_pi': (0x07f0, u'\u03C0'),
'Greek_psi': (0x07f8, u'\u03C8'),
'Greek_rho': (0x07f1, u'\u03C1'),
'Greek_sigma': (0x07f2, u'\u03C3'),
'Greek_tau': (0x07f4, u'\u03C4'),
'Greek_theta': (0x07e8, u'\u03B8'),
'Greek_upsilon': (0x07f5, u'\u03C5'),
'Greek_upsilonaccent': (0x07b8, u'\u03CD'),
'Greek_upsilonaccentdieresis': (0x07ba, u'\u03B0'),
'Greek_upsilondieresis': (0x07b9, u'\u03CB'),
'Greek_xi': (0x07ee, u'\u03BE'),
'Greek_zeta': (0x07e6, u'\u03B6'),
'H': (0x0048, u'\u0048'),
'Hcircumflex': (0x02a6, u'\u0124'),
'Hstroke': (0x02a1, u'\u0126'),
'I': (0x0049, u'\u0049'),
'Iabovedot': (0x02a9, u'\u0130'),
'Iacute': (0x00cd, u'\u00CD'),
'Ibelowdot': (0x1001eca, u'\u1ECA'),
'Ibreve': (0x100012c, u'\u012C'),
'Icircumflex': (0x00ce, u'\u00CE'),
'Idiaeresis': (0x00cf, u'\u00CF'),
'Igrave': (0x00cc, u'\u00CC'),
'Ihook': (0x1001ec8, u'\u1EC8'),
'Imacron': (0x03cf, u'\u012A'),
'Iogonek': (0x03c7, u'\u012E'),
'Itilde': (0x03a5, u'\u0128'),
'J': (0x004a, u'\u004A'),
'Jcircumflex': (0x02ac, u'\u0134'),
'K': (0x004b, u'\u004B'),
'KP_0': (0xffb0, None),
'KP_1': (0xffb1, None),
'KP_2': (0xffb2, None),
'KP_3': (0xffb3, None),
'KP_4': (0xffb4, None),
'KP_5': (0xffb5, None),
'KP_6': (0xffb6, None),
'KP_7': (0xffb7, None),
'KP_8': (0xffb8, None),
'KP_9': (0xffb9, None),
'KP_Add': (0xffab, None),
'KP_Begin': (0xff9d, None),
'KP_Decimal': (0xffae, None),
'KP_Delete': (0xff9f, None),
'KP_Divide': (0xffaf, None),
'KP_Down': (0xff99, None),
'KP_End': (0xff9c, None),
'KP_Enter': (0xff8d, None),
'KP_Equal': (0xffbd, None),
'KP_F1': (0xff91, None),
'KP_F2': (0xff92, None),
'KP_F3': (0xff93, None),
'KP_F4': (0xff94, None),
'KP_Home': (0xff95, None),
'KP_Insert': (0xff9e, None),
'KP_Left': (0xff96, None),
'KP_Multiply': (0xffaa, None),
'KP_Next': (0xff9b, None),
'KP_Page_Down': (0xff9b, None),
'KP_Page_Up': (0xff9a, None),
'KP_Prior': (0xff9a, None),
'KP_Right': (0xff98, None),
'KP_Separator': (0xffac, None),
'KP_Space': (0xff80, None),
'KP_Subtract': (0xffad, None),
'KP_Tab': (0xff89, None),
'KP_Up': (0xff97, None),
'Kcedilla': (0x03d3, u'\u0136'),
'L': (0x004c, u'\u004C'),
'Lacute': (0x01c5, u'\u0139'),
'Lbelowdot': (0x1001e36, u'\u1E36'),
'Lcaron': (0x01a5, u'\u013D'),
'Lcedilla': (0x03a6, u'\u013B'),
'LiraSign': (0x10020a4, u'\u20A4'),
'Lstroke': (0x01a3, u'\u0141'),
'M': (0x004d, u'\u004D'),
'Mabovedot': (0x1001e40, u'\u1E40'),
'Macedonia_DSE': (0x06b5, u'\u0405'),
'Macedonia_GJE': (0x06b2, u'\u0403'),
'Macedonia_KJE': (0x06bc, u'\u040C'),
'Macedonia_dse': (0x06a5, u'\u0455'),
'Macedonia_gje': (0x06a2, u'\u0453'),
'Macedonia_kje': (0x06ac, u'\u045C'),
'MillSign': (0x10020a5, u'\u20A5'),
'N': (0x004e, u'\u004E'),
'Nacute': (0x01d1, u'\u0143'),
'NairaSign': (0x10020a6, u'\u20A6'),
'Ncaron': (0x01d2, u'\u0147'),
'Ncedilla': (0x03d1, u'\u0145'),
'NewSheqelSign': (0x10020aa, u'\u20AA'),
'Ntilde': (0x00d1, u'\u00D1'),
'O': (0x004f, u'\u004F'),
'OE': (0x13bc, u'\u0152'),
'Oacute': (0x00d3, u'\u00D3'),
'Obarred': (0x100019f, u'\u019F'),
'Obelowdot': (0x1001ecc, u'\u1ECC'),
'Ocaron': (0x10001d1, u'\u01D2'),
'Ocircumflex': (0x00d4, u'\u00D4'),
'Ocircumflexacute': (0x1001ed0, u'\u1ED0'),
'Ocircumflexbelowdot': (0x1001ed8, u'\u1ED8'),
'Ocircumflexgrave': (0x1001ed2, u'\u1ED2'),
'Ocircumflexhook': (0x1001ed4, u'\u1ED4'),
'Ocircumflextilde': (0x1001ed6, u'\u1ED6'),
'Odiaeresis': (0x00d6, u'\u00D6'),
'Odoubleacute': (0x01d5, u'\u0150'),
'Ograve': (0x00d2, u'\u00D2'),
'Ohook': (0x1001ece, u'\u1ECE'),
'Ohorn': (0x10001a0, u'\u01A0'),
'Ohornacute': (0x1001eda, u'\u1EDA'),
'Ohornbelowdot': (0x1001ee2, u'\u1EE2'),
'Ohorngrave': (0x1001edc, u'\u1EDC'),
'Ohornhook': (0x1001ede, u'\u1EDE'),
'Ohorntilde': (0x1001ee0, u'\u1EE0'),
'Omacron': (0x03d2, u'\u014C'),
'Ooblique': (0x00d8, u'\u00D8'),
'Oslash': (0x00d8, u'\u00D8'),
'Otilde': (0x00d5, u'\u00D5'),
'P': (0x0050, u'\u0050'),
'Pabovedot': (0x1001e56, u'\u1E56'),
'PesetaSign': (0x10020a7, u'\u20A7'),
'Q': (0x0051, u'\u0051'),
'R': (0x0052, u'\u0052'),
'Racute': (0x01c0, u'\u0154'),
'Rcaron': (0x01d8, u'\u0158'),
'Rcedilla': (0x03a3, u'\u0156'),
'RupeeSign': (0x10020a8, u'\u20A8'),
'S': (0x0053, u'\u0053'),
'SCHWA': (0x100018f, u'\u018F'),
'Sabovedot': (0x1001e60, u'\u1E60'),
'Sacute': (0x01a6, u'\u015A'),
'Scaron': (0x01a9, u'\u0160'),
'Scedilla': (0x01aa, u'\u015E'),
'Scircumflex': (0x02de, u'\u015C'),
'Serbian_DJE': (0x06b1, u'\u0402'),
'Serbian_TSHE': (0x06bb, u'\u040B'),
'Serbian_dje': (0x06a1, u'\u0452'),
'Serbian_tshe': (0x06ab, u'\u045B'),
'Sinh_a': (0x1000d85, u'\u0D85'),
'Sinh_aa': (0x1000d86, u'\u0D86'),
'Sinh_aa2': (0x1000dcf, u'\u0DCF'),
'Sinh_ae': (0x1000d87, u'\u0D87'),
'Sinh_ae2': (0x1000dd0, u'\u0DD0'),
'Sinh_aee': (0x1000d88, u'\u0D88'),
'Sinh_aee2': (0x1000dd1, u'\u0DD1'),
'Sinh_ai': (0x1000d93, u'\u0D93'),
'Sinh_ai2': (0x1000ddb, u'\u0DDB'),
'Sinh_al': (0x1000dca, u'\u0DCA'),
'Sinh_au': (0x1000d96, u'\u0D96'),
'Sinh_au2': (0x1000dde, u'\u0DDE'),
'Sinh_ba': (0x1000db6, u'\u0DB6'),
'Sinh_bha': (0x1000db7, u'\u0DB7'),
'Sinh_ca': (0x1000da0, u'\u0DA0'),
'Sinh_cha': (0x1000da1, u'\u0DA1'),
'Sinh_dda': (0x1000da9, u'\u0DA9'),
'Sinh_ddha': (0x1000daa, u'\u0DAA'),
'Sinh_dha': (0x1000daf, u'\u0DAF'),
'Sinh_dhha': (0x1000db0, u'\u0DB0'),
'Sinh_e': (0x1000d91, u'\u0D91'),
'Sinh_e2': (0x1000dd9, u'\u0DD9'),
'Sinh_ee': (0x1000d92, u'\u0D92'),
'Sinh_ee2': (0x1000dda, u'\u0DDA'),
'Sinh_fa': (0x1000dc6, u'\u0DC6'),
'Sinh_ga': (0x1000d9c, u'\u0D9C'),
'Sinh_gha': (0x1000d9d, u'\u0D9D'),
'Sinh_h2': (0x1000d83, u'\u0D83'),
'Sinh_ha': (0x1000dc4, u'\u0DC4'),
'Sinh_i': (0x1000d89, u'\u0D89'),
'Sinh_i2': (0x1000dd2, u'\u0DD2'),
'Sinh_ii': (0x1000d8a, u'\u0D8A'),
'Sinh_ii2': (0x1000dd3, u'\u0DD3'),
'Sinh_ja': (0x1000da2, u'\u0DA2'),
'Sinh_jha': (0x1000da3, u'\u0DA3'),
'Sinh_jnya': (0x1000da5, u'\u0DA5'),
'Sinh_ka': (0x1000d9a, u'\u0D9A'),
'Sinh_kha': (0x1000d9b, u'\u0D9B'),
'Sinh_kunddaliya': (0x1000df4, u'\u0DF4'),
'Sinh_la': (0x1000dbd, u'\u0DBD'),
'Sinh_lla': (0x1000dc5, u'\u0DC5'),
'Sinh_lu': (0x1000d8f, u'\u0D8F'),
'Sinh_lu2': (0x1000ddf, u'\u0DDF'),
'Sinh_luu': (0x1000d90, u'\u0D90'),
'Sinh_luu2': (0x1000df3, u'\u0DF3'),
'Sinh_ma': (0x1000db8, u'\u0DB8'),
'Sinh_mba': (0x1000db9, u'\u0DB9'),
'Sinh_na': (0x1000db1, u'\u0DB1'),
'Sinh_ndda': (0x1000dac, u'\u0DAC'),
'Sinh_ndha': (0x1000db3, u'\u0DB3'),
'Sinh_ng': (0x1000d82, u'\u0D82'),
'Sinh_ng2': (0x1000d9e, u'\u0D9E'),
'Sinh_nga': (0x1000d9f, u'\u0D9F'),
'Sinh_nja': (0x1000da6, u'\u0DA6'),
'Sinh_nna': (0x1000dab, u'\u0DAB'),
'Sinh_nya': (0x1000da4, u'\u0DA4'),
'Sinh_o': (0x1000d94, u'\u0D94'),
'Sinh_o2': (0x1000ddc, u'\u0DDC'),
'Sinh_oo': (0x1000d95, u'\u0D95'),
'Sinh_oo2': (0x1000ddd, u'\u0DDD'),
'Sinh_pa': (0x1000db4, u'\u0DB4'),
'Sinh_pha': (0x1000db5, u'\u0DB5'),
'Sinh_ra': (0x1000dbb, u'\u0DBB'),
'Sinh_ri': (0x1000d8d, u'\u0D8D'),
'Sinh_rii': (0x1000d8e, u'\u0D8E'),
'Sinh_ru2': (0x1000dd8, u'\u0DD8'),
'Sinh_ruu2': (0x1000df2, u'\u0DF2'),
'Sinh_sa': (0x1000dc3, u'\u0DC3'),
'Sinh_sha': (0x1000dc1, u'\u0DC1'),
'Sinh_ssha': (0x1000dc2, u'\u0DC2'),
'Sinh_tha': (0x1000dad, u'\u0DAD'),
'Sinh_thha': (0x1000dae, u'\u0DAE'),
'Sinh_tta': (0x1000da7, u'\u0DA7'),
'Sinh_ttha': (0x1000da8, u'\u0DA8'),
'Sinh_u': (0x1000d8b, u'\u0D8B'),
'Sinh_u2': (0x1000dd4, u'\u0DD4'),
'Sinh_uu': (0x1000d8c, u'\u0D8C'),
'Sinh_uu2': (0x1000dd6, u'\u0DD6'),
'Sinh_va': (0x1000dc0, u'\u0DC0'),
'Sinh_ya': (0x1000dba, u'\u0DBA'),
'T': (0x0054, u'\u0054'),
'THORN': (0x00de, u'\u00DE'),
'Tabovedot': (0x1001e6a, u'\u1E6A'),
'Tcaron': (0x01ab, u'\u0164'),
'Tcedilla': (0x01de, u'\u0162'),
'Thai_baht': (0x0ddf, u'\u0E3F'),
'Thai_bobaimai': (0x0dba, u'\u0E1A'),
'Thai_chochan': (0x0da8, u'\u0E08'),
'Thai_chochang': (0x0daa, u'\u0E0A'),
'Thai_choching': (0x0da9, u'\u0E09'),
'Thai_chochoe': (0x0dac, u'\u0E0C'),
'Thai_dochada': (0x0dae, u'\u0E0E'),
'Thai_dodek': (0x0db4, u'\u0E14'),
'Thai_fofa': (0x0dbd, u'\u0E1D'),
'Thai_fofan': (0x0dbf, u'\u0E1F'),
'Thai_hohip': (0x0dcb, u'\u0E2B'),
'Thai_honokhuk': (0x0dce, u'\u0E2E'),
'Thai_khokhai': (0x0da2, u'\u0E02'),
'Thai_khokhon': (0x0da5, u'\u0E05'),
'Thai_khokhuat': (0x0da3, u'\u0E03'),
'Thai_khokhwai': (0x0da4, u'\u0E04'),
'Thai_khorakhang': (0x0da6, u'\u0E06'),
'Thai_kokai': (0x0da1, u'\u0E01'),
'Thai_lakkhangyao': (0x0de5, u'\u0E45'),
'Thai_lekchet': (0x0df7, u'\u0E57'),
'Thai_lekha': (0x0df5, u'\u0E55'),
'Thai_lekhok': (0x0df6, u'\u0E56'),
'Thai_lekkao': (0x0df9, u'\u0E59'),
'Thai_leknung': (0x0df1, u'\u0E51'),
'Thai_lekpaet': (0x0df8, u'\u0E58'),
'Thai_leksam': (0x0df3, u'\u0E53'),
'Thai_leksi': (0x0df4, u'\u0E54'),
'Thai_leksong': (0x0df2, u'\u0E52'),
'Thai_leksun': (0x0df0, u'\u0E50'),
'Thai_lochula': (0x0dcc, u'\u0E2C'),
'Thai_loling': (0x0dc5, u'\u0E25'),
'Thai_lu': (0x0dc6, u'\u0E26'),
'Thai_maichattawa': (0x0deb, u'\u0E4B'),
'Thai_maiek': (0x0de8, u'\u0E48'),
'Thai_maihanakat': (0x0dd1, u'\u0E31'),
'Thai_maitaikhu': (0x0de7, u'\u0E47'),
'Thai_maitho': (0x0de9, u'\u0E49'),
'Thai_maitri': (0x0dea, u'\u0E4A'),
'Thai_maiyamok': (0x0de6, u'\u0E46'),
'Thai_moma': (0x0dc1, u'\u0E21'),
'Thai_ngongu': (0x0da7, u'\u0E07'),
'Thai_nikhahit': (0x0ded, u'\u0E4D'),
'Thai_nonen': (0x0db3, u'\u0E13'),
'Thai_nonu': (0x0db9, u'\u0E19'),
'Thai_oang': (0x0dcd, u'\u0E2D'),
'Thai_paiyannoi': (0x0dcf, u'\u0E2F'),
'Thai_phinthu': (0x0dda, u'\u0E3A'),
'Thai_phophan': (0x0dbe, u'\u0E1E'),
'Thai_phophung': (0x0dbc, u'\u0E1C'),
'Thai_phosamphao': (0x0dc0, u'\u0E20'),
'Thai_popla': (0x0dbb, u'\u0E1B'),
'Thai_rorua': (0x0dc3, u'\u0E23'),
'Thai_ru': (0x0dc4, u'\u0E24'),
'Thai_saraa': (0x0dd0, u'\u0E30'),
'Thai_saraaa': (0x0dd2, u'\u0E32'),
'Thai_saraae': (0x0de1, u'\u0E41'),
'Thai_saraaimaimalai': (0x0de4, u'\u0E44'),
'Thai_saraaimaimuan': (0x0de3, u'\u0E43'),
'Thai_saraam': (0x0dd3, u'\u0E33'),
'Thai_sarae': (0x0de0, u'\u0E40'),
'Thai_sarai': (0x0dd4, u'\u0E34'),
'Thai_saraii': (0x0dd5, u'\u0E35'),
'Thai_sarao': (0x0de2, u'\u0E42'),
'Thai_sarau': (0x0dd8, u'\u0E38'),
'Thai_saraue': (0x0dd6, u'\u0E36'),
'Thai_sarauee': (0x0dd7, u'\u0E37'),
'Thai_sarauu': (0x0dd9, u'\u0E39'),
'Thai_sorusi': (0x0dc9, u'\u0E29'),
'Thai_sosala': (0x0dc8, u'\u0E28'),
'Thai_soso': (0x0dab, u'\u0E0B'),
'Thai_sosua': (0x0dca, u'\u0E2A'),
'Thai_thanthakhat': (0x0dec, u'\u0E4C'),
'Thai_thonangmontho': (0x0db1, u'\u0E11'),
'Thai_thophuthao': (0x0db2, u'\u0E12'),
'Thai_thothahan': (0x0db7, u'\u0E17'),
'Thai_thothan': (0x0db0, u'\u0E10'),
'Thai_thothong': (0x0db8, u'\u0E18'),
'Thai_thothung': (0x0db6, u'\u0E16'),
'Thai_topatak': (0x0daf, u'\u0E0F'),
'Thai_totao': (0x0db5, u'\u0E15'),
'Thai_wowaen': (0x0dc7, u'\u0E27'),
'Thai_yoyak': (0x0dc2, u'\u0E22'),
'Thai_yoying': (0x0dad, u'\u0E0D'),
'Tslash': (0x03ac, u'\u0166'),
'U': (0x0055, u'\u0055'),
'Uacute': (0x00da, u'\u00DA'),
'Ubelowdot': (0x1001ee4, u'\u1EE4'),
'Ubreve': (0x02dd, u'\u016C'),
'Ucircumflex': (0x00db, u'\u00DB'),
'Udiaeresis': (0x00dc, u'\u00DC'),
'Udoubleacute': (0x01db, u'\u0170'),
'Ugrave': (0x00d9, u'\u00D9'),
'Uhook': (0x1001ee6, u'\u1EE6'),
'Uhorn': (0x10001af, u'\u01AF'),
'Uhornacute': (0x1001ee8, u'\u1EE8'),
'Uhornbelowdot': (0x1001ef0, u'\u1EF0'),
'Uhorngrave': (0x1001eea, u'\u1EEA'),
'Uhornhook': (0x1001eec, u'\u1EEC'),
'Uhorntilde': (0x1001eee, u'\u1EEE'),
'Ukrainian_GHE_WITH_UPTURN': (0x06bd, u'\u0490'),
'Ukrainian_I': (0x06b6, u'\u0406'),
'Ukrainian_IE': (0x06b4, u'\u0404'),
'Ukrainian_YI': (0x06b7, u'\u0407'),
'Ukrainian_ghe_with_upturn': (0x06ad, u'\u0491'),
'Ukrainian_i': (0x06a6, u'\u0456'),
'Ukrainian_ie': (0x06a4, u'\u0454'),
'Ukrainian_yi': (0x06a7, u'\u0457'),
'Umacron': (0x03de, u'\u016A'),
'Uogonek': (0x03d9, u'\u0172'),
'Uring': (0x01d9, u'\u016E'),
'Utilde': (0x03dd, u'\u0168'),
'V': (0x0056, u'\u0056'),
'W': (0x0057, u'\u0057'),
'Wacute': (0x1001e82, u'\u1E82'),
'Wcircumflex': (0x1000174, u'\u0174'),
'Wdiaeresis': (0x1001e84, u'\u1E84'),
'Wgrave': (0x1001e80, u'\u1E80'),
'WonSign': (0x10020a9, u'\u20A9'),
'X': (0x0058, u'\u0058'),
'Xabovedot': (0x1001e8a, u'\u1E8A'),
'Y': (0x0059, u'\u0059'),
'Yacute': (0x00dd, u'\u00DD'),
'Ybelowdot': (0x1001ef4, u'\u1EF4'),
'Ycircumflex': (0x1000176, u'\u0176'),
'Ydiaeresis': (0x13be, u'\u0178'),
'Ygrave': (0x1001ef2, u'\u1EF2'),
'Yhook': (0x1001ef6, u'\u1EF6'),
'Ytilde': (0x1001ef8, u'\u1EF8'),
'Z': (0x005a, u'\u005A'),
'Zabovedot': (0x01af, u'\u017B'),
'Zacute': (0x01ac, u'\u0179'),
'Zcaron': (0x01ae, u'\u017D'),
'Zstroke': (0x10001b5, u'\u01B5'),
'a': (0x0061, u'\u0061'),
'aacute': (0x00e1, u'\u00E1'),
'abelowdot': (0x1001ea1, u'\u1EA1'),
'abovedot': (0x01ff, u'\u02D9'),
'abreve': (0x01e3, u'\u0103'),
'abreveacute': (0x1001eaf, u'\u1EAF'),
'abrevebelowdot': (0x1001eb7, u'\u1EB7'),
'abrevegrave': (0x1001eb1, u'\u1EB1'),
'abrevehook': (0x1001eb3, u'\u1EB3'),
'abrevetilde': (0x1001eb5, u'\u1EB5'),
'acircumflex': (0x00e2, u'\u00E2'),
'acircumflexacute': (0x1001ea5, u'\u1EA5'),
'acircumflexbelowdot': (0x1001ead, u'\u1EAD'),
'acircumflexgrave': (0x1001ea7, u'\u1EA7'),
'acircumflexhook': (0x1001ea9, u'\u1EA9'),
'acircumflextilde': (0x1001eab, u'\u1EAB'),
'acute': (0x00b4, u'\u00B4'),
'adiaeresis': (0x00e4, u'\u00E4'),
'ae': (0x00e6, u'\u00E6'),
'agrave': (0x00e0, u'\u00E0'),
'ahook': (0x1001ea3, u'\u1EA3'),
'amacron': (0x03e0, u'\u0101'),
'ampersand': (0x0026, u'\u0026'),
'aogonek': (0x01b1, u'\u0105'),
'apostrophe': (0x0027, u'\u0027'),
'approxeq': (0x1002248, u'\u2245'),
'approximate': (0x08c8, u'\u223C'),
'aring': (0x00e5, u'\u00E5'),
'asciicircum': (0x005e, u'\u005E'),
'asciitilde': (0x007e, u'\u007E'),
'asterisk': (0x002a, u'\u002A'),
'at': (0x0040, u'\u0040'),
'atilde': (0x00e3, u'\u00E3'),
'b': (0x0062, u'\u0062'),
'babovedot': (0x1001e03, u'\u1E03'),
'backslash': (0x005c, u'\u005C'),
'ballotcross': (0x0af4, u'\u2717'),
'bar': (0x007c, u'\u007C'),
'because': (0x1002235, u'\u2235'),
'botintegral': (0x08a5, u'\u2321'),
'botleftparens': (0x08ac, u'\u239D'),
'botleftsqbracket': (0x08a8, u'\u23A3'),
'botrightparens': (0x08ae, u'\u23A0'),
'botrightsqbracket': (0x08aa, u'\u23A6'),
'bott': (0x09f6, u'\u2534'),
'braceleft': (0x007b, u'\u007B'),
'braceright': (0x007d, u'\u007D'),
'bracketleft': (0x005b, u'\u005B'),
'bracketright': (0x005d, u'\u005D'),
'braille_blank': (0x1002800, u'\u2800'),
'braille_dots_1': (0x1002801, u'\u2801'),
'braille_dots_12': (0x1002803, u'\u2803'),
'braille_dots_123': (0x1002807, u'\u2807'),
'braille_dots_1234': (0x100280f, u'\u280f'),
'braille_dots_12345': (0x100281f, u'\u281f'),
'braille_dots_123456': (0x100283f, u'\u283f'),
'braille_dots_1234567': (0x100287f, u'\u287f'),
'braille_dots_12345678': (0x10028ff, u'\u28ff'),
'braille_dots_1234568': (0x10028bf, u'\u28bf'),
'braille_dots_123457': (0x100285f, u'\u285f'),
'braille_dots_1234578': (0x10028df, u'\u28df'),
'braille_dots_123458': (0x100289f, u'\u289f'),
'braille_dots_12346': (0x100282f, u'\u282f'),
'braille_dots_123467': (0x100286f, u'\u286f'),
'braille_dots_1234678': (0x10028ef, u'\u28ef'),
'braille_dots_123468': (0x10028af, u'\u28af'),
'braille_dots_12347': (0x100284f, u'\u284f'),
'braille_dots_123478': (0x10028cf, u'\u28cf'),
'braille_dots_12348': (0x100288f, u'\u288f'),
'braille_dots_1235': (0x1002817, u'\u2817'),
'braille_dots_12356': (0x1002837, u'\u2837'),
'braille_dots_123567': (0x1002877, u'\u2877'),
'braille_dots_1235678': (0x10028f7, u'\u28f7'),
'braille_dots_123568': (0x10028b7, u'\u28b7'),
'braille_dots_12357': (0x1002857, u'\u2857'),
'braille_dots_123578': (0x10028d7, u'\u28d7'),
'braille_dots_12358': (0x1002897, u'\u2897'),
'braille_dots_1236': (0x1002827, u'\u2827'),
'braille_dots_12367': (0x1002867, u'\u2867'),
'braille_dots_123678': (0x10028e7, u'\u28e7'),
'braille_dots_12368': (0x10028a7, u'\u28a7'),
'braille_dots_1237': (0x1002847, u'\u2847'),
'braille_dots_12378': (0x10028c7, u'\u28c7'),
'braille_dots_1238': (0x1002887, u'\u2887'),
'braille_dots_124': (0x100280b, u'\u280b'),
'braille_dots_1245': (0x100281b, u'\u281b'),
'braille_dots_12456': (0x100283b, u'\u283b'),
'braille_dots_124567': (0x100287b, u'\u287b'),
'braille_dots_1245678': (0x10028fb, u'\u28fb'),
'braille_dots_124568': (0x10028bb, u'\u28bb'),
'braille_dots_12457': (0x100285b, u'\u285b'),
'braille_dots_124578': (0x10028db, u'\u28db'),
'braille_dots_12458': (0x100289b, u'\u289b'),
'braille_dots_1246': (0x100282b, u'\u282b'),
'braille_dots_12467': (0x100286b, u'\u286b'),
'braille_dots_124678': (0x10028eb, u'\u28eb'),
'braille_dots_12468': (0x10028ab, u'\u28ab'),
'braille_dots_1247': (0x100284b, u'\u284b'),
'braille_dots_12478': (0x10028cb, u'\u28cb'),
'braille_dots_1248': (0x100288b, u'\u288b'),
'braille_dots_125': (0x1002813, u'\u2813'),
'braille_dots_1256': (0x1002833, u'\u2833'),
'braille_dots_12567': (0x1002873, u'\u2873'),
'braille_dots_125678': (0x10028f3, u'\u28f3'),
'braille_dots_12568': (0x10028b3, u'\u28b3'),
'braille_dots_1257': (0x1002853, u'\u2853'),
'braille_dots_12578': (0x10028d3, u'\u28d3'),
'braille_dots_1258': (0x1002893, u'\u2893'),
'braille_dots_126': (0x1002823, u'\u2823'),
'braille_dots_1267': (0x1002863, u'\u2863'),
'braille_dots_12678': (0x10028e3, u'\u28e3'),
'braille_dots_1268': (0x10028a3, u'\u28a3'),
'braille_dots_127': (0x1002843, u'\u2843'),
'braille_dots_1278': (0x10028c3, u'\u28c3'),
'braille_dots_128': (0x1002883, u'\u2883'),
'braille_dots_13': (0x1002805, u'\u2805'),
'braille_dots_134': (0x100280d, u'\u280d'),
'braille_dots_1345': (0x100281d, u'\u281d'),
'braille_dots_13456': (0x100283d, u'\u283d'),
'braille_dots_134567': (0x100287d, u'\u287d'),
'braille_dots_1345678': (0x10028fd, u'\u28fd'),
'braille_dots_134568': (0x10028bd, u'\u28bd'),
'braille_dots_13457': (0x100285d, u'\u285d'),
'braille_dots_134578': (0x10028dd, u'\u28dd'),
'braille_dots_13458': (0x100289d, u'\u289d'),
'braille_dots_1346': (0x100282d, u'\u282d'),
'braille_dots_13467': (0x100286d, u'\u286d'),
'braille_dots_134678': (0x10028ed, u'\u28ed'),
'braille_dots_13468': (0x10028ad, u'\u28ad'),
'braille_dots_1347': (0x100284d, u'\u284d'),
'braille_dots_13478': (0x10028cd, u'\u28cd'),
'braille_dots_1348': (0x100288d, u'\u288d'),
'braille_dots_135': (0x1002815, u'\u2815'),
'braille_dots_1356': (0x1002835, u'\u2835'),
'braille_dots_13567': (0x1002875, u'\u2875'),
'braille_dots_135678': (0x10028f5, u'\u28f5'),
'braille_dots_13568': (0x10028b5, u'\u28b5'),
'braille_dots_1357': (0x1002855, u'\u2855'),
'braille_dots_13578': (0x10028d5, u'\u28d5'),
'braille_dots_1358': (0x1002895, u'\u2895'),
'braille_dots_136': (0x1002825, u'\u2825'),
'braille_dots_1367': (0x1002865, u'\u2865'),
'braille_dots_13678': (0x10028e5, u'\u28e5'),
'braille_dots_1368': (0x10028a5, u'\u28a5'),
'braille_dots_137': (0x1002845, u'\u2845'),
'braille_dots_1378': (0x10028c5, u'\u28c5'),
'braille_dots_138': (0x1002885, u'\u2885'),
'braille_dots_14': (0x1002809, u'\u2809'),
'braille_dots_145': (0x1002819, u'\u2819'),
'braille_dots_1456': (0x1002839, u'\u2839'),
'braille_dots_14567': (0x1002879, u'\u2879'),
'braille_dots_145678': (0x10028f9, u'\u28f9'),
'braille_dots_14568': (0x10028b9, u'\u28b9'),
'braille_dots_1457': (0x1002859, u'\u2859'),
'braille_dots_14578': (0x10028d9, u'\u28d9'),
'braille_dots_1458': (0x1002899, u'\u2899'),
'braille_dots_146': (0x1002829, u'\u2829'),
'braille_dots_1467': (0x1002869, u'\u2869'),
'braille_dots_14678': (0x10028e9, u'\u28e9'),
'braille_dots_1468': (0x10028a9, u'\u28a9'),
'braille_dots_147': (0x1002849, u'\u2849'),
'braille_dots_1478': (0x10028c9, u'\u28c9'),
'braille_dots_148': (0x1002889, u'\u2889'),
'braille_dots_15': (0x1002811, u'\u2811'),
'braille_dots_156': (0x1002831, u'\u2831'),
'braille_dots_1567': (0x1002871, u'\u2871'),
'braille_dots_15678': (0x10028f1, u'\u28f1'),
'braille_dots_1568': (0x10028b1, u'\u28b1'),
'braille_dots_157': (0x1002851, u'\u2851'),
'braille_dots_1578': (0x10028d1, u'\u28d1'),
'braille_dots_158': (0x1002891, u'\u2891'),
'braille_dots_16': (0x1002821, u'\u2821'),
'braille_dots_167': (0x1002861, u'\u2861'),
'braille_dots_1678': (0x10028e1, u'\u28e1'),
'braille_dots_168': (0x10028a1, u'\u28a1'),
'braille_dots_17': (0x1002841, u'\u2841'),
'braille_dots_178': (0x10028c1, u'\u28c1'),
'braille_dots_18': (0x1002881, u'\u2881'),
'braille_dots_2': (0x1002802, u'\u2802'),
'braille_dots_23': (0x1002806, u'\u2806'),
'braille_dots_234': (0x100280e, u'\u280e'),
'braille_dots_2345': (0x100281e, u'\u281e'),
'braille_dots_23456': (0x100283e, u'\u283e'),
'braille_dots_234567': (0x100287e, u'\u287e'),
'braille_dots_2345678': (0x10028fe, u'\u28fe'),
'braille_dots_234568': (0x10028be, u'\u28be'),
'braille_dots_23457': (0x100285e, u'\u285e'),
'braille_dots_234578': (0x10028de, u'\u28de'),
'braille_dots_23458': (0x100289e, u'\u289e'),
'braille_dots_2346': (0x100282e, u'\u282e'),
'braille_dots_23467': (0x100286e, u'\u286e'),
'braille_dots_234678': (0x10028ee, u'\u28ee'),
'braille_dots_23468': (0x10028ae, u'\u28ae'),
'braille_dots_2347': (0x100284e, u'\u284e'),
'braille_dots_23478': (0x10028ce, u'\u28ce'),
'braille_dots_2348': (0x100288e, u'\u288e'),
'braille_dots_235': (0x1002816, u'\u2816'),
'braille_dots_2356': (0x1002836, u'\u2836'),
'braille_dots_23567': (0x1002876, u'\u2876'),
'braille_dots_235678': (0x10028f6, u'\u28f6'),
'braille_dots_23568': (0x10028b6, u'\u28b6'),
'braille_dots_2357': (0x1002856, u'\u2856'),
'braille_dots_23578': (0x10028d6, u'\u28d6'),
'braille_dots_2358': (0x1002896, u'\u2896'),
'braille_dots_236': (0x1002826, u'\u2826'),
'braille_dots_2367': (0x1002866, u'\u2866'),
'braille_dots_23678': (0x10028e6, u'\u28e6'),
'braille_dots_2368': (0x10028a6, u'\u28a6'),
'braille_dots_237': (0x1002846, u'\u2846'),
'braille_dots_2378': (0x10028c6, u'\u28c6'),
'braille_dots_238': (0x1002886, u'\u2886'),
'braille_dots_24': (0x100280a, u'\u280a'),
'braille_dots_245': (0x100281a, u'\u281a'),
'braille_dots_2456': (0x100283a, u'\u283a'),
'braille_dots_24567': (0x100287a, u'\u287a'),
'braille_dots_245678': (0x10028fa, u'\u28fa'),
'braille_dots_24568': (0x10028ba, u'\u28ba'),
'braille_dots_2457': (0x100285a, u'\u285a'),
'braille_dots_24578': (0x10028da, u'\u28da'),
'braille_dots_2458': (0x100289a, u'\u289a'),
'braille_dots_246': (0x100282a, u'\u282a'),
'braille_dots_2467': (0x100286a, u'\u286a'),
'braille_dots_24678': (0x10028ea, u'\u28ea'),
'braille_dots_2468': (0x10028aa, u'\u28aa'),
'braille_dots_247': (0x100284a, u'\u284a'),
'braille_dots_2478': (0x10028ca, u'\u28ca'),
'braille_dots_248': (0x100288a, u'\u288a'),
'braille_dots_25': (0x1002812, u'\u2812'),
'braille_dots_256': (0x1002832, u'\u2832'),
'braille_dots_2567': (0x1002872, u'\u2872'),
'braille_dots_25678': (0x10028f2, u'\u28f2'),
'braille_dots_2568': (0x10028b2, u'\u28b2'),
'braille_dots_257': (0x1002852, u'\u2852'),
'braille_dots_2578': (0x10028d2, u'\u28d2'),
'braille_dots_258': (0x1002892, u'\u2892'),
'braille_dots_26': (0x1002822, u'\u2822'),
'braille_dots_267': (0x1002862, u'\u2862'),
'braille_dots_2678': (0x10028e2, u'\u28e2'),
'braille_dots_268': (0x10028a2, u'\u28a2'),
'braille_dots_27': (0x1002842, u'\u2842'),
'braille_dots_278': (0x10028c2, u'\u28c2'),
'braille_dots_28': (0x1002882, u'\u2882'),
'braille_dots_3': (0x1002804, u'\u2804'),
'braille_dots_34': (0x100280c, u'\u280c'),
'braille_dots_345': (0x100281c, u'\u281c'),
'braille_dots_3456': (0x100283c, u'\u283c'),
'braille_dots_34567': (0x100287c, u'\u287c'),
'braille_dots_345678': (0x10028fc, u'\u28fc'),
'braille_dots_34568': (0x10028bc, u'\u28bc'),
'braille_dots_3457': (0x100285c, u'\u285c'),
'braille_dots_34578': (0x10028dc, u'\u28dc'),
'braille_dots_3458': (0x100289c, u'\u289c'),
'braille_dots_346': (0x100282c, u'\u282c'),
'braille_dots_3467': (0x100286c, u'\u286c'),
'braille_dots_34678': (0x10028ec, u'\u28ec'),
'braille_dots_3468': (0x10028ac, u'\u28ac'),
'braille_dots_347': (0x100284c, u'\u284c'),
'braille_dots_3478': (0x10028cc, u'\u28cc'),
'braille_dots_348': (0x100288c, u'\u288c'),
'braille_dots_35': (0x1002814, u'\u2814'),
'braille_dots_356': (0x1002834, u'\u2834'),
'braille_dots_3567': (0x1002874, u'\u2874'),
'braille_dots_35678': (0x10028f4, u'\u28f4'),
'braille_dots_3568': (0x10028b4, u'\u28b4'),
'braille_dots_357': (0x1002854, u'\u2854'),
'braille_dots_3578': (0x10028d4, u'\u28d4'),
'braille_dots_358': (0x1002894, u'\u2894'),
'braille_dots_36': (0x1002824, u'\u2824'),
'braille_dots_367': (0x1002864, u'\u2864'),
'braille_dots_3678': (0x10028e4, u'\u28e4'),
'braille_dots_368': (0x10028a4, u'\u28a4'),
'braille_dots_37': (0x1002844, u'\u2844'),
'braille_dots_378': (0x10028c4, u'\u28c4'),
'braille_dots_38': (0x1002884, u'\u2884'),
'braille_dots_4': (0x1002808, u'\u2808'),
'braille_dots_45': (0x1002818, u'\u2818'),
'braille_dots_456': (0x1002838, u'\u2838'),
'braille_dots_4567': (0x1002878, u'\u2878'),
'braille_dots_45678': (0x10028f8, u'\u28f8'),
'braille_dots_4568': (0x10028b8, u'\u28b8'),
'braille_dots_457': (0x1002858, u'\u2858'),
'braille_dots_4578': (0x10028d8, u'\u28d8'),
'braille_dots_458': (0x1002898, u'\u2898'),
'braille_dots_46': (0x1002828, u'\u2828'),
'braille_dots_467': (0x1002868, u'\u2868'),
'braille_dots_4678': (0x10028e8, u'\u28e8'),
'braille_dots_468': (0x10028a8, u'\u28a8'),
'braille_dots_47': (0x1002848, u'\u2848'),
'braille_dots_478': (0x10028c8, u'\u28c8'),
'braille_dots_48': (0x1002888, u'\u2888'),
'braille_dots_5': (0x1002810, u'\u2810'),
'braille_dots_56': (0x1002830, u'\u2830'),
'braille_dots_567': (0x1002870, u'\u2870'),
'braille_dots_5678': (0x10028f0, u'\u28f0'),
'braille_dots_568': (0x10028b0, u'\u28b0'),
'braille_dots_57': (0x1002850, u'\u2850'),
'braille_dots_578': (0x10028d0, u'\u28d0'),
'braille_dots_58': (0x1002890, u'\u2890'),
'braille_dots_6': (0x1002820, u'\u2820'),
'braille_dots_67': (0x1002860, u'\u2860'),
'braille_dots_678': (0x10028e0, u'\u28e0'),
'braille_dots_68': (0x10028a0, u'\u28a0'),
'braille_dots_7': (0x1002840, u'\u2840'),
'braille_dots_78': (0x10028c0, u'\u28c0'),
'braille_dots_8': (0x1002880, u'\u2880'),
'breve': (0x01a2, u'\u02D8'),
'brokenbar': (0x00a6, u'\u00A6'),
'c': (0x0063, u'\u0063'),
'cabovedot': (0x02e5, u'\u010B'),
'cacute': (0x01e6, u'\u0107'),
'careof': (0x0ab8, u'\u2105'),
'caret': (0x0afc, u'\u2038'),
'caron': (0x01b7, u'\u02C7'),
'ccaron': (0x01e8, u'\u010D'),
'ccedilla': (0x00e7, u'\u00E7'),
'ccircumflex': (0x02e6, u'\u0109'),
'cedilla': (0x00b8, u'\u00B8'),
'cent': (0x00a2, u'\u00A2'),
'checkerboard': (0x09e1, u'\u2592'),
'checkmark': (0x0af3, u'\u2713'),
'circle': (0x0bcf, u'\u25CB'),
'club': (0x0aec, u'\u2663'),
'colon': (0x003a, u'\u003A'),
'comma': (0x002c, u'\u002C'),
'containsas': (0x100220B, u'\u220B'),
'copyright': (0x00a9, u'\u00A9'),
'cr': (0x09e4, u'\u240D'),
'crossinglines': (0x09ee, u'\u253C'),
'cuberoot': (0x100221B, u'\u221B'),
'currency': (0x00a4, u'\u00A4'),
'd': (0x0064, u'\u0064'),
'dabovedot': (0x1001e0b, u'\u1E0B'),
'dagger': (0x0af1, u'\u2020'),
'dcaron': (0x01ef, u'\u010F'),
'dead_A': (0xfe81, None),
'dead_E': (0xfe83, None),
'dead_I': (0xfe85, None),
'dead_O': (0xfe87, None),
'dead_U': (0xfe89, None),
'dead_a': (0xfe80, None),
'dead_abovecomma': (0xfe64, u'\u0315'),
'dead_abovedot': (0xfe56, u'\u0307'),
'dead_abovereversedcomma': (0xfe65, u'\u0312'),
'dead_abovering': (0xfe58, u'\u030A'),
'dead_aboveverticalline': (0xfe91, u'\u030D'),
'dead_acute': (0xfe51, u'\u0301'),
'dead_belowbreve': (0xfe6b, u'\u032E'),
'dead_belowcircumflex': (0xfe69, u'\u032D'),
'dead_belowcomma': (0xfe6e, u'\u0326'),
'dead_belowdiaeresis': (0xfe6c, u'\u0324'),
'dead_belowdot': (0xfe60, u'\u0323'),
'dead_belowmacron': (0xfe68, u'\u0331'),
'dead_belowring': (0xfe67, u'\u0325'),
'dead_belowtilde': (0xfe6a, u'\u0330'),
'dead_belowverticalline': (0xfe92, u'\u0329'),
'dead_breve': (0xfe55, u'\u0306'),
'dead_capital_schwa': (0xfe8b, None),
'dead_caron': (0xfe5a, u'\u030C'),
'dead_cedilla': (0xfe5b, u'\u0327'),
'dead_circumflex': (0xfe52, u'\u0302'),
'dead_currency': (0xfe6f, None),
'dead_diaeresis': (0xfe57, u'\u0308'),
'dead_doubleacute': (0xfe59, u'\u030B'),
'dead_doublegrave': (0xfe66, u'\u030F'),
'dead_e': (0xfe82, None),
'dead_grave': (0xfe50, u'\u0300'),
'dead_greek': (0xfe8c, None),
'dead_hook': (0xfe61, u'\u0309'),
'dead_horn': (0xfe62, u'\u031B'),
'dead_i': (0xfe84, None),
'dead_invertedbreve': (0xfe6d, u'\u032F'),
'dead_iota': (0xfe5d, u'\u0345'),
'dead_longsolidusoverlay': (0xfe93, u'\u0338'),
'dead_lowline': (0xfe90, u'\u0332'),
'dead_macron': (0xfe54, u'\u0304'),
'dead_o': (0xfe86, None),
'dead_ogonek': (0xfe5c, u'\u0328'),
'dead_semivoiced_sound': (0xfe5f, None),
'dead_small_schwa': (0xfe8a, None),
'dead_stroke': (0xfe63, u'\u0335'),
'dead_tilde': (0xfe53, u'\u0303'),
'dead_u': (0xfe88, None),
'dead_voiced_sound': (0xfe5e, None),
'degree': (0x00b0, u'\u00B0'),
'diaeresis': (0x00a8, u'\u00A8'),
'diamond': (0x0aed, u'\u2666'),
'digitspace': (0x0aa5, u'\u2007'),
'dintegral': (0x100222C, u'\u222C'),
'division': (0x00f7, u'\u00F7'),
'dollar': (0x0024, u'\u0024'),
'doubbaselinedot': (0x0aaf, u'\u2025'),
'doubleacute': (0x01bd, u'\u02DD'),
'doubledagger': (0x0af2, u'\u2021'),
'doublelowquotemark': (0x0afe, u'\u201E'),
'downarrow': (0x08fe, u'\u2193'),
'downstile': (0x0bc4, u'\u230A'),
'downtack': (0x0bc2, u'\u22A4'),
'dstroke': (0x01f0, u'\u0111'),
'e': (0x0065, u'\u0065'),
'eabovedot': (0x03ec, u'\u0117'),
'eacute': (0x00e9, u'\u00E9'),
'ebelowdot': (0x1001eb9, u'\u1EB9'),
'ecaron': (0x01ec, u'\u011B'),
'ecircumflex': (0x00ea, u'\u00EA'),
'ecircumflexacute': (0x1001ebf, u'\u1EBF'),
'ecircumflexbelowdot': (0x1001ec7, u'\u1EC7'),
'ecircumflexgrave': (0x1001ec1, u'\u1EC1'),
'ecircumflexhook': (0x1001ec3, u'\u1EC3'),
'ecircumflextilde': (0x1001ec5, u'\u1EC5'),
'ediaeresis': (0x00eb, u'\u00EB'),
'egrave': (0x00e8, u'\u00E8'),
'ehook': (0x1001ebb, u'\u1EBB'),
'eightsubscript': (0x1002088, u'\u2088'),
'eightsuperior': (0x1002078, u'\u2078'),
'elementof': (0x1002208, u'\u2208'),
'ellipsis': (0x0aae, u'\u2026'),
'em3space': (0x0aa3, u'\u2004'),
'em4space': (0x0aa4, u'\u2005'),
'emacron': (0x03ba, u'\u0113'),
'emdash': (0x0aa9, u'\u2014'),
'emptyset': (0x1002205, u'\u2205'),
'emspace': (0x0aa1, u'\u2003'),
'endash': (0x0aaa, u'\u2013'),
'eng': (0x03bf, u'\u014B'),
'enspace': (0x0aa2, u'\u2002'),
'eogonek': (0x01ea, u'\u0119'),
'equal': (0x003d, u'\u003D'),
'eth': (0x00f0, u'\u00F0'),
'etilde': (0x1001ebd, u'\u1EBD'),
'exclam': (0x0021, u'\u0021'),
'exclamdown': (0x00a1, u'\u00A1'),
'ezh': (0x1000292, u'\u0292'),
'f': (0x0066, u'\u0066'),
'fabovedot': (0x1001e1f, u'\u1E1F'),
'femalesymbol': (0x0af8, u'\u2640'),
'ff': (0x09e3, u'\u240C'),
'figdash': (0x0abb, u'\u2012'),
'fiveeighths': (0x0ac5, u'\u215D'),
'fivesixths': (0x0ab7, u'\u215A'),
'fivesubscript': (0x1002085, u'\u2085'),
'fivesuperior': (0x1002075, u'\u2075'),
'fourfifths': (0x0ab5, u'\u2158'),
'foursubscript': (0x1002084, u'\u2084'),
'foursuperior': (0x1002074, u'\u2074'),
'fourthroot': (0x100221C, u'\u221C'),
'function': (0x08f6, u'\u0192'),
'g': (0x0067, u'\u0067'),
'gabovedot': (0x02f5, u'\u0121'),
'gbreve': (0x02bb, u'\u011F'),
'gcaron': (0x10001e7, u'\u01E7'),
'gcedilla': (0x03bb, u'\u0123'),
'gcircumflex': (0x02f8, u'\u011D'),
'grave': (0x0060, u'\u0060'),
'greater': (0x003e, u'\u003E'),
'greaterthanequal': (0x08be, u'\u2265'),
'guillemotleft': (0x00ab, u'\u00AB'),
'guillemotright': (0x00bb, u'\u00BB'),
'h': (0x0068, u'\u0068'),
'hairspace': (0x0aa8, u'\u200A'),
'hcircumflex': (0x02b6, u'\u0125'),
'heart': (0x0aee, u'\u2665'),
'hebrew_aleph': (0x0ce0, u'\u05D0'),
'hebrew_ayin': (0x0cf2, u'\u05E2'),
'hebrew_bet': (0x0ce1, u'\u05D1'),
'hebrew_chet': (0x0ce7, u'\u05D7'),
'hebrew_dalet': (0x0ce3, u'\u05D3'),
'hebrew_doublelowline': (0x0cdf, u'\u2017'),
'hebrew_finalkaph': (0x0cea, u'\u05DA'),
'hebrew_finalmem': (0x0ced, u'\u05DD'),
'hebrew_finalnun': (0x0cef, u'\u05DF'),
'hebrew_finalpe': (0x0cf3, u'\u05E3'),
'hebrew_finalzade': (0x0cf5, u'\u05E5'),
'hebrew_gimel': (0x0ce2, u'\u05D2'),
'hebrew_he': (0x0ce4, u'\u05D4'),
'hebrew_kaph': (0x0ceb, u'\u05DB'),
'hebrew_lamed': (0x0cec, u'\u05DC'),
'hebrew_mem': (0x0cee, u'\u05DE'),
'hebrew_nun': (0x0cf0, u'\u05E0'),
'hebrew_pe': (0x0cf4, u'\u05E4'),
'hebrew_qoph': (0x0cf7, u'\u05E7'),
'hebrew_resh': (0x0cf8, u'\u05E8'),
'hebrew_samech': (0x0cf1, u'\u05E1'),
'hebrew_shin': (0x0cf9, u'\u05E9'),
'hebrew_taw': (0x0cfa, u'\u05EA'),
'hebrew_tet': (0x0ce8, u'\u05D8'),
'hebrew_waw': (0x0ce5, u'\u05D5'),
'hebrew_yod': (0x0ce9, u'\u05D9'),
'hebrew_zade': (0x0cf6, u'\u05E6'),
'hebrew_zain': (0x0ce6, u'\u05D6'),
'horizlinescan1': (0x09ef, u'\u23BA'),
'horizlinescan3': (0x09f0, u'\u23BB'),
'horizlinescan5': (0x09f1, u'\u2500'),
'horizlinescan7': (0x09f2, u'\u23BC'),
'horizlinescan9': (0x09f3, u'\u23BD'),
'hstroke': (0x02b1, u'\u0127'),
'ht': (0x09e2, u'\u2409'),
'hyphen': (0x00ad, u'\u00AD'),
'i': (0x0069, u'\u0069'),
'iacute': (0x00ed, u'\u00ED'),
'ibelowdot': (0x1001ecb, u'\u1ECB'),
'ibreve': (0x100012d, u'\u012D'),
'icircumflex': (0x00ee, u'\u00EE'),
'identical': (0x08cf, u'\u2261'),
'idiaeresis': (0x00ef, u'\u00EF'),
'idotless': (0x02b9, u'\u0131'),
'ifonlyif': (0x08cd, u'\u21D4'),
'igrave': (0x00ec, u'\u00EC'),
'ihook': (0x1001ec9, u'\u1EC9'),
'imacron': (0x03ef, u'\u012B'),
'implies': (0x08ce, u'\u21D2'),
'includedin': (0x08da, u'\u2282'),
'includes': (0x08db, u'\u2283'),
'infinity': (0x08c2, u'\u221E'),
'integral': (0x08bf, u'\u222B'),
'intersection': (0x08dc, u'\u2229'),
'iogonek': (0x03e7, u'\u012F'),
'itilde': (0x03b5, u'\u0129'),
'j': (0x006a, u'\u006A'),
'jcircumflex': (0x02bc, u'\u0135'),
'jot': (0x0bca, u'\u2218'),
'k': (0x006b, u'\u006B'),
'kana_A': (0x04b1, u'\u30A2'),
'kana_CHI': (0x04c1, u'\u30C1'),
'kana_E': (0x04b4, u'\u30A8'),
'kana_FU': (0x04cc, u'\u30D5'),
'kana_HA': (0x04ca, u'\u30CF'),
'kana_HE': (0x04cd, u'\u30D8'),
'kana_HI': (0x04cb, u'\u30D2'),
'kana_HO': (0x04ce, u'\u30DB'),
'kana_I': (0x04b2, u'\u30A4'),
'kana_KA': (0x04b6, u'\u30AB'),
'kana_KE': (0x04b9, u'\u30B1'),
'kana_KI': (0x04b7, u'\u30AD'),
'kana_KO': (0x04ba, u'\u30B3'),
'kana_KU': (0x04b8, u'\u30AF'),
'kana_MA': (0x04cf, u'\u30DE'),
'kana_ME': (0x04d2, u'\u30E1'),
'kana_MI': (0x04d0, u'\u30DF'),
'kana_MO': (0x04d3, u'\u30E2'),
'kana_MU': (0x04d1, u'\u30E0'),
'kana_N': (0x04dd, u'\u30F3'),
'kana_NA': (0x04c5, u'\u30CA'),
'kana_NE': (0x04c8, u'\u30CD'),
'kana_NI': (0x04c6, u'\u30CB'),
'kana_NO': (0x04c9, u'\u30CE'),
'kana_NU': (0x04c7, u'\u30CC'),
'kana_O': (0x04b5, u'\u30AA'),
'kana_RA': (0x04d7, u'\u30E9'),
'kana_RE': (0x04da, u'\u30EC'),
'kana_RI': (0x04d8, u'\u30EA'),
'kana_RO': (0x04db, u'\u30ED'),
'kana_RU': (0x04d9, u'\u30EB'),
'kana_SA': (0x04bb, u'\u30B5'),
'kana_SE': (0x04be, u'\u30BB'),
'kana_SHI': (0x04bc, u'\u30B7'),
'kana_SO': (0x04bf, u'\u30BD'),
'kana_SU': (0x04bd, u'\u30B9'),
'kana_TA': (0x04c0, u'\u30BF'),
'kana_TE': (0x04c3, u'\u30C6'),
'kana_TO': (0x04c4, u'\u30C8'),
'kana_TSU': (0x04c2, u'\u30C4'),
'kana_U': (0x04b3, u'\u30A6'),
'kana_WA': (0x04dc, u'\u30EF'),
'kana_WO': (0x04a6, u'\u30F2'),
'kana_YA': (0x04d4, u'\u30E4'),
'kana_YO': (0x04d6, u'\u30E8'),
'kana_YU': (0x04d5, u'\u30E6'),
'kana_a': (0x04a7, u'\u30A1'),
'kana_closingbracket': (0x04a3, u'\u300D'),
'kana_comma': (0x04a4, u'\u3001'),
'kana_conjunctive': (0x04a5, u'\u30FB'),
'kana_e': (0x04aa, u'\u30A7'),
'kana_fullstop': (0x04a1, u'\u3002'),
'kana_i': (0x04a8, u'\u30A3'),
'kana_o': (0x04ab, u'\u30A9'),
'kana_openingbracket': (0x04a2, u'\u300C'),
'kana_tsu': (0x04af, u'\u30C3'),
'kana_u': (0x04a9, u'\u30A5'),
'kana_ya': (0x04ac, u'\u30E3'),
'kana_yo': (0x04ae, u'\u30E7'),
'kana_yu': (0x04ad, u'\u30E5'),
'kcedilla': (0x03f3, u'\u0137'),
'kra': (0x03a2, u'\u0138'),
'l': (0x006c, u'\u006C'),
'lacute': (0x01e5, u'\u013A'),
'latincross': (0x0ad9, u'\u271D'),
'lbelowdot': (0x1001e37, u'\u1E37'),
'lcaron': (0x01b5, u'\u013E'),
'lcedilla': (0x03b6, u'\u013C'),
'leftarrow': (0x08fb, u'\u2190'),
'leftdoublequotemark': (0x0ad2, u'\u201C'),
'leftmiddlecurlybrace': (0x08af, u'\u23A8'),
'leftradical': (0x08a1, u'\u23B7'),
'leftsinglequotemark': (0x0ad0, u'\u2018'),
'leftt': (0x09f4, u'\u251C'),
'lefttack': (0x0bdc, u'\u22A3'),
'less': (0x003c, u'\u003C'),
'lessthanequal': (0x08bc, u'\u2264'),
'lf': (0x09e5, u'\u240A'),
'logicaland': (0x08de, u'\u2227'),
'logicalor': (0x08df, u'\u2228'),
'lowleftcorner': (0x09ed, u'\u2514'),
'lowrightcorner': (0x09ea, u'\u2518'),
'lstroke': (0x01b3, u'\u0142'),
'm': (0x006d, u'\u006D'),
'mabovedot': (0x1001e41, u'\u1E41'),
'macron': (0x00af, u'\u00AF'),
'malesymbol': (0x0af7, u'\u2642'),
'maltesecross': (0x0af0, u'\u2720'),
'masculine': (0x00ba, u'\u00BA'),
'minus': (0x002d, u'\u002D'),
'minutes': (0x0ad6, u'\u2032'),
'mu': (0x00b5, u'\u00B5'),
'multiply': (0x00d7, u'\u00D7'),
'musicalflat': (0x0af6, u'\u266D'),
'musicalsharp': (0x0af5, u'\u266F'),
'n': (0x006e, u'\u006E'),
'nabla': (0x08c5, u'\u2207'),
'nacute': (0x01f1, u'\u0144'),
'ncaron': (0x01f2, u'\u0148'),
'ncedilla': (0x03f1, u'\u0146'),
'ninesubscript': (0x1002089, u'\u2089'),
'ninesuperior': (0x1002079, u'\u2079'),
'nl': (0x09e8, u'\u2424'),
'nobreakspace': (0x00a0, u'\u00A0'),
'notapproxeq': (0x1002247, u'\u2247'),
'notelementof': (0x1002209, u'\u2209'),
'notequal': (0x08bd, u'\u2260'),
'notidentical': (0x1002262, u'\u2262'),
'notsign': (0x00ac, u'\u00AC'),
'ntilde': (0x00f1, u'\u00F1'),
'numbersign': (0x0023, u'\u0023'),
'numerosign': (0x06b0, u'\u2116'),
'o': (0x006f, u'\u006F'),
'oacute': (0x00f3, u'\u00F3'),
'obarred': (0x1000275, u'\u0275'),
'obelowdot': (0x1001ecd, u'\u1ECD'),
'ocaron': (0x10001d2, u'\u01D2'),
'ocircumflex': (0x00f4, u'\u00F4'),
'ocircumflexacute': (0x1001ed1, u'\u1ED1'),
'ocircumflexbelowdot': (0x1001ed9, u'\u1ED9'),
'ocircumflexgrave': (0x1001ed3, u'\u1ED3'),
'ocircumflexhook': (0x1001ed5, u'\u1ED5'),
'ocircumflextilde': (0x1001ed7, u'\u1ED7'),
'odiaeresis': (0x00f6, u'\u00F6'),
'odoubleacute': (0x01f5, u'\u0151'),
'oe': (0x13bd, u'\u0153'),
'ogonek': (0x01b2, u'\u02DB'),
'ograve': (0x00f2, u'\u00F2'),
'ohook': (0x1001ecf, u'\u1ECF'),
'ohorn': (0x10001a1, u'\u01A1'),
'ohornacute': (0x1001edb, u'\u1EDB'),
'ohornbelowdot': (0x1001ee3, u'\u1EE3'),
'ohorngrave': (0x1001edd, u'\u1EDD'),
'ohornhook': (0x1001edf, u'\u1EDF'),
'ohorntilde': (0x1001ee1, u'\u1EE1'),
'omacron': (0x03f2, u'\u014D'),
'oneeighth': (0x0ac3, u'\u215B'),
'onefifth': (0x0ab2, u'\u2155'),
'onehalf': (0x00bd, u'\u00BD'),
'onequarter': (0x00bc, u'\u00BC'),
'onesixth': (0x0ab6, u'\u2159'),
'onesubscript': (0x1002081, u'\u2081'),
'onesuperior': (0x00b9, u'\u00B9'),
'onethird': (0x0ab0, u'\u2153'),
'ooblique': (0x00f8, u'\u00F8'),
'ordfeminine': (0x00aa, u'\u00AA'),
'oslash': (0x00f8, u'\u00F8'),
'otilde': (0x00f5, u'\u00F5'),
'overline': (0x047e, u'\u203E'),
'p': (0x0070, u'\u0070'),
'pabovedot': (0x1001e57, u'\u1E57'),
'paragraph': (0x00b6, u'\u00B6'),
'parenleft': (0x0028, u'\u0028'),
'parenright': (0x0029, u'\u0029'),
'partdifferential': (0x1002202, u'\u2202'),
'partialderivative': (0x08ef, u'\u2202'),
'percent': (0x0025, u'\u0025'),
'period': (0x002e, u'\u002E'),
'periodcentered': (0x00b7, u'\u00B7'),
'permille': (0x0ad5, u'\u2030'),
'phonographcopyright': (0x0afb, u'\u2117'),
'plus': (0x002b, u'\u002B'),
'plusminus': (0x00b1, u'\u00B1'),
'prescription': (0x0ad4, u'\u211E'),
'prolongedsound': (0x04b0, u'\u30FC'),
'punctspace': (0x0aa6, u'\u2008'),
'q': (0x0071, u'\u0071'),
'quad': (0x0bcc, u'\u2395'),
'question': (0x003f, u'\u003F'),
'questiondown': (0x00bf, u'\u00BF'),
'quotedbl': (0x0022, u'\u0022'),
'r': (0x0072, u'\u0072'),
'racute': (0x01e0, u'\u0155'),
'radical': (0x08d6, u'\u221A'),
'rcaron': (0x01f8, u'\u0159'),
'rcedilla': (0x03b3, u'\u0157'),
'registered': (0x00ae, u'\u00AE'),
'rightarrow': (0x08fd, u'\u2192'),
'rightdoublequotemark': (0x0ad3, u'\u201D'),
'rightmiddlecurlybrace': (0x08b0, u'\u23AC'),
'rightsinglequotemark': (0x0ad1, u'\u2019'),
'rightt': (0x09f5, u'\u2524'),
'righttack': (0x0bfc, u'\u22A2'),
's': (0x0073, u'\u0073'),
'sabovedot': (0x1001e61, u'\u1E61'),
'sacute': (0x01b6, u'\u015B'),
'scaron': (0x01b9, u'\u0161'),
'scedilla': (0x01ba, u'\u015F'),
'schwa': (0x1000259, u'\u0259'),
'scircumflex': (0x02fe, u'\u015D'),
'seconds': (0x0ad7, u'\u2033'),
'section': (0x00a7, u'\u00A7'),
'semicolon': (0x003b, u'\u003B'),
'semivoicedsound': (0x04df, u'\u309C'),
'seveneighths': (0x0ac6, u'\u215E'),
'sevensubscript': (0x1002087, u'\u2087'),
'sevensuperior': (0x1002077, u'\u2077'),
'similarequal': (0x08c9, u'\u2243'),
'singlelowquotemark': (0x0afd, u'\u201A'),
'sixsubscript': (0x1002086, u'\u2086'),
'sixsuperior': (0x1002076, u'\u2076'),
'slash': (0x002f, u'\u002F'),
'soliddiamond': (0x09e0, u'\u25C6'),
'space': (0x0020, u'\u0020'),
'squareroot': (0x100221A, u'\u221A'),
'ssharp': (0x00df, u'\u00DF'),
'sterling': (0x00a3, u'\u00A3'),
'stricteq': (0x1002263, u'\u2263'),
't': (0x0074, u'\u0074'),
'tabovedot': (0x1001e6b, u'\u1E6B'),
'tcaron': (0x01bb, u'\u0165'),
'tcedilla': (0x01fe, u'\u0163'),
'telephone': (0x0af9, u'\u260E'),
'telephonerecorder': (0x0afa, u'\u2315'),
'therefore': (0x08c0, u'\u2234'),
'thinspace': (0x0aa7, u'\u2009'),
'thorn': (0x00fe, u'\u00FE'),
'threeeighths': (0x0ac4, u'\u215C'),
'threefifths': (0x0ab4, u'\u2157'),
'threequarters': (0x00be, u'\u00BE'),
'threesubscript': (0x1002083, u'\u2083'),
'threesuperior': (0x00b3, u'\u00B3'),
'tintegral': (0x100222D, u'\u222D'),
'topintegral': (0x08a4, u'\u2320'),
'topleftparens': (0x08ab, u'\u239B'),
'topleftsqbracket': (0x08a7, u'\u23A1'),
'toprightparens': (0x08ad, u'\u239E'),
'toprightsqbracket': (0x08a9, u'\u23A4'),
'topt': (0x09f7, u'\u252C'),
'trademark': (0x0ac9, u'\u2122'),
'tslash': (0x03bc, u'\u0167'),
'twofifths': (0x0ab3, u'\u2156'),
'twosubscript': (0x1002082, u'\u2082'),
'twosuperior': (0x00b2, u'\u00B2'),
'twothirds': (0x0ab1, u'\u2154'),
'u': (0x0075, u'\u0075'),
'uacute': (0x00fa, u'\u00FA'),
'ubelowdot': (0x1001ee5, u'\u1EE5'),
'ubreve': (0x02fd, u'\u016D'),
'ucircumflex': (0x00fb, u'\u00FB'),
'udiaeresis': (0x00fc, u'\u00FC'),
'udoubleacute': (0x01fb, u'\u0171'),
'ugrave': (0x00f9, u'\u00F9'),
'uhook': (0x1001ee7, u'\u1EE7'),
'uhorn': (0x10001b0, u'\u01B0'),
'uhornacute': (0x1001ee9, u'\u1EE9'),
'uhornbelowdot': (0x1001ef1, u'\u1EF1'),
'uhorngrave': (0x1001eeb, u'\u1EEB'),
'uhornhook': (0x1001eed, u'\u1EED'),
'uhorntilde': (0x1001eef, u'\u1EEF'),
'umacron': (0x03fe, u'\u016B'),
'underscore': (0x005f, u'\u005F'),
'union': (0x08dd, u'\u222A'),
'uogonek': (0x03f9, u'\u0173'),
'uparrow': (0x08fc, u'\u2191'),
'upleftcorner': (0x09ec, u'\u250C'),
'uprightcorner': (0x09eb, u'\u2510'),
'upstile': (0x0bd3, u'\u2308'),
'uptack': (0x0bce, u'\u22A5'),
'uring': (0x01f9, u'\u016F'),
'utilde': (0x03fd, u'\u0169'),
'v': (0x0076, u'\u0076'),
'variation': (0x08c1, u'\u221D'),
'vertbar': (0x09f8, u'\u2502'),
'voicedsound': (0x04de, u'\u309B'),
'vt': (0x09e9, u'\u240B'),
'w': (0x0077, u'\u0077'),
'wacute': (0x1001e83, u'\u1E83'),
'wcircumflex': (0x1000175, u'\u0175'),
'wdiaeresis': (0x1001e85, u'\u1E85'),
'wgrave': (0x1001e81, u'\u1E81'),
'x': (0x0078, u'\u0078'),
'xabovedot': (0x1001e8b, u'\u1E8B'),
'y': (0x0079, u'\u0079'),
'yacute': (0x00fd, u'\u00FD'),
'ybelowdot': (0x1001ef5, u'\u1EF5'),
'ycircumflex': (0x1000177, u'\u0177'),
'ydiaeresis': (0x00ff, u'\u00FF'),
'yen': (0x00a5, u'\u00A5'),
'ygrave': (0x1001ef3, u'\u1EF3'),
'yhook': (0x1001ef7, u'\u1EF7'),
'ytilde': (0x1001ef9, u'\u1EF9'),
'z': (0x007a, u'\u007A'),
'zabovedot': (0x01bf, u'\u017C'),
'zacute': (0x01bc, u'\u017A'),
'zcaron': (0x01be, u'\u017E'),
'zerosubscript': (0x1002080, u'\u2080'),
'zerosuperior': (0x1002070, u'\u2070'),
'zstroke': (0x10001b6, u'\u01B6')}
DEAD_KEYS = {
u'\u0307': u'\u02D9',
u'\u030A': u'\u02DA',
u'\u0301': u'\u00B4',
u'\u0306': u'\u02D8',
u'\u030C': u'\u02C7',
u'\u0327': u'\u00B8',
u'\u0302': u'\u005E',
u'\u0308': u'\u00A8',
u'\u030B': u'\u02DD',
u'\u0300': u'\u0060',
u'\u0345': u'\u037A',
u'\u0332': u'\u005F',
u'\u0304': u'\u00AF',
u'\u0328': u'\u02DB',
u'\u0303': u'\u007E'}
KEYPAD_KEYS = {
'KP_0': 0xffb0,
'KP_1': 0xffb1,
'KP_2': 0xffb2,
'KP_3': 0xffb3,
'KP_4': 0xffb4,
'KP_5': 0xffb5,
'KP_6': 0xffb6,
'KP_7': 0xffb7,
'KP_8': 0xffb8,
'KP_9': 0xffb9,
'KP_Add': 0xffab,
'KP_Begin': 0xff9d,
'KP_Decimal': 0xffae,
'KP_Delete': 0xff9f,
'KP_Divide': 0xffaf,
'KP_Down': 0xff99,
'KP_End': 0xff9c,
'KP_Enter': 0xff8d,
'KP_Equal': 0xffbd,
'KP_F1': 0xff91,
'KP_F2': 0xff92,
'KP_F3': 0xff93,
'KP_F4': 0xff94,
'KP_Home': 0xff95,
'KP_Insert': 0xff9e,
'KP_Left': 0xff96,
'KP_Multiply': 0xffaa,
'KP_Next': 0xff9b,
'KP_Page_Down': 0xff9b,
'KP_Page_Up': 0xff9a,
'KP_Prior': 0xff9a,
'KP_Right': 0xff98,
'KP_Separator': 0xffac,
'KP_Space': 0xff80,
'KP_Subtract': 0xffad,
'KP_Tab': 0xff89,
'KP_Up': 0xff97}
CHARS = {
codepoint: name
for name, (keysym, codepoint) in SYMBOLS.items()
if codepoint}
KEYSYMS = {
keysym: name
for name, (keysym, codepoint) in SYMBOLS.items()
if codepoint}
pynput-1.7.6/lib/pynput/keyboard/ 0000775 0000000 0000000 00000000000 14164131047 0016772 5 ustar 00root root 0000000 0000000 pynput-1.7.6/lib/pynput/keyboard/__init__.py 0000664 0000000 0000000 00000016050 14164131047 0021105 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
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):
#: The key.
self.key = key
class Release(Events.Event):
"""A key release event.
"""
def __init__(self, key):
#: The key.
self.key = key
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 ``''``.
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:
return Key[p.lower()]
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):
"""The press callback.
This is automatically registered upon creation.
:param key: The key provided by the base class.
"""
for hotkey in self._hotkeys:
hotkey.press(self.canonical(key))
def _on_release(self, key):
"""The release callback.
This is automatically registered upon creation.
:param key: The key provided by the base class.
"""
for hotkey in self._hotkeys:
hotkey.release(self.canonical(key))
pynput-1.7.6/lib/pynput/keyboard/_base.py 0000664 0000000 0000000 00000053577 14164131047 0020436 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
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 = 0
#: The left Alt key. This is a modifier.
alt_l = 0
#: The right Alt key. This is a modifier.
alt_r = 0
#: The AltGr key. This is a modifier.
alt_gr = 0
#: The Backspace key.
backspace = 0
#: The CapsLock key.
caps_lock = 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 = 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 = 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 = 0
#: A generic Ctrl key. This is a modifier.
ctrl = 0
#: The left Ctrl key. This is a modifier.
ctrl_l = 0
#: The right Ctrl key. This is a modifier.
ctrl_r = 0
#: The Delete key.
delete = 0
#: A down arrow key.
down = 0
#: The End key.
end = 0
#: The Enter or Return key.
enter = 0
#: The Esc key.
esc = 0
#: The function keys. F1 to F20 are defined.
f1 = 0
f2 = 0
f3 = 0
f4 = 0
f5 = 0
f6 = 0
f7 = 0
f8 = 0
f9 = 0
f10 = 0
f11 = 0
f12 = 0
f13 = 0
f14 = 0
f15 = 0
f16 = 0
f17 = 0
f18 = 0
f19 = 0
f20 = 0
#: The Home key.
home = 0
#: A left arrow key.
left = 0
#: The PageDown key.
page_down = 0
#: The PageUp key.
page_up = 0
#: A right arrow key.
right = 0
#: A generic Shift key. This is a modifier.
shift = 0
#: The left Shift key. This is a modifier.
shift_l = 0
#: The right Shift key. This is a modifier.
shift_r = 0
#: The Space key.
space = 0
#: The Tab key.
tab = 0
#: An up arrow key.
up = 0
#: The play/pause toggle.
media_play_pause = 0
#: The volume mute button.
media_volume_mute = 0
#: The volume down button.
media_volume_down = 0
#: The volume up button.
media_volume_up = 0
#: The previous track button.
media_previous = 0
#: The next track button.
media_next = 0
#: The Insert key. This may be undefined for some platforms.
insert = 0
#: The Menu key. This may be undefined for some platforms.
menu = 0
#: The NumLock key. This may be undefined for some platforms.
num_lock = 0
#: The Pause/Break key. This may be undefined for some platforms.
pause = 0
#: The PrintScreen key. This may be undefined for some platforms.
print_screen = 0
#: The ScrollLock key. This may be undefined for some platforms.
scroll_lock = 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.
:param callable on_press: The callback to call when a button is pressed.
It will be called with the argument ``(key)``, where ``key`` is a
:class:`KeyCode`, a :class:`Key` or ``None`` if the key is unknown.
:param callable on_release: The callback to call when a button is released.
It will be called with the argument ``(key)``, where ``key`` is a
:class:`KeyCode`, a :class:`Key` or ``None`` if the key is unknown.
: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.kCGEventKeyDown``, 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 `_.
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=on_press, on_release=on_release, 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
pynput-1.7.6/lib/pynput/keyboard/_darwin.py 0000664 0000000 0000000 00000026062 14164131047 0020775 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
The keyboard implementation for *macOS*.
"""
# pylint: disable=C0111
# The documentation is extracted from the base classes
# pylint: disable=R0903
# We implement stubs
import enum
import Quartz
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
# 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(
Quartz.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(
Quartz.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 = Quartz.CGEventCreateKeyboardEvent(
None, 0 if vk is None else vk, is_pressed)
Quartz.CGEventSetFlags(
result,
0
| (Quartz.kCGEventFlagMaskAlternate
if Key.alt in modifiers else 0)
| (Quartz.kCGEventFlagMaskCommand
if Key.cmd in modifiers else 0)
| (Quartz.kCGEventFlagMaskControl
if Key.ctrl in modifiers else 0)
| (Quartz.kCGEventFlagMaskShift
if Key.shift in modifiers else 0))
if vk is None and self.char is not None:
Quartz.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)
# 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:
Quartz.CGEventPost(
Quartz.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 = (
Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventFlagsChanged) |
Quartz.CGEventMaskBit(Quartz.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: Quartz.kCGEventFlagMaskAlternate,
Key.alt_l: Quartz.kCGEventFlagMaskAlternate,
Key.alt_r: Quartz.kCGEventFlagMaskAlternate,
Key.cmd: Quartz.kCGEventFlagMaskCommand,
Key.cmd_l: Quartz.kCGEventFlagMaskCommand,
Key.cmd_r: Quartz.kCGEventFlagMaskCommand,
Key.ctrl: Quartz.kCGEventFlagMaskControl,
Key.ctrl_l: Quartz.kCGEventFlagMaskControl,
Key.ctrl_r: Quartz.kCGEventFlagMaskControl,
Key.shift: Quartz.kCGEventFlagMaskShift,
Key.shift_l: Quartz.kCGEventFlagMaskShift,
Key.shift_r: Quartz.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(self, _proxy, event_type, event, _refcon):
# 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 == Quartz.kCGEventKeyDown:
# This is a normal key press
self.on_press(key)
elif event_type == Quartz.kCGEventKeyUp:
# This is a normal key release
self.on_release(key)
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)
self.on_release(key)
elif event_type == Quartz.NSSystemDefined:
sys_event = Quartz.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 = Quartz.CGEventGetFlags(event)
is_press = flags & self._MODIFIER_FLAGS.get(key, 0)
if is_press:
self.on_press(key)
else:
self.on_release(key)
finally:
# Store the current flag mask to be able to detect modifier state
# changes
self._flags = Quartz.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 = Quartz.CGEventGetIntegerValueField(
event, Quartz.kCGKeyboardEventKeycode)
event_type = Quartz.CGEventGetType(event)
is_media = True if event_type == Quartz.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 = Quartz.CGEventKeyboardGetUnicodeString(
event, 100, None, None)
try:
printable = chars.isprintable()
except AttributeError:
printable = chars.isalnum()
if not printable and vk in SYMBOLS \
and Quartz.CGEventGetFlags(event) \
& Quartz.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)
pynput-1.7.6/lib/pynput/keyboard/_dummy.py 0000664 0000000 0000000 00000001577 14164131047 0020650 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
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
pynput-1.7.6/lib/pynput/keyboard/_uinput.py 0000664 0000000 0000000 00000034076 14164131047 0021041 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
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(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)
if is_press:
self.on_press(key)
else:
self.on_release(key)
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)))
pynput-1.7.6/lib/pynput/keyboard/_win32.py 0000664 0000000 0000000 00000025115 14164131047 0020451 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
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
"""
if self.vk:
vk = self.vk
scan = self._scan \
or MapVirtualKey(vk, MapVirtualKey.MAPVK_VK_TO_VSC)
flags = 0
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_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):
SendInput(
1,
ctypes.byref(INPUT(
type=INPUT.KEYBOARD,
value=INPUT_union(
ki=KEYBDINPUT(**key._parameters(is_press))))),
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 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``.
"""
_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
# Suppress further propagation of the event if it is filtered
if self._event_filter(msg, data) is False:
return None
elif is_packet:
return (msg | self._UTF16_FLAG, data.scanCode)
else:
return (msg, 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
if is_utf16:
msg = msg ^ self._UTF16_FLAG
scan = vk
key = KeyCode.from_char(six.unichr(scan))
else:
try:
key = self._event_to_key(msg, vk)
except OSError:
key = None
if msg in self._PRESS_MESSAGES:
self.on_press(key)
elif msg in self._RELEASE_MESSAGES:
self.on_release(key)
# 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)
pynput-1.7.6/lib/pynput/keyboard/_xorg.py 0000664 0000000 0000000 00000052600 14164131047 0020465 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
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 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 event: The *X* keyboard event.
:param int keysym: The keysym to handle.
"""
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)
mapping[i][index] = keysym
dm.change_keyboard_mapping(
keycode,
mapping[i:i + 1])
self._borrows[keysym] = (keycode, index, 0)
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 events 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(self, display, event):
# 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)
elif event.type == Xlib.X.KeyRelease:
self.on_release(key)
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))
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)
pynput-1.7.6/lib/pynput/mouse/ 0000775 0000000 0000000 00000000000 14164131047 0016322 5 ustar 00root root 0000000 0000000 pynput-1.7.6/lib/pynput/mouse/__init__.py 0000664 0000000 0000000 00000005020 14164131047 0020430 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
The module containing mouse classes.
See the documentation for more information.
"""
# pylint: disable=C0103
# Button, Controller and Listener are not constants
from pynput._util import backend, Events
backend = backend(__name__)
Button = backend.Button
Controller = backend.Controller
Listener = backend.Listener
del backend
class Events(Events):
"""A mouse event listener supporting synchronous iteration over the events.
Possible events are:
:class:`Events.Move`
The mouse was moved.
:class:`Events.Click`
A mouse button was pressed or released.
:class:`Events.Scroll`
The device was scrolled.
"""
_Listener = Listener
class Move(Events.Event):
"""A move event.
"""
def __init__(self, x, y):
#: The X screen coordinate.
self.x = x
#: The Y screen coordinate.
self.y = y
class Click(Events.Event):
"""A click event.
"""
def __init__(self, x, y, button, pressed):
#: The X screen coordinate.
self.x = x
#: The Y screen coordinate.
self.y = y
#: The button.
self.button = button
#: Whether the button was pressed.
self.pressed = pressed
class Scroll(Events.Event):
"""A scroll event.
"""
def __init__(self, x, y, dx, dy):
#: The X screen coordinate.
self.x = x
#: The Y screen coordinate.
self.y = y
#: The number of horisontal steps.
self.dx = dx
#: The number of vertical steps.
self.dy = dy
def __init__(self):
super(Events, self).__init__(
on_move=self.Move,
on_click=self.Click,
on_scroll=self.Scroll)
pynput-1.7.6/lib/pynput/mouse/_base.py 0000664 0000000 0000000 00000020375 14164131047 0017754 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
This module contains the base implementation.
The actual interface to mouse classes is defined here, but the implementation
is located in a platform dependent module.
"""
# pylint: disable=R0903
# We implement stubs
import enum
from pynput._util import AbstractListener, prefix
from pynput import _logger
class Button(enum.Enum):
"""The various buttons.
The actual values for these items differ between platforms. Some
platforms may have additional buttons, but these are guaranteed to be
present everywhere.
"""
#: An unknown button was pressed
unknown = 0
#: The left button
left = 1
#: The middle button
middle = 2
#: The right button
right = 3
class Controller(object):
"""A controller for sending virtual mouse events to the system.
"""
def __init__(self):
self._log = _logger(self.__class__)
@property
def position(self):
"""The current position of the mouse pointer.
This is the tuple ``(x, y)``, and setting it will move the pointer.
"""
return self._position_get()
@position.setter
def position(self, pos):
self._position_set(pos)
def scroll(self, dx, dy):
"""Sends scroll events.
:param int dx: The horizontal scroll. The units of scrolling is
undefined.
:param int dy: The vertical scroll. The units of scrolling is
undefined.
:raises ValueError: if the values are invalid, for example out of
bounds
"""
self._scroll(dx, dy)
def press(self, button):
"""Emits a button press event at the current position.
:param Button button: The button to press.
"""
self._press(button)
def release(self, button):
"""Emits a button release event at the current position.
:param Button button: The button to release.
"""
self._release(button)
def move(self, dx, dy):
"""Moves the mouse pointer a number of pixels from its current
position.
:param int dx: The horizontal offset.
:param int dy: The vertical offset.
:raises ValueError: if the values are invalid, for example out of
bounds
"""
self.position = tuple(sum(i) for i in zip(self.position, (dx, dy)))
def click(self, button, count=1):
"""Emits a button click event at the current position.
The default implementation sends a series of press and release events.
:param Button button: The button to click.
:param int count: The number of clicks to send.
"""
with self as controller:
for _ in range(count):
controller.press(button)
controller.release(button)
def __enter__(self):
"""Begins a series of clicks.
In the default :meth:`click` implementation, the return value of this
method is used for the calls to :meth:`press` and :meth:`release`
instead of ``self``.
The default implementation is a no-op.
"""
return self
def __exit__(self, exc_type, value, traceback):
"""Ends a series of clicks.
"""
pass
def _position_get(self):
"""The implementation of the getter for :attr:`position`.
This is a platform dependent implementation.
"""
raise NotImplementedError()
def _position_set(self, pos):
"""The implementation of the setter for :attr:`position`.
This is a platform dependent implementation.
"""
raise NotImplementedError()
def _scroll(self, dx, dy):
"""The implementation of the :meth:`scroll` method.
This is a platform dependent implementation.
"""
raise NotImplementedError()
def _press(self, button):
"""The implementation of the :meth:`press` method.
This is a platform dependent implementation.
"""
raise NotImplementedError()
def _release(self, button):
"""The implementation of the :meth:`release` method.
This is a platform dependent implementation.
"""
raise NotImplementedError()
# pylint: disable=W0223; This is also an abstract class
class Listener(AbstractListener):
"""A listener for mouse 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.
:param callable on_move: The callback to call when mouse move events occur.
It will be called with the arguments ``(x, y)``, which is the new
pointer position. If this callback raises :class:`StopException` or
returns ``False``, the listener is stopped.
:param callable on_click: The callback to call when a mouse button is
clicked.
It will be called with the arguments ``(x, y, button, pressed)``,
where ``(x, y)`` is the new pointer position, ``button`` is one of the
:class:`Button` values and ``pressed`` is whether the button was
pressed.
If this callback raises :class:`StopException` or returns ``False``,
the listener is stopped.
:param callable on_scroll: The callback to call when mouse scroll
events occur.
It will be called with the arguments ``(x, y, dx, dy)``, where
``(x, y)`` is the new pointer position, and ``(dx, dy)`` is the scroll
vector.
If this callback raises :class:`StopException` or returns ``False``,
the listener is stopped.
: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_``, ``xorg_`` or
``win32_``.
Supported values are:
``darwin_intercept``
A callable taking the arguments ``(event_type, event)``, where
``event_type`` is any mouse related event type constant, 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.
``win32_event_filter``
A callable taking the arguments ``(msg, data)``, where ``msg`` is
the current message, and ``data`` associated data as a
`MSLLHOOKSTRUCT `_.
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_move=None, on_click=None, on_scroll=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_move=on_move, on_click=on_click, on_scroll=on_scroll,
suppress=suppress)
# pylint: enable=W0223
pynput-1.7.6/lib/pynput/mouse/_darwin.py 0000664 0000000 0000000 00000015117 14164131047 0020324 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
The mouse implementation for *macOS*.
"""
# pylint: disable=C0111
# The documentation is extracted from the base classes
# pylint: disable=R0903
# We implement stubs
import enum
import Quartz
from AppKit import NSEvent
from pynput._util.darwin import (
ListenerMixin)
from . import _base
def _button_value(base_name, mouse_button):
"""Generates the value tuple for a :class:`Button` value.
:param str base_name: The base name for the button. This should be a string
like ``'kCGEventLeftMouse'``.
:param int mouse_button: The mouse button ID.
:return: a value tuple
"""
return (
tuple(
getattr(Quartz, '%sMouse%s' % (base_name, name))
for name in ('Down', 'Up', 'Dragged')),
mouse_button)
class Button(enum.Enum):
"""The various buttons.
"""
unknown = None
left = _button_value('kCGEventLeft', 0)
middle = _button_value('kCGEventOther', 2)
right = _button_value('kCGEventRight', 1)
class Controller(_base.Controller):
#: The scroll speed
_SCROLL_SPEED = 10
def __init__(self, *args, **kwargs):
super(Controller, self).__init__(*args, **kwargs)
self._click = None
self._drag_button = None
def _position_get(self):
pos = NSEvent.mouseLocation()
return pos.x, Quartz.CGDisplayPixelsHigh(0) - pos.y
def _position_set(self, pos):
try:
(_, _, mouse_type), mouse_button = self._drag_button.value
except AttributeError:
mouse_type = Quartz.kCGEventMouseMoved
mouse_button = 0
Quartz.CGEventPost(
Quartz.kCGHIDEventTap,
Quartz.CGEventCreateMouseEvent(
None,
mouse_type,
pos,
mouse_button))
def _scroll(self, dx, dy):
dx = int(dx)
dy = int(dy)
Quartz.CGEventPost(
Quartz.kCGHIDEventTap,
Quartz.CGEventCreateScrollWheelEvent(
None,
Quartz.kCGScrollEventUnitPixel,
2,
dy * self._SCROLL_SPEED,
dx * self._SCROLL_SPEED))
def _press(self, button):
(press, _, _), mouse_button = button.value
event = Quartz.CGEventCreateMouseEvent(
None,
press,
self.position,
mouse_button)
# If we are performing a click, we need to set this state flag
if self._click is not None:
self._click += 1
Quartz.CGEventSetIntegerValueField(
event,
Quartz.kCGMouseEventClickState,
self._click)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)
# Store the button to enable dragging
self._drag_button = button
def _release(self, button):
(_, release, _), mouse_button = button.value
event = Quartz.CGEventCreateMouseEvent(
None,
release,
self.position,
mouse_button)
# If we are performing a click, we need to set this state flag
if self._click is not None:
Quartz.CGEventSetIntegerValueField(
event,
Quartz.kCGMouseEventClickState,
self._click)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)
if button == self._drag_button:
self._drag_button = None
def __enter__(self):
self._click = 0
return self
def __exit__(self, exc_type, value, traceback):
self._click = None
class Listener(ListenerMixin, _base.Listener):
#: The events that we listen to
_EVENTS = (
Quartz.CGEventMaskBit(Quartz.kCGEventMouseMoved) |
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseDragged) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseDragged) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseDragged) |
Quartz.CGEventMaskBit(Quartz.kCGEventScrollWheel))
def __init__(self, *args, **kwargs):
super(Listener, self).__init__(*args, **kwargs)
self._intercept = self._options.get(
'intercept',
None)
def _handle(self, _proxy, event_type, event, _refcon):
"""The callback registered with *macOS* for mouse events.
This method will call the callbacks registered on initialisation.
"""
try:
(px, py) = Quartz.CGEventGetLocation(event)
except AttributeError:
# This happens during teardown of the virtual machine
return
# Quickly detect the most common event type
if event_type == Quartz.kCGEventMouseMoved:
self.on_move(px, py)
elif event_type == Quartz.kCGEventScrollWheel:
dx = Quartz.CGEventGetIntegerValueField(
event,
Quartz.kCGScrollWheelEventDeltaAxis2)
dy = Quartz.CGEventGetIntegerValueField(
event,
Quartz.kCGScrollWheelEventDeltaAxis1)
self.on_scroll(px, py, dx, dy)
else:
for button in Button:
try:
(press, release, drag), _ = button.value
except TypeError:
# Button.unknown cannot be enumerated
continue
# Press and release generate click events, and drag
# generates move events
if event_type in (press, release):
self.on_click(px, py, button, event_type == press)
elif event_type == drag:
self.on_move(px, py)
pynput-1.7.6/lib/pynput/mouse/_dummy.py 0000664 0000000 0000000 00000001552 14164131047 0020171 0 ustar 00root root 0000000 0000000 # pynput
# Copyright (C) 2015-2022 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 .
"""
This module contains a dummy implementation.
It cannot be used, but importing it will not raise any exceptions.
"""
from ._base import Button, Controller, Listener
pynput-1.7.6/lib/pynput/mouse/_win32.py 0000664 0000000 0000000 00000015253 14164131047 0020003 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
The mouse implementation for *Windows*.
"""
# pylint: disable=C0111
# The documentation is extracted from the base classes
# pylint: disable=R0903
# We implement stubs
import ctypes
import enum
from ctypes import (
windll,
wintypes)
from pynput._util import NotifierMixin
from pynput._util.win32 import (
INPUT,
INPUT_union,
ListenerMixin,
MOUSEINPUT,
SendInput,
SystemHook)
from . import _base
#: A constant used as a factor when constructing mouse scroll data.
WHEEL_DELTA = 120
class Button(enum.Enum):
"""The various buttons.
"""
unknown = None
left = (MOUSEINPUT.LEFTUP, MOUSEINPUT.LEFTDOWN, 0)
middle = (MOUSEINPUT.MIDDLEUP, MOUSEINPUT.MIDDLEDOWN, 0)
right = (MOUSEINPUT.RIGHTUP, MOUSEINPUT.RIGHTDOWN, 0)
x1 = (MOUSEINPUT.XUP, MOUSEINPUT.XDOWN, MOUSEINPUT.XBUTTON1)
x2 = (MOUSEINPUT.XUP, MOUSEINPUT.XDOWN, MOUSEINPUT.XBUTTON2)
class Controller(NotifierMixin, _base.Controller):
__GetCursorPos = windll.user32.GetCursorPos
__SetCursorPos = windll.user32.SetCursorPos
def __init__(self, *args, **kwargs):
super(Controller, self).__init__(*args, **kwargs)
def _position_get(self):
point = wintypes.POINT()
if self.__GetCursorPos(ctypes.byref(point)):
return (point.x, point.y)
else:
return None
def _position_set(self, pos):
pos = int(pos[0]), int(pos[1])
self.__SetCursorPos(*pos)
self._emit('on_move', *pos)
def _scroll(self, dx, dy):
if dy:
SendInput(
1,
ctypes.byref(INPUT(
type=INPUT.MOUSE,
value=INPUT_union(
mi=MOUSEINPUT(
dwFlags=MOUSEINPUT.WHEEL,
mouseData=int(dy * WHEEL_DELTA))))),
ctypes.sizeof(INPUT))
if dx:
SendInput(
1,
ctypes.byref(INPUT(
type=INPUT.MOUSE,
value=INPUT_union(
mi=MOUSEINPUT(
dwFlags=MOUSEINPUT.HWHEEL,
mouseData=int(dx * WHEEL_DELTA))))),
ctypes.sizeof(INPUT))
if dx or dy:
px, py = self._position_get()
self._emit('on_scroll', px, py, dx, dy)
def _press(self, button):
SendInput(
1,
ctypes.byref(INPUT(
type=INPUT.MOUSE,
value=INPUT_union(
mi=MOUSEINPUT(
dwFlags=button.value[1],
mouseData=button.value[2])))),
ctypes.sizeof(INPUT))
def _release(self, button):
SendInput(
1,
ctypes.byref(INPUT(
type=INPUT.MOUSE,
value=INPUT_union(
mi=MOUSEINPUT(
dwFlags=button.value[0],
mouseData=button.value[2])))),
ctypes.sizeof(INPUT))
@Controller._receiver
class Listener(ListenerMixin, _base.Listener):
#: The Windows hook ID for low level mouse events, ``WH_MOUSE_LL``
_EVENTS = 14
WM_LBUTTONDOWN = 0x0201
WM_LBUTTONUP = 0x0202
WM_MBUTTONDOWN = 0x0207
WM_MBUTTONUP = 0x0208
WM_MOUSEMOVE = 0x0200
WM_MOUSEWHEEL = 0x020A
WM_MOUSEHWHEEL = 0x020E
WM_RBUTTONDOWN = 0x0204
WM_RBUTTONUP = 0x0205
WM_XBUTTONDOWN = 0x20B
WM_XBUTTONUP = 0x20C
MK_XBUTTON1 = 0x0020
MK_XBUTTON2 = 0x0040
XBUTTON1 = 1
XBUTTON2 = 2
#: A mapping from messages to button events
CLICK_BUTTONS = {
WM_LBUTTONDOWN: (Button.left, True),
WM_LBUTTONUP: (Button.left, False),
WM_MBUTTONDOWN: (Button.middle, True),
WM_MBUTTONUP: (Button.middle, False),
WM_RBUTTONDOWN: (Button.right, True),
WM_RBUTTONUP: (Button.right, False)}
#: A mapping from message to X button events.
X_BUTTONS = {
WM_XBUTTONDOWN: {
XBUTTON1: (Button.x1, True),
XBUTTON2: (Button.x2, True)},
WM_XBUTTONUP: {
XBUTTON1: (Button.x1, False),
XBUTTON2: (Button.x2, False)}}
#: A mapping from messages to scroll vectors
SCROLL_BUTTONS = {
WM_MOUSEWHEEL: (0, 1),
WM_MOUSEHWHEEL: (1, 0)}
_HANDLED_EXCEPTIONS = (
SystemHook.SuppressException,)
class _MSLLHOOKSTRUCT(ctypes.Structure):
"""Contains information about a mouse event passed to a ``WH_MOUSE_LL``
hook procedure, ``MouseProc``.
"""
_fields_ = [
('pt', wintypes.POINT),
('mouseData', wintypes.DWORD),
('flags', wintypes.DWORD),
('time', wintypes.DWORD),
('dwExtraInfo', ctypes.c_void_p)]
#: A pointer to a :class:`_MSLLHOOKSTRUCT`
_LPMSLLHOOKSTRUCT = ctypes.POINTER(_MSLLHOOKSTRUCT)
def __init__(self, *args, **kwargs):
super(Listener, self).__init__(*args, **kwargs)
self._event_filter = self._options.get(
'event_filter',
lambda msg, data: True)
def _handle(self, code, msg, lpdata):
if code != SystemHook.HC_ACTION:
return
data = ctypes.cast(lpdata, self._LPMSLLHOOKSTRUCT).contents
# Suppress further propagation of the event if it is filtered
if self._event_filter(msg, data) is False:
return
if msg == self.WM_MOUSEMOVE:
self.on_move(data.pt.x, data.pt.y)
elif msg in self.CLICK_BUTTONS:
button, pressed = self.CLICK_BUTTONS[msg]
self.on_click(data.pt.x, data.pt.y, button, pressed)
elif msg in self.X_BUTTONS:
button, pressed = self.X_BUTTONS[msg][data.mouseData >> 16]
self.on_click(data.pt.x, data.pt.y, button, pressed)
elif msg in self.SCROLL_BUTTONS:
mx, my = self.SCROLL_BUTTONS[msg]
dd = wintypes.SHORT(data.mouseData >> 16).value // WHEEL_DELTA
self.on_scroll(data.pt.x, data.pt.y, dd * mx, dd * my)
pynput-1.7.6/lib/pynput/mouse/_xorg.py 0000664 0000000 0000000 00000012461 14164131047 0020016 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pynput
# Copyright (C) 2015-2022 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 .
"""
The keyboard implementation for *Xorg*.
"""
# pylint: disable=C0111
# The documentation is extracted from the base classes
# pylint: disable=E1101,E1102
# We dynamically generate the Button class
# 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 Xlib.display
import Xlib.ext
import Xlib.ext.xtest
import Xlib.X
import Xlib.protocol
from pynput._util.xorg import (
display_manager,
ListenerMixin)
from . import _base
# pylint: disable=C0103
Button = enum.Enum(
'Button',
module=__name__,
names=[
('unknown', None),
('left', 1),
('middle', 2),
('right', 3),
('scroll_up', 4),
('scroll_down', 5),
('scroll_left', 6),
('scroll_right', 7)] + [
('button%d' % i, i)
for i in range(8, 31)])
# pylint: enable=C0103
class Controller(_base.Controller):
def __init__(self, *args, **kwargs):
super(Controller, self).__init__(*args, **kwargs)
self._display = Xlib.display.Display()
def __del__(self):
if hasattr(self, '_display'):
self._display.close()
def _position_get(self):
with display_manager(self._display) as dm:
qp = dm.screen().root.query_pointer()
return (qp.root_x, qp.root_y)
def _position_set(self, pos):
px, py = self._check_bounds(*pos)
with display_manager(self._display) as dm:
Xlib.ext.xtest.fake_input(dm, Xlib.X.MotionNotify, x=px, y=py)
def _scroll(self, dx, dy):
dx, dy = self._check_bounds(dx, dy)
if dy:
self.click(
button=Button.scroll_up if dy > 0 else Button.scroll_down,
count=abs(dy))
if dx:
self.click(
button=Button.scroll_right if dx > 0 else Button.scroll_left,
count=abs(dx))
def _press(self, button):
with display_manager(self._display) as dm:
Xlib.ext.xtest.fake_input(dm, Xlib.X.ButtonPress, button.value)
def _release(self, button):
with display_manager(self._display) as dm:
Xlib.ext.xtest.fake_input(dm, Xlib.X.ButtonRelease, button.value)
def _check_bounds(self, *args):
"""Checks the arguments and makes sure they are within the bounds of a
short integer.
:param args: The values to verify.
"""
if not all(
(-0x7fff - 1) <= number <= 0x7fff
for number in args):
raise ValueError(args)
else:
return tuple(int(p) for p in args)
class Listener(ListenerMixin, _base.Listener):
#: A mapping from button values to scroll directions
_SCROLL_BUTTONS = {
Button.scroll_up.value: (0, 1),
Button.scroll_down.value: (0, -1),
Button.scroll_right.value: (1, 0),
Button.scroll_left.value: (-1, 0)}
_EVENTS = (
Xlib.X.ButtonPressMask,
Xlib.X.ButtonReleaseMask)
def __init__(self, *args, **kwargs):
super(Listener, self).__init__(*args, **kwargs)
def _handle(self, dummy_display, event):
px = event.root_x
py = event.root_y
if event.type == Xlib.X.ButtonPress:
# Scroll events are sent as button presses with the scroll
# button codes
scroll = self._SCROLL_BUTTONS.get(event.detail, None)
if scroll:
self.on_scroll(px, py, *scroll)
else:
self.on_click(px, py, self._button(event.detail), True)
elif event.type == Xlib.X.ButtonRelease:
# Send an event only if this was not a scroll event
if event.detail not in self._SCROLL_BUTTONS:
self.on_click(px, py, self._button(event.detail), False)
else:
self.on_move(px, py)
def _suppress_start(self, display):
display.screen().root.grab_pointer(
True, self._event_mask, Xlib.X.GrabModeAsync, Xlib.X.GrabModeAsync,
0, 0, Xlib.X.CurrentTime)
def _suppress_stop(self, display):
display.ungrab_pointer(Xlib.X.CurrentTime)
# pylint: disable=R0201
def _button(self, detail):
"""Creates a mouse button from an event detail.
If the button is unknown, :attr:`Button.unknown` is returned.
:param detail: The event detail.
:return: a button
"""
try:
return Button(detail)
except ValueError:
return Button.unknown
# pylint: enable=R0201
pynput-1.7.6/pylintrc 0000664 0000000 0000000 00000033252 14164131047 0014661 0 ustar 00root root 0000000 0000000 [MASTER]
# Specify a configuration file.
#rcfile=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Add files or directories to the blacklist. They should be base names, not
# paths.
ignore=CVS
# Add files or directories matching the regex patterns to the blacklist. The
# regex matches against base names, not paths.
ignore-patterns=
# Pickle collected data for later comparisons.
persistent=yes
# List of plugins (as comma separated values of python modules names) to load,
# usually to register additional checkers.
load-plugins=
# Use multiple processes to speed up Pylint.
jobs=1
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code
extension-pkg-whitelist=
# Allow optimization of some AST trees. This will activate a peephole AST
# optimizer, which will apply various small optimizations. For instance, it can
# be used to obtain the result of joining multiple strings with the addition
# operator. Joining a lot of strings can lead to a maximum recursion error in
# Pylint and this flag can prevent that. It has one side effect, the resulting
# AST will be different than the one from reality. This option is deprecated
# and it will be removed in Pylint 2.0.
optimize-ast=no
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
confidence=
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
#enable=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once).You can also use "--disable=all" to
# disable everything first and then reenable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
disable=suppressed-message,cmp-method,next-method-called,buffer-builtin,dict-iter-method,old-raise-syntax,coerce-builtin,reload-builtin,round-builtin,file-builtin,using-cmp-argument,print-statement,basestring-builtin,range-builtin-not-iterating,zip-builtin-not-iterating,filter-builtin-not-iterating,old-division,parameter-unpacking,coerce-method,cmp-builtin,unpacking-in-except,import-star-module-level,long-suffix,standarderror-builtin,metaclass-assignment,oct-method,intern-builtin,backtick,apply-builtin,hex-method,setslice-method,delslice-method,indexing-exception,raw_input-builtin,dict-view-method,old-octal-literal,unicode-builtin,raising-string,getslice-method,unichr-builtin,nonzero-method,old-ne-operator,map-builtin-not-iterating,execfile-builtin,input-builtin,no-absolute-import,long-builtin,xrange-builtin,reduce-builtin,useless-suppression,import-error,useless-object-inheritance,too-few-public-methods,abstract-method
[REPORTS]
# Set the output format. Available formats are text, parseable, colorized, msvs
# (visual studio) and html. You can also give a reporter class, eg
# mypackage.mymodule.MyReporterClass.
output-format=text
# Put messages in a separate file for each module / package specified on the
# command line instead of printing them on stdout. Reports (if any) will be
# written in a file name "pylint_global.[txt|html]". This option is deprecated
# and it will be removed in Pylint 2.0.
files-output=no
# Tells whether to display a full report or only the messages
reports=yes
# Python expression which should return a note less than 10 (10 is the highest
# note). You have access to the variables errors warning, statement which
# respectively contain the number of errors / warnings messages and the total
# number of statements analyzed. This is used by the global evaluation report
# (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details
#msg-template=
[LOGGING]
# Logging modules to check that the string format arguments are in logging
# function parameter format
logging-modules=logging
[FORMAT]
# Maximum number of characters on a single line.
max-line-length=80
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )??$
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
# List of optional constructs for which whitespace checking is disabled. `dict-
# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
# `trailing-comma` allows a space between comma and closing bracket: (a, ).
# `empty-line` allows space-only lines.
no-space-check=trailing-comma,dict-separator
# Maximum number of lines in a module
max-module-lines=1000
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=LF
[SIMILARITIES]
# Minimum lines number of a similarity.
min-similarity-lines=4
# Ignore comments when computing similarities.
ignore-comments=yes
# Ignore docstrings when computing similarities.
ignore-docstrings=yes
# Ignore imports when computing similarities.
ignore-imports=no
[VARIABLES]
# Tells whether we should check for unused import in __init__ files.
init-import=no
# A regular expression matching the name of dummy variables (i.e. expectedly
# not used).
dummy-variables-rgx=(dummy)?(_+[a-zA-Z0-9]*?$)
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid to define new builtins when possible.
additional-builtins=
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,_cb
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,future.builtins
[BASIC]
# Good variable names which should always be accepted, separated by a comma
good-names=e,f,i,j,k,ex,Run,_
# Bad variable names which should always be refused, separated by a comma
bad-names=foo,bar,baz,toto,tutu,tata
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Include a hint for the correct naming format with invalid-name
include-naming-hint=no
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
property-classes=abc.abstractproperty
# Regular expression matching correct variable names
variable-rgx=[a-z_][a-z0-9_]{1,30}$
# Naming hint for variable names
variable-name-hint=[a-z_][a-z0-9_]{1,30}$
# Regular expression matching correct inline iteration names
inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
# Naming hint for inline iteration names
inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$
# Regular expression matching correct class names
class-rgx=[A-Z_][a-zA-Z0-9]+$
# Naming hint for class names
class-name-hint=[A-Z_][a-zA-Z0-9]+$
# Regular expression matching correct module names
module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
# Naming hint for module names
module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
# Regular expression matching correct class attribute names
class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{1,30}|(__.*__))$
# Naming hint for class attribute names
class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{1,30}|(__.*__))$
# Regular expression matching correct argument names
argument-rgx=[a-z_][a-z0-9_]{1,30}$
# Naming hint for argument names
argument-name-hint=[a-z_][a-z0-9_]{1,30}$
# Regular expression matching correct function names
function-rgx=[a-z_][a-z0-9_]{2,30}$
# Naming hint for function names
function-name-hint=[a-z_][a-z0-9_]{2,30}$
# Regular expression matching correct constant names
const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
# Naming hint for constant names
const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$
# Regular expression matching correct attribute names
attr-rgx=[a-z_][a-z0-9_]{1,30}$
# Naming hint for attribute names
attr-name-hint=[a-z_][a-z0-9_]{1,30}$
# Regular expression matching correct method names
method-rgx=[a-z_][a-z0-9_]{2,30}$
# Naming hint for method names
method-name-hint=[a-z_][a-z0-9_]{2,30}$
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_|inner|wrapper
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
[ELIF]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,XXX,TODO
[SPELLING]
# Spelling dictionary name. Available dictionaries: none. To make it working
# install python-enchant package.
spelling-dict=
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to indicated private dictionary in
# --spelling-private-dict-file option instead of raising a message.
spelling-store-unknown-words=no
[TYPECHECK]
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis. It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=_receive,on_click,on_move,on_press,on_release,on_scroll
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
[IMPORTS]
# Deprecated modules which should not be used, separated by a comma
deprecated-modules=optparse
# Create a graph of every (i.e. internal and external) dependencies in the
# given file (report RP0402 must not be disabled)
import-graph=
# Create a graph of external dependencies in the given file (report RP0402 must
# not be disabled)
ext-import-graph=
# Create a graph of internal dependencies in the given file (report RP0402 must
# not be disabled)
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=yes
[DESIGN]
# Maximum number of arguments for function / method
max-args=5
# Argument names that match this expression will be ignored. Default to name
# with leading underscore
ignored-argument-names=_.*
# Maximum number of locals for function / method body
max-locals=15
# Maximum number of return / yield for function / method body
max-returns=6
# Maximum number of branch for function / method body
max-branches=12
# Maximum number of statements in function / method body
max-statements=50
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of boolean expressions in a if statement
max-bool-expr=5
[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,__new__,setUp
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=mcs
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,_fields,_replace,_source,_make,__altgr_mask,__alt_mask,__numlock_mask,_emitter,_event,_from_symbol,_objc,_parameters,_receiver
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "Exception"
overgeneral-exceptions=Exception
pynput-1.7.6/setup.cfg 0000664 0000000 0000000 00000000221 14164131047 0014701 0 ustar 00root root 0000000 0000000 [bdist_wheel]
universal = 1
[build_sphinx]
source-dir = docs
build-dir = build/docs
all-files = 1
[upload_sphinx]
upload-dir = build/docs/html
pynput-1.7.6/setup.py 0000664 0000000 0000000 00000007175 14164131047 0014611 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
# coding: utf-8
import os
import setuptools
#: The name of the package on PyPi
PYPI_PACKAGE_NAME = 'pynput'
#: The name of the main Python package
MAIN_PACKAGE_NAME = 'pynput'
#: The package URL
PACKAGE_URL = 'https://github.com/moses-palmer/pynput'
#: The author email
AUTHOR_EMAIL = 'moses.palmer@gmail.com'
#: The runtime requirements
RUNTIME_PACKAGES = [
'six']
#: Additional requirements used during setup
SETUP_PACKAGES = [
'setuptools-lint >=0.5',
'sphinx >=1.3.1']
#: Packages requires for different environments
EXTRA_PACKAGES = {
':sys_platform == "darwin"': [
'pyobjc-framework-ApplicationServices >=8.0',
'pyobjc-framework-Quartz >=8.0'],
':"linux" in sys_platform': [
'evdev >= 1.3',
'python-xlib >= 0.17'],
':python_version == "2.7"': [
'enum34']}
# Read globals from ._info without loading it
INFO = {}
with open(os.path.join(
os.path.dirname(__file__),
'lib',
MAIN_PACKAGE_NAME,
'_info.py'), 'rb') as f:
for line in f.read().decode('utf-8').splitlines():
try:
name, value = (i.strip() for i in line.split('='))
if name.startswith('__') and name.endswith('__'):
INFO[name[2:-2]] = eval(value)
except ValueError:
pass
# Load the read me
try:
with open(os.path.join(
os.path.dirname(__file__),
'README.rst'), 'rb') as f:
README = f.read().decode('utf-8')
with open(os.path.join(
os.path.dirname(__file__),
os.path.join('docs', 'mouse-usage.rst')), 'rb') as f:
README += '\n\n' + f.read().decode('utf-8')
with open(os.path.join(
os.path.dirname(__file__),
os.path.join('docs', 'keyboard-usage.rst')), 'rb') as f:
README += '\n\n' + f.read().decode('utf-8')
except IOError:
README = ''
# Load the release notes
try:
with open(os.path.join(
os.path.dirname(__file__),
'CHANGES.rst'), 'rb') as f:
CHANGES = f.read().decode('utf-8')
except IOError:
CHANGES = ''
setuptools.setup(
name=PYPI_PACKAGE_NAME,
version='.'.join(str(i) for i in INFO['version']),
description='Monitor and control user input devices',
long_description=README + '\n\n' + CHANGES,
install_requires=RUNTIME_PACKAGES,
setup_requires=RUNTIME_PACKAGES + SETUP_PACKAGES,
extras_require=EXTRA_PACKAGES,
author=INFO['author'],
author_email=AUTHOR_EMAIL,
url=PACKAGE_URL,
packages=setuptools.find_packages(
os.path.join(
os.path.dirname(__file__),
'lib')),
package_dir={'': 'lib'},
zip_safe=True,
test_suite='tests',
license='LGPLv3',
keywords='control mouse, mouse input, control keyboard, keyboard input',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 '
'(LGPLv3)',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows :: Windows NT/2000',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Monitoring'])
pynput-1.7.6/tests/ 0000775 0000000 0000000 00000000000 14164131047 0014227 5 ustar 00root root 0000000 0000000 pynput-1.7.6/tests/__init__.py 0000664 0000000 0000000 00000017404 14164131047 0016346 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pystray
# Copyright (C) 2015-2022 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 .
import contextlib
import functools
import time
import unittest
from six.moves import input
import pynput
#: The name of the current backend
BACKEND = pynput.keyboard.Controller.__module__.rsplit('.', 1)[-1][1:]
def _backend(name, f):
"""Returns ``f`` if the current backend is ``name``.
:param str name: The name of the backend.
:param f: A value.
:return: ``f`` or ``None``
"""
return f if name == BACKEND else None
def notify(message, delay=None, columns=50):
"""Prints a notification on screen.
:param str message: The message to display.
:param delay: An optional delay, in seconds, before returning from this
function
:type delay: float or None
:param int columns: The number of columns for the notification.
"""
# The maximum length of a message line; we need four columns for the
# frame
max_length = columns - 4
# Split the message into lines containing at most max_length characters
lines = []
for line in message.splitlines():
if lines:
lines.append('')
for word in line.split():
if not lines or not lines[-1] \
or len(lines[-1]) + 1 + len(word) > max_length:
lines.append(word)
else:
lines[-1] += ' ' + word
# Print the message
print('')
print('+' + '=' * (columns - 2) + '+')
for line in lines:
print(('| {:<%ds} |' % max_length).format(line))
print('+' + '-' * (columns - 2) + '+')
if delay:
time.sleep(delay)
#: A decorator to make a test run only on macOS
darwin = functools.partial(_backend, 'darwin')
#: A decorator to make a test run only on Windows
win32 = functools.partial(_backend, 'win32')
#: A decorator to make a test run only on Linux
xorg = functools.partial(_backend, 'xorg')
class EventTest(unittest.TestCase):
#: The message displayed when this test suite is started
NOTIFICATION = None
#: The controller class; if this is defined, :attr:`controller` will be
# instantiated for every test
CONTROLLER_CLASS = None
#: The listener class; this must be defined for subclasses
LISTENER_CLASS = None
#: The maximum number of seconds to wait before failing in
#: :meth:`assert_stop`
STOP_MAX_WAIT = 3.0
#: The minimum number of events to accumulate before checking for changes
#: in :meth:`assertChange`
CHANGE_MIN_EVENTS = 50
@classmethod
def setUpClass(self):
self.notify(self.NOTIFICATION, 4)
self.listeners = []
@classmethod
def tearDownClass(self):
remaining = [
listener
for listener in self.listeners
if not (listener.join(0.5) or listener.is_alive)]
for listener in remaining:
listener.join()
def setUp(self):
if self.CONTROLLER_CLASS is not None:
self.controller = self.CONTROLLER_CLASS()
self.suppress = False
@classmethod
def notify(self, message, delay=None, columns=50):
notify(message, delay, columns)
def listener(self, *args, **kwargs):
"""Creates a listener.
All arguments are passed to the constructor.
"""
listener = self.LISTENER_CLASS(suppress=self.suppress, *args, **kwargs)
self.listeners.append(listener)
return listener
@contextlib.contextmanager
def assert_event(self, failure_message, **kwargs):
"""Asserts that a specific event is emitted when a code block is
executed.
:param str failure_message: The message to display upon failure.
:param args: Arguments to pass to the listener constructor.
:param kwargs: Arguments to pass to the listener constructor.
"""
def wrapper(name, callback):
def inner(*a):
if callback(*a):
listener.success = True
return False
return inner if callback else None
with self.listener(**{
name: wrapper(name, callback)
for name, callback in kwargs.items()}) as listener:
time.sleep(0.1)
listener.success = False
yield
for _ in range(30):
time.sleep(0.1)
if listener.success:
break
self.assertTrue(
listener.success,
failure_message)
def assert_stop(self, failure_message, **callbacks):
"""Asserts that a listener stop within :attr:`STOP_MAX_WAIT` seconds.
:param str failure_message: The message to display upon failure.
:param args: Arguments to pass to the listener constructor.
:param callbacks: The callbacks for checking whether change has
occurred.
"""
success = False
listener = self.listener(**callbacks)
with listener:
for _ in range(10):
time.sleep(self.STOP_MAX_WAIT * 0.1)
if not listener.running:
success = True
break
self.assertTrue(
success,
failure_message)
def assert_cumulative(self, failure_message, **callbacks):
"""Asserts that the callback returns true for at least two thirds of
the elements.
At least :attr:`CHANGE_MIN_EVENTS` will be examined.
:param str failure_message: The message to display upon failure.
:param callbacks: The callbacks for checking whether change has
occurred.
"""
# The lists of accumulated events
events = {
name: []
for name in callbacks}
def wrapper(name, callback):
def inner(*a):
cache = events[name]
cache.append(a)
total_length = len(cache)
if total_length > self.CHANGE_MIN_EVENTS:
change_length = len([
None
for i, b in enumerate(cache[1:])
if callback(cache[i], b)])
if change_length > (2 * total_length) / 3:
return False
return inner if callback else None
self.assert_stop(failure_message, **{
name: wrapper(name, callback)
for name, callback in callbacks.items()})
def confirm(self, statement, *fmt):
"""Asks the user to confirm a statement.
:param str statement: The statement to confirm.
:raises AssertionError: if the user does not confirm
"""
valid_responses = ('yes', 'y', 'no', 'n')
accept_responses = valid_responses[:2]
message = ('\n' + statement % fmt) + ' '
while True:
response = input(message)
if response.lower() in valid_responses:
self.assertIn(
response.lower(), accept_responses,
'User declined statement "%s"' % message)
return
else:
print(
'Please respond %s' % ', '.join(
'"%s"' % r for r in valid_responses))
pynput-1.7.6/tests/keyboard_controller_tests.py 0000664 0000000 0000000 00000024434 14164131047 0022075 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pystray
# Copyright (C) 2015-2022 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 .
import contextlib
import locale
import sys
import threading
import pynput.keyboard
from six.moves import input
from . import EventTest
class KeyboardControllerTest(EventTest):
NOTIFICATION = (
'This test case is non-interactive, so you must not use the '
'keyboard.\n'
'You must, however, keep this window focused.')
CONTROLLER_CLASS = pynput.keyboard.Controller
LISTENER_CLASS = pynput.keyboard.Listener
def decode(self, string):
"""Decodes a string read from ``stdin``.
:param str string: The string to decode.
"""
if sys.version_info.major >= 3:
yield string
else:
for encoding in (
'utf-8',
locale.getpreferredencoding(),
sys.stdin.encoding):
if encoding:
try:
yield string.decode(encoding)
except:
pass
@contextlib.contextmanager
def capture(self):
"""Captures a string in a code block.
:returns: a callable which returns the actual data read
"""
data = []
#: The thread body that reads a line from stdin and appends it to data
def reader():
while reader.running:
data.append(sys.stdin.readline()[:-1])
reader.running = True
# Start the thread
thread = threading.Thread(target=reader)
thread.start()
# Run the code block
try:
yield lambda: tuple(self.decode(''.join(data)))
finally:
# Send a newline to let sys.stdin.readline return in reader
reader.running = False
self.controller.tap(pynput.keyboard.Key.enter)
thread.join()
def assert_input(self, failure_message, expected):
"""Asserts that a specific text is generated when typing.
:param str failure_message: The message to display upon failure.
:param text: The text to type and expect.
"""
with self.capture() as collect:
self.controller.type(expected)
self.assertIn(expected, collect(), failure_message)
def test_keys(self):
"""Asserts that all keys defined for the base keyboard interface are
defined for the current platform"""
from pynput.keyboard._base import Key
for key in Key:
self.assertTrue(
hasattr(pynput.keyboard.Key, key.name),
'%s is not defined for the current platform' % key.name)
def test_press_invalid(self):
with self.assertRaises(self.controller.InvalidKeyException):
self.controller.press(True)
def test_release_invalid(self):
with self.assertRaises(self.controller.InvalidKeyException):
self.controller.release(True)
def test_press_release(self):
"""Asserts that a press followed by a release generates a typed string
for an ascii character"""
with self.capture() as collect:
self.controller.tap(pynput.keyboard.Key.space)
self.assertIn(
u' ',
collect(),
'Failed to press and release space')
def test_touch(self):
"""Asserts that the touch shortcut behaves as expected"""
with self.capture() as collect:
self.controller.touch(pynput.keyboard.Key.space, True)
self.controller.touch(pynput.keyboard.Key.space, False)
self.assertIn(
u' ',
collect(),
'Failed to press and release space')
def test_touch_dead(self):
"""Asserts that pressing dead keys generate combined characters"""
with self.capture() as collect:
dead = pynput.keyboard.KeyCode.from_dead(u'~')
self.controller.tap(dead)
self.controller.tap(u'a')
self.assertIn(
u'ã',
collect(),
'Failed to apply dead key')
def test_touch_dead_space(self):
"""Asserts that pressing dead keys followed by space yields the
non-dead version"""
with self.capture() as collect:
dead = pynput.keyboard.KeyCode.from_dead(u'~')
self.controller.tap(dead)
self.controller.tap(pynput.keyboard.Key.space)
self.assertIn(
u'~',
collect(),
'Failed to apply dead key')
def test_touch_dead_twice(self):
"""Asserts that pressing dead keys twice yields the non-dead version"""
with self.capture() as collect:
dead = pynput.keyboard.KeyCode.from_dead(u'~')
self.controller.tap(dead)
self.controller.tap(dead)
self.assertIn(
u'~',
collect(),
'Failed to apply dead key')
def test_alt_pressed(self):
"""Asserts that alt_pressed works"""
# We do not test alt_r, since that does not necessarily exist on the
# keyboard
for key in (
pynput.keyboard.Key.alt,
pynput.keyboard.Key.alt_l):
self.controller.press(key)
self.assertTrue(
self.controller.alt_pressed,
'alt_pressed was not set with %s down' % key.name)
self.controller.release(key)
self.assertFalse(
self.controller.alt_pressed,
'alt_pressed was incorrectly set')
def test_ctrl_pressed(self):
"""Asserts that ctrl_pressed works"""
for key in (
pynput.keyboard.Key.ctrl,
pynput.keyboard.Key.ctrl_l,
pynput.keyboard.Key.ctrl_r):
self.controller.press(key)
self.assertTrue(
self.controller.ctrl_pressed,
'ctrl_pressed was not set with %s down' % key.name)
self.controller.release(key)
self.assertFalse(
self.controller.ctrl_pressed,
'ctrl_pressed was incorrectly set')
def test_shift_pressed(self):
"""Asserts that shift_pressed works with normal presses"""
for key in (
pynput.keyboard.Key.shift,
pynput.keyboard.Key.shift_l,
pynput.keyboard.Key.shift_r):
self.controller.press(key)
self.assertTrue(
self.controller.shift_pressed,
'shift_pressed was not set with %s down' % key.name)
self.controller.release(key)
self.assertFalse(
self.controller.shift_pressed,
'shift_pressed was incorrectly set')
def test_shift_pressed_caps_lock(self):
"""Asserts that shift_pressed is True when caps lock is toggled"""
self.controller.tap(pynput.keyboard.Key.caps_lock)
self.assertTrue(
self.controller.shift_pressed,
'shift_pressed was not set with caps lock toggled')
self.controller.tap(pynput.keyboard.Key.caps_lock)
self.assertFalse(
self.controller.shift_pressed,
'shift_pressed was not deactivated with caps lock toggled')
def test_pressed_shift(self):
"""Asserts that pressing and releasing a Latin character while pressing
shift causes it to shift to upper case"""
with self.capture() as collect:
with self.controller.pressed(pynput.keyboard.Key.shift):
self.controller.tap(u'a')
with self.controller.modifiers as modifiers:
self.assertIn(
pynput.keyboard.Key.shift,
modifiers)
self.assertIn(
u'A',
collect(),
'shift+a did not yield "A"')
def test_pressed_is_release(self):
"""Asserts that pressed actually releases the key"""
with self.capture() as collect:
with self.controller.pressed(pynput.keyboard.Key.shift):
self.controller.tap(u'a')
self.controller.tap(u'a')
with self.controller.pressed(pynput.keyboard.Key.shift):
self.controller.tap(u'a')
self.assertIn(
u'AaA',
collect(),
'Keys were not properly released')
def test_type_latin(self):
"""Asserts that type works for a Latin string"""
self.assert_input(
'Failed to type latin string',
u'Hello World')
def test_type_ascii(self):
"""Asserts that type works for an ascii string"""
self.assert_input(
'Failed to type ascii string',
u'abc123, "quoted!"')
def test_type_nonascii(self):
"""Asserts that type works for a non-ascii strings"""
self.assert_input(
'Failed to type Spanish string',
u'Teclado (informática)')
self.assert_input(
'Failed to type Russian string',
u'Компьютерная клавиатура')
def test_type_control_codes(self):
"""Asserts that type works for a string containing control codes"""
self.assert_input(
'Failed to type latin string',
u'Hello\tworld')
def test_controller_events(self):
"""Tests that events sent by a controller are received correctly"""
with self.assert_event(
'Failed to send press',
on_press=lambda k: getattr(k, 'char', None) == u'a'):
self.controller.press(u'a')
with self.assert_event(
'Failed to send release',
on_release=lambda k: getattr(k, 'char', None) == u'a'):
self.controller.release(u'a')
self.controller.tap(pynput.keyboard.Key.enter)
input()
pynput-1.7.6/tests/keyboard_hotkey_tests.py 0000664 0000000 0000000 00000011312 14164131047 0021204 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pystray
# Copyright (C) 2015-2022 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 .
import unittest
from six.moves import queue
from pynput.keyboard import (
GlobalHotKeys,
HotKey,
Key as k,
KeyCode as kc,
)
from . import notify
class KeyboardHotKeyTest(unittest.TestCase):
def test_parse_invalid(self):
with self.assertRaises(ValueError) as e:
HotKey.parse('invalid')
self.assertEqual(e.exception.args, ('invalid',))
with self.assertRaises(ValueError) as e:
HotKey.parse('a+')
self.assertEqual(e.exception.args, ('a+',))
with self.assertRaises(ValueError) as e:
HotKey.parse('+')
self.assertEqual(e.exception.args, ('',))
with self.assertRaises(ValueError) as e:
HotKey.parse('+a+a')
self.assertEqual(e.exception.args, ('+a+a',))
with self.assertRaises(ValueError) as e:
HotKey.parse('+a+A')
self.assertEqual(e.exception.args, ('+a+A',))
def test_parse_valid(self):
self.assertSequenceEqual(
HotKey.parse('a'),
[
kc.from_char('a')])
self.assertSequenceEqual(
HotKey.parse('A'),
[
kc.from_char('a')])
self.assertSequenceEqual(
HotKey.parse('+a'),
[
k.ctrl,
kc.from_char('a')])
self.assertSequenceEqual(
HotKey.parse('++a'),
[
k.ctrl,
k.alt,
kc.from_char('a')])
self.assertSequenceEqual(
HotKey.parse('+<123456>'),
[
k.ctrl,
kc.from_vk(123456)])
def test_activate_single(self):
activations = []
def on_activate():
activations.append(True)
hk = HotKey({kc.from_char('a')}, on_activate)
hk.press(kc.from_char('b'))
self.assertEqual(0, len(activations))
hk.release(kc.from_char('b'))
self.assertEqual(0, len(activations))
hk.press(kc.from_char('a'))
self.assertEqual(1, len(activations))
hk.release(kc.from_char('a'))
self.assertEqual(1, len(activations))
hk.press(kc.from_char('a'))
self.assertEqual(2, len(activations))
hk.press(kc.from_char('a'))
self.assertEqual(2, len(activations))
hk.release(kc.from_char('a'))
self.assertEqual(2, len(activations))
def test_activate_combo(self):
activations = []
def on_activate():
activations.append(True)
hk = HotKey({k.ctrl, kc.from_char('a')}, on_activate)
hk.press(kc.from_char('b'))
self.assertEqual(0, len(activations))
hk.release(kc.from_char('b'))
self.assertEqual(0, len(activations))
hk.press(kc.from_char('a'))
self.assertEqual(0, len(activations))
hk.release(kc.from_char('a'))
self.assertEqual(0, len(activations))
hk.press(k.ctrl)
self.assertEqual(0, len(activations))
hk.release(k.ctrl)
self.assertEqual(0, len(activations))
hk.press(kc.from_char('a'))
hk.press(k.ctrl)
self.assertEqual(1, len(activations))
hk.press(kc.from_char('a'))
hk.press(k.ctrl)
self.assertEqual(1, len(activations))
hk.release(k.ctrl)
hk.press(k.ctrl)
self.assertEqual(2, len(activations))
hk.release(kc.from_char('a'))
hk.press(kc.from_char('a'))
self.assertEqual(3, len(activations))
def test_hotkeys(self):
q = queue.Queue()
with GlobalHotKeys({
'++a': lambda: q.put('a'),
'++b': lambda: q.put('b'),
'++c': lambda: q.put('c')}):
notify('Press ++a')
self.assertEqual('a', q.get())
notify('Press ++b')
self.assertEqual('b', q.get())
notify('Press ++c')
self.assertEqual('c', q.get())
pynput-1.7.6/tests/keyboard_listener_tests.py 0000664 0000000 0000000 00000023335 14164131047 0021536 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pystray
# Copyright (C) 2015-2022 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 .
import contextlib
import six
import six.moves.queue as queue
import time
import threading
import pynput.keyboard
from . import EventTest, darwin, win32, xorg
from six.moves import input
class KeyboardListenerTest(EventTest):
NOTIFICATION = (
'This test case is interactive, so you must follow the instructions '
'on screen')
LISTENER_CLASS = pynput.keyboard.Listener
@contextlib.contextmanager
def events(self, timeout=5.0):
"""A context manager that yields keyboard events.
The context object is a generator that yields the actual events. An
event is the tuple ``(key, pressed)``.
The generator is stopped whenever the timeout is triggered. If this
happens, ``None`` will be yielded as the last event.
:param timeout: The number of seconds to wait for a key event.
"""
def generator(q):
while True:
try:
yield q.get(timeout=timeout)
except queue.Empty:
yield None
break
# Yield the generator and allow the client to capture events
q = queue.Queue()
with self.listener(
on_press=lambda k: q.put((k, True)),
on_release=lambda k: q.put((k, False))):
yield generator(q)
def assert_keys(self, failure_message, *args):
"""Asserts that the list of key events is emitted.
:param str failure_message: The message to display upon failure.
:param expected: A sequence of the tuple ``(key, pressed)``, where
``key`` is the key and ``pressed`` whether it was pressed.
``key`` may be either a string, a :class:`~pynput.keyboard.Key` or
a :class:`~pynput.keyboard.KeyCode`.
The tuple may only be a tuple of tuples, in which case any of the
values will be accepted.
"""
def normalize(event):
if not isinstance(event[0], tuple):
return normalize(((event[0],), event[1]))
key, is_pressed = event
return (
tuple(
pynput.keyboard.KeyCode.from_char(key)
if isinstance(key, six.string_types)
else key.value if key in pynput.keyboard.Key
else key
for key in event[0]),
is_pressed)
original_expected = [normalize(arg) for arg in args]
remaining = list(original_expected)
time.sleep(1)
actual = []
try:
with self.events() as events:
for event in events:
if event is None:
break
expected = remaining.pop(0)
current = normalize(event)
actual.append(current)
self.assertIn(
current[0][0],
expected[0],
'%s was not found in %s' % (
expected[0],
current[0][0]))
self.assertEqual(
current[1],
expected[1],
'Pressed state for %s was incorrect' % (
str(current[0][0])))
if not remaining:
break
# Ensure that no keys remain
self.assertSequenceEqual(
[],
remaining,
'%s ([%s] != [%s])' % (
failure_message,
' '.join(str(e) for e in original_expected),
' '.join(str(a) for a in actual)))
finally:
self.notify('Press to continue...', delay=0)
result = input()
time.sleep(1)
return result
def string_to_events(self, s):
"""Yields all events necessary to type a string.
:param str s: The string.
"""
for c in s:
yield (c, True)
yield (c, False)
def test_tap(self):
"""Tests that a single key can be tapped"""
self.notify('Press and release "a"')
self.assert_keys(
'Failed to register event',
('a', True), ('a', False))
def test_enter(self):
"""Tests that the enter key can be tapped"""
self.notify('Press ')
self.assert_keys(
'Failed to register event',
(pynput.keyboard.Key.enter, True))
def test_modifier(self):
"""Tests that the modifier keys can be tapped"""
from pynput.keyboard import Key
for key in (
(Key.alt, Key.alt_l, Key.alt_r),
(Key.ctrl, Key.ctrl_l, Key.ctrl_r),
(Key.shift, Key.shift_l, Key.shift_r)):
self.notify('Press <%s>' % key[0].name)
self.assert_keys(
'Failed to register event',
(key, True))
def test_order(self):
"""Tests that the order of key events is correct"""
self.notify('Type "hello world"')
self.assert_keys(
'Failed to register event',
*tuple(self.string_to_events('hello world')))
def test_shift(self):
"""Tests that yields capital letters"""
self.notify('Type "TEST" with pressed')
self.assert_keys(
'Failed to register event',
(
(
pynput.keyboard.Key.shift,
pynput.keyboard.Key.shift_l,
pynput.keyboard.Key.shift_r),
True),
*tuple(self.string_to_events('TEST')))
def test_modifier_and_normal(self):
"""Tests that the modifier keys do not stick"""
from pynput.keyboard import Key
self.notify('Press a, , a')
self.assert_keys(
'Failed to register event',
('a', True),
('a', False),
((Key.ctrl, Key.ctrl_l, Key.ctrl_r), True),
((Key.ctrl, Key.ctrl_l, Key.ctrl_r), False),
('a', True),
('a', False))
def test_suppress(self):
"""Tests that passing ``suppress`` prevents events from propagating"""
self.suppress = True
self.notify('Type "hello world"')
self.assertEqual(
'',
self.assert_keys(
'Failed to register event',
*tuple(self.string_to_events('hello world'))).strip())
def test_reraise(self):
"""Tests that exception are reraised"""
class MyException(Exception): pass
def on_press(key):
raise MyException()
with self.assertRaises(MyException):
with pynput.keyboard.Listener(
on_press=on_press) as l:
self.notify('Press any key')
l.join()
def test_stop(self):
"""Tests that stop works from a separate thread"""
self.notify('Do not touch the keyboard')
with pynput.keyboard.Listener() as l:
def runner():
time.sleep(1)
l.stop()
threading.Thread(target=runner).start()
l.join(2.0)
self.assertFalse(
l.is_alive(),
'Listener did not stop')
@darwin
def test_options_darwin(self):
"""Tests that options are correctly set on OSX"""
self.assertTrue(
pynput.keyboard.Listener(
darwin_test=True,
win32_test=False,
xorg_test=False)._options['test'])
@win32
def test_options_win32(self):
"""Tests that options are correctly set on Windows"""
self.assertTrue(
pynput.keyboard.Listener(
darwin_test=False,
win32_test=True,
xorg_test=False)._options['test'])
@xorg
def test_options_xorg(self):
"""Tests that options are correctly set on Linux"""
self.assertTrue(
pynput.keyboard.Listener(
darwin_test=False,
win32_test=False,
xorg_test=True)._options['test'])
def test_events(self):
"""Tests that events are correctly yielded"""
from pynput.keyboard import Key, KeyCode, Events
self.notify('Press a, b, a, ')
with Events() as events:
result = []
for event in events:
if event.key == Key.esc:
break
else:
result.append(event)
self.assertSequenceEqual(
result,
[
Events.Press(KeyCode.from_char('a')),
Events.Release(KeyCode.from_char('a')),
Events.Press(KeyCode.from_char('b')),
Events.Release(KeyCode.from_char('b')),
Events.Press(KeyCode.from_char('a')),
Events.Release(KeyCode.from_char('a')),
])
self.notify('Do not touch the keyboard', delay=2.0)
with Events() as events:
self.assertIsNone(events.get(1.0))
pynput-1.7.6/tests/mouse_controller_tests.py 0000664 0000000 0000000 00000014702 14164131047 0021422 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pystray
# Copyright (C) 2015-2022 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 .
import numbers
import pynput.mouse
import time
from . import EventTest
class MouseControllerTest(EventTest):
NOTIFICATION = (
'This test case is non-interactive, so you must not use the mouse.\n'
'You may need to keep the mouse pointer away from this window to '
'avoid interference.')
CONTROLLER_CLASS = pynput.mouse.Controller
LISTENER_CLASS = pynput.mouse.Listener
def assert_movement(self, failure_message, d):
"""Asserts that movement results in corresponding change of pointer
position.
:param str failure_message: The message to display upon failure.
:param tuple d: The movement vector.
"""
pos = self.controller.position
self.controller.move(*d)
time.sleep(1)
self.assertEqual(
self.controller.position,
tuple(o + n for o, n in zip(pos, d)),
failure_message)
def test_buttons(self):
"""Asserts that all buttons defined for the base mouse interface are
defined for the current platform"""
from pynput.mouse._base import Button
for button in Button:
self.assertTrue(
hasattr(pynput.mouse.Button, button.name),
'%s is not defined for the current platform' % button.name)
def test_position_get(self):
"""Tests that reading the position returns consistent values"""
position = self.controller.position
self.assertTrue(
all(isinstance(i, numbers.Number) for i in position),
'Not all coordinates in %s are numbers' % str(position))
self.assertEqual(
position,
self.controller.position,
'Second read of position returned different value')
def test_position_set(self):
"""Tests that writing the position updates the position value"""
position = self.controller.position
new_position = tuple(i + 1 for i in position)
self.controller.position = new_position
time.sleep(1)
self.assertEqual(
new_position,
self.controller.position,
'Updating position failed')
def test_position_set_float(self):
"""Tests that writing a floating point position does not crash"""
position = self.controller.position
new_position = tuple(i + 1.5 for i in position)
self.controller.position = new_position
def test_press(self):
"""Tests that press works"""
for b in (
pynput.mouse.Button.left,
pynput.mouse.Button.right):
with self.assert_event(
'Failed to send press event',
on_click=lambda x, y, button, pressed:
button == b and pressed):
self.controller.press(b)
self.controller.release(b)
def test_release(self):
"""Tests that release works"""
for b in (
pynput.mouse.Button.left,
pynput.mouse.Button.right):
self.controller.press(b)
with self.assert_event(
'Failed to send release event',
on_click=lambda x, y, button, pressed:
button == b and not pressed):
self.controller.release(b)
def test_left(self):
"""Tests that moving left works"""
ox, oy = self.controller.position
with self.assert_event(
'Failed to send move left event',
on_move=lambda x, y: x < ox):
self.assert_movement(
'Pointer did not move',
(-1, 0))
def test_right(self):
"""Tests that moving right works"""
ox, oy = self.controller.position
with self.assert_event(
'Failed to send move right event',
on_move=lambda x, y: x > ox):
self.assert_movement(
'Pointer did not move',
(1, 0))
def test_up(self):
"""Tests that moving up works"""
ox, oy = self.controller.position
with self.assert_event(
'Failed to send move up event',
on_move=lambda x, y: y < oy):
self.assert_movement(
'Pointer did not move',
(0, -1))
def test_down(self):
"""Tests that moving down works"""
ox, oy = self.controller.position
with self.assert_event(
'Failed to send move down event',
on_move=lambda x, y: y > oy):
self.assert_movement(
'Pointer did not move',
(0, 1))
def test_click(self):
"""Tests that click works"""
for b in (
pynput.mouse.Button.left,
pynput.mouse.Button.right):
events = [True, False]
events.reverse()
def on_click(x, y, button, pressed):
if button == b:
self.assertEqual(
pressed,
events.pop(),
'Unexpected event')
return len(events) == 0
with self.assert_event(
'Failed to send click events',
on_click=on_click):
self.controller.click(b)
def test_scroll_up(self):
"""Tests that scrolling up works"""
with self.assert_event(
'Failed to send scroll up event',
on_scroll=lambda x, y, dx, dy: dy > 0):
self.controller.scroll(0, 1)
def test_scroll_down(self):
"""Tests that scrolling down works"""
with self.assert_event(
'Failed to send scroll down event',
on_scroll=lambda x, y, dx, dy: dy < 0):
self.controller.scroll(0, -1)
pynput-1.7.6/tests/mouse_listener_tests.py 0000664 0000000 0000000 00000015442 14164131047 0021066 0 ustar 00root root 0000000 0000000 # coding=utf-8
# pystray
# Copyright (C) 2015-2022 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 .
import pynput.mouse
import time
from . import EventTest, darwin, win32, xorg
class MouseListenerTest(EventTest):
NOTIFICATION = (
'This test case is interactive, so you must follow the instructions '
'on screen.\n'
'You do not have to perform any actions on this specific window.')
LISTENER_CLASS = pynput.mouse.Listener
def test_stop(self):
"""Tests that stopping the listener from a different thread works"""
listener = self.listener()
listener.start()
listener.wait()
self.notify('Move mouse, click button or scroll')
listener.stop()
time.sleep(1)
def test_stop_no_wait(self):
"""Tests that stopping the listener from a different thread without
waiting for the listener to start works"""
listener = self.listener()
listener.start()
self.notify('Move mouse, click button or scroll')
listener.stop()
time.sleep(1)
def test_move(self):
"""Tests that move events are emitted at all"""
self.notify('Move mouse pointer')
self.assert_cumulative(
'Failed to register movement',
on_move=lambda a, b: True)
def test_left(self):
"""Tests that move left events are emitted correctly"""
self.notify('Move mouse pointer left')
self.assert_cumulative(
'Failed to register movement',
on_move=lambda a, b: b[0] < a[0])
def test_right(self):
"""Tests that move right events are emitted correctly"""
self.notify('Move mouse pointer right')
self.assert_cumulative(
'Failed to register movement',
on_move=lambda a, b: b[0] > a[0])
def test_up(self):
"""Tests that move up events are emitted correctly"""
self.notify('Move mouse pointer up')
self.assert_cumulative(
'Failed to register movement',
on_move=lambda a, b: b[1] < a[1])
def test_down(self):
"""Tests that move down events are emitted correctly"""
self.notify('Move mouse pointer down')
self.assert_cumulative(
'Failed to register movement',
on_move=lambda a, b: b[1] > a[1])
def test_click_left(self):
"""Tests that left click events are emitted"""
self.notify('Click left mouse button')
self.assert_stop(
'No left click registered',
on_click=lambda x, y, button, pressed: not (
pressed and button == pynput.mouse.Button.left))
def test_click_right(self):
"""Tests that right click events are emitted"""
self.notify('Click right mouse button')
self.assert_stop(
'No right click registered',
on_click=lambda x, y, button, pressed: not (
pressed and button == pynput.mouse.Button.right))
def test_scroll_up(self):
"""Tests that scroll up events are emitted"""
self.notify('Scroll up')
self.assert_stop(
'No scroll up registered',
on_scroll=lambda x, y, dx, dy: not (
dy > 0))
def test_scroll_down(self):
"""Tests that scroll down events are emitted"""
self.notify('Scroll down')
self.assert_stop(
'No scroll down registered',
on_scroll=lambda x, y, dx, dy: not (
dy < 0))
def test_suppress(self):
"""Tests that passing ``suppress`` prevents events from propagating"""
self.suppress = True
self.notify(
'Click right mouse button where it will have an effect, and then '
'press the left mouse button')
self.assert_stop(
'No right click registered',
on_click=lambda x, y, button, pressed: not (
pressed and button == pynput.mouse.Button.left))
self.confirm('Was the action suppressed?')
def test_reraise(self):
"""Tests that exception are reraised"""
class MyException(Exception): pass
def on_click(x, y, button, pressed):
raise MyException()
with self.assertRaises(MyException):
with pynput.mouse.Listener(
on_click=on_click) as l:
self.notify('Click any button')
l.join()
@darwin
def test_options_darwin(self):
"""Tests that options are correctly set on OSX"""
self.assertTrue(
pynput.mouse.Listener(
darwin_test=True,
win32_test=False,
xorg_test=False)._options['test'])
@win32
def test_options_win32(self):
"""Tests that options are correctly set on Windows"""
self.assertTrue(
pynput.mouse.Listener(
darwin_test=False,
win32_test=True,
xorg_test=False)._options['test'])
@xorg
def test_options_xorg(self):
"""Tests that options are correctly set on Linux"""
self.assertTrue(
pynput.mouse.Listener(
darwin_test=False,
win32_test=False,
xorg_test=True)._options['test'])
def test_events(self):
"""Tests that events are correctly yielded"""
from pynput.mouse import Button, Events
with Events() as events:
self.notify('Move the mouse')
for event in events:
if isinstance(event, Events.Move):
break
self.notify('Press the left mouse button')
for event in events:
if isinstance(event, Events.Click) \
and event.button == Button.left:
break
self.notify('Press the right mouse button')
for event in events:
if isinstance(event, Events.Click) \
and event.button == Button.right:
break
self.notify('Scroll the mouse')
for event in events:
if isinstance(event, Events.Scroll):
break
self.notify('Do not touch the mouse', delay=2.0)
self.assertIsNone(events.get(1.0))
pynput-1.7.6/tools/ 0000775 0000000 0000000 00000000000 14164131047 0014225 5 ustar 00root root 0000000 0000000 pynput-1.7.6/tools/keyboard-test.py 0000664 0000000 0000000 00000000644 14164131047 0017360 0 ustar 00root root 0000000 0000000 import os
import sys
sys.path.append(
os.path.join(os.path.dirname(__file__), '..', 'lib'))
from pynput import keyboard
def on_press(key):
print('=> %s' % key)
if key == keyboard.Key.esc:
return False
def on_release(key):
print('=< %s' % key)
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
print('Press esc to exit')
listener.join()
pynput-1.7.6/tools/make-release.py 0000775 0000000 0000000 00000014362 14164131047 0017143 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
import os
import re
import subprocess
import sys
DESCRIPTION='''Makes a full release.
This script will update the version number of the package and perform all steps
necessary to make a full release.
'''
ROOT = os.path.join(
os.path.dirname(__file__),
os.pardir)
LIB_DIR = os.path.join(ROOT, 'lib')
PACKAGE_NAME = next(
name
for name in os.listdir(LIB_DIR)
if name[0] != '_')
PACKAGE_DIR = os.path.join(LIB_DIR, PACKAGE_NAME)
def main(version):
assert_current_branch_is_clean()
update_info(version)
check_readme()
check_release_notes(version)
commit_changes(version)
try:
tag_release(version)
except:
commit_changes.undo()
raise
push_to_origin()
upload_to_pypi()
def assert_current_branch_is_clean():
"""Asserts that the current branch contains no local changes.
:raises RuntimeError: if the repository contains local changes
"""
try:
git('diff-index', '--quiet', 'HEAD', '--')
except RuntimeError as e:
print(e.args[0] % e.args[1:])
raise RuntimeError('Your repository contains local changes')
def update_info(version):
"""Updates the version information in ``._info.``
:param tuple version: The version to set.
"""
gsub(
os.path.join(PACKAGE_DIR, '_info.py'),
re.compile(r'__version__\s*=\s*(\([0-9]+(\s*,\s*[0-9]+)*\))'),
1,
repr(version))
def check_readme():
"""Verifies that the ``README`` is *reStructuredText* compliant.
"""
python('setup.py', 'check', '--restructuredtext', '--strict')
def check_release_notes(version):
"""Displays the release notes and allows the user to cancel the release
process.
:param tuple version: The version that is being released.
"""
CHANGES = os.path.join(ROOT, 'CHANGES.rst')
header = 'v%s' % '.'.join(str(v) for v in version)
# Read the release notes
found = False
release_notes = []
with open(CHANGES) as f:
for line in (l.strip() for l in f):
if found:
if not line:
# Break on the first empty line after release notes
break
elif set(line) == {'-'}:
# Ignore underline lines
continue
release_notes.append(line)
elif line.startswith(header):
# The release notes begin after the header
found = True
while True:
# Display the release notes
sys.stdout.write('Release notes for %s:\n' % header)
sys.stdout.write(
'\n'.join(
' %s' % release_note
for release_note in release_notes) + '\n')
sys.stdout.write('Is this correct [yes/no]? ')
sys.stdout.flush()
response = sys.stdin.readline().strip()
if response in ('yes', 'y'):
break
elif response in ('no', 'n'):
raise RuntimeError('Release notes are not up to date')
def commit_changes(version):
"""Commits all local changes.
:param tuple version: The version that is being released.
"""
git('commit',
'-a',
'-m', 'Release %s' % '.'.join(str(v) for v in version))
def _commit_changes_undo():
git('reset',
'--hard',
'HEAD^')
commit_changes.undo = _commit_changes_undo
def tag_release(version):
"""Tags the current commit as a release.
:param version: The version that is being released.
:type version: tuple of version parts
"""
git('tag',
'-a',
'-m', 'Release %s' % '.'.join(str(v) for v in version),
'v' + '.'.join(str(v) for v in version))
def push_to_origin():
"""Pushes master to origin.
"""
print('Pushing to origin...')
git('push', 'origin', 'HEAD:master')
git('push', '--tags')
def upload_to_pypi():
"""Uploads this project to PyPi.
"""
print('Uploading to PyPi...')
python(
os.path.join(ROOT, 'setup.py'),
'sdist',
'bdist_egg',
'bdist_wheel',
'upload')
def git(*args):
"""Executes ``git`` with the command line arguments given.
:param args: The arguments to ``git``.
:return: stdout of ``git``
:raises RuntimeError: if ``git`` returns non-zero
"""
return command('git', *args)
def python(*args):
"""Executes *Python* with the command line arguments given.
The *Python* used is the one executing the current script.
:param args: The arguments to *Python*.
:return: stdout of *Python*
:raises RuntimeError: if *Python* returns non-zero
"""
return command(sys.executable, *args)
def gsub(path, regex, group, replacement):
"""Runs a regular expression on the contents of a file and replaces a
group.
:param str path: The path to the file.
:param regex: The regular expression to use.
:param int group: The group of the regular expression to replace.
:param str replacement: The replacement string.
"""
with open(path) as f:
data = f.read()
def sub(match):
full = match.group(0)
o = match.start(0)
return full[:match.start(group) - o] \
+ replacement \
+ full[match.end(group) - o:]
with open(path, 'w') as f:
f.write(regex.sub(sub, data))
def command(*args):
"""Executes a command.
:param args: The command and arguments.
:return: stdout of the command
:raises RuntimeError: if the command returns non-zero
"""
g = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = g.communicate()
if g.returncode != 0:
raise RuntimeError(
'Failed to execute <%s> (%d): %s',
' '.join(args),
g.returncode, stderr)
else:
return stdout.decode('utf-8')
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument(
'version',
type=lambda s: tuple(int(v) for v in s.split('.')))
try:
main(**vars(parser.parse_args()))
except Exception as e:
try:
sys.stderr.write(e.args[0] % e.args[1:] + '\n')
except:
sys.stderr.write('%s\n' % str(e))
sys.exit(1)
pynput-1.7.6/tools/win32-vks.py 0000664 0000000 0000000 00000004467 14164131047 0016355 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
# coding: utf-8
# Copyright 2016 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# 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 General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see .
"""
Converts virtual key codes from to Python definitions.
"""
import datetime
import re
import sys
import unicodedata
#: The regular expression used to extract virtual key codes; they are on the
#: form:
#:
#: #define VK_
VK_RE = re.compile(r'''(?mx)
# name
\#define \s+ VK_([a-zA-Z0-9_]+)\s+
# vk
0x([0-9a-fA-F]+)\s*
# Discard rest of line
.*''')
def definitions(data):
"""Yields all virtual key codes as the tuple ``(name, vk)``.
"""
for line in data:
m = VK_RE.search(line)
if not m:
continue
name, vk = m.groups()
yield (name, int(vk, 16))
def main():
data = sys.stdin.read().splitlines()
sys.stdout.write('''# coding: utf-8
# pynput
# Copyright (C) 2015-2022-%d 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 .
# pylint: disable=C0111,C0302
%s
''' % (
datetime.date.today().year,
'\n'.join(
'%s = %d' % (name, vk)
for name, vk in definitions(data))))
main()
pynput-1.7.6/tools/xorg-keysymdef.py 0000664 0000000 0000000 00000016035 14164131047 0017561 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
# coding: utf-8
# Copyright 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# 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 General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see .
"""
Converts to Python mappings.
"""
import datetime
import re
import sys
import unicodedata
#: The regular expression used to extract normal values; they are on the form:
#:
#: #define XK_ /* */
KEYSYM_RE = re.compile(r'''(?mx)
# name
\#define \s+ XK_([a-zA-Z0-9_]+)\s+
# keysym
0x([0-9a-fA-F]+)\s+
# codepoint
/\*\s* U\+([0-9a-fA-F]+)\s+.*?\*/
# description, not present
()''')
#: The prefix used for dead keys
DEAD_PREFIX = 'dead_'
#: The regular expression used to extract dead key values; they are on the form:
#:
#: #define XK_dead_ [/* description */]
DEAD_KEYSYM_RE = re.compile(r'''(?mx)
# name
\#define \s+ XK_(%s[a-zA-Z0-9_]+)\s+
# keysym
0x([0-9a-fA-F]+)\s*
# codepoint, not present
()
# description
(?:/\*(.*?)\*/)?''' % DEAD_PREFIX)
#: The prefix used for keypad keys
KEYPAD_PREFIX = 'KP_'
#: The regular expression used to extract keypad key values; they are on the
#: form:
#:
#: #define XK_KP_ [/* description */]
KP_KEYPAD_RE = re.compile(r'''(?mx)
# name
\#define \s+ XK_(%s[a-zA-Z0-9_]+)\s+
# keysym
0x([0-9a-fA-F]+)\s*
# codepoint, not present
()
# description
(?:/\*(.*?)\*/)?''' % KEYPAD_PREFIX)
def lookup(name):
"""Looks up a named unicode character.
If it does not exist, ``None`` is returned, otherwise the code point is
returned.
:return: a hex number as a string or ``None``
"""
try:
return '%04X' % ord(unicodedata.lookup(name))
except KeyError:
return None
# A mapping from dead keys to their unicode codepoints
DEAD_CODEPOINTS = {
name: (
lookup('COMBINING ' + codepoint),
lookup(codepoint))
for name, codepoint in {
'abovecomma': 'COMMA ABOVE RIGHT',
'abovedot': 'DOT ABOVE',
'abovereversedcomma': 'TURNED COMMA ABOVE',
'abovering': 'RING ABOVE',
'aboveverticalline': 'VERTICAL LINE ABOVE',
'acute': 'ACUTE ACCENT',
'belowbreve': 'BREVE BELOW',
'belowcircumflex': 'CIRCUMFLEX ACCENT BELOW',
'belowcomma': 'COMMA BELOW',
'belowdiaeresis': 'DIAERESIS BELOW',
'belowdot': 'DOT BELOW',
'belowmacron': 'MACRON BELOW',
'belowring': 'RING BELOW',
'belowtilde': 'TILDE BELOW',
'belowverticalline': 'VERTICAL LINE BELOW',
'breve': 'BREVE',
'caron': 'CARON',
'cedilla': 'CEDILLA',
'circumflex': 'CIRCUMFLEX ACCENT',
'diaeresis': 'DIAERESIS',
'doubleacute': 'DOUBLE ACUTE ACCENT',
'doublegrave': 'DOUBLE GRAVE ACCENT',
'grave': 'GRAVE ACCENT',
'hook': 'HOOK ABOVE',
'horn': 'HORN',
'invertedbreve': 'INVERTED BREVE BELOW',
'iota': 'GREEK YPOGEGRAMMENI',
'longsolidusoverlay': 'LONG SOLIDUS OVERLAY',
'lowline': 'LOW LINE',
'macron': 'MACRON',
'ogonek': 'OGONEK',
'stroke': 'SHORT STROKE OVERLAY',
'tilde': 'TILDE'}.items()}
def definitions(data):
"""Yields all keysym as the tuple ``(name, keysym, (first, second))``.
``(first, second))`` is a tuple of codepoints. The first value is the one
to use in the lookup table, and the second one is used only by dead keys to
indicate the non-combining version. If both are ``None``, the keysym is a
keypad key.
If a codepoint is ``None``, the definition is for a dead key with no
unicode codepoint.
"""
for line in data:
for regex in (KEYSYM_RE, DEAD_KEYSYM_RE, KP_KEYPAD_RE):
m = regex.search(line)
if m:
name, keysym, codepoint, description = m.groups()
if codepoint:
# If the code point is specified, this keysym corresponds
# to a normal character
yield (
name,
(keysym, (codepoint, codepoint)))
break
elif name.startswith(DEAD_PREFIX) and (
not description or 'alias for' not in description):
yield (
name,
(keysym, DEAD_CODEPOINTS.get(
name[len(DEAD_PREFIX):],
(None, None))))
break
elif name.startswith(KEYPAD_PREFIX):
yield (
name,
(keysym, (None, None)))
break
def main():
syms = sorted(list(definitions(sys.stdin.read().splitlines())))
sys.stdout.write('''# coding: utf-8
# pynput
# Copyright (C) 2015-2022-%d 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 .
# pylint: disable=C0111,C0302
SYMBOLS = {
%s}
DEAD_KEYS = {
%s}
KEYPAD_KEYS = {
%s}
CHARS = {
codepoint: name
for name, (keysym, codepoint) in SYMBOLS.items()
if codepoint}
KEYSYMS = {
keysym: name
for name, (keysym, codepoint) in SYMBOLS.items()
if codepoint}
''' % (
datetime.date.today().year,
',\n'.join(
' \'%s\': (0x%s, %s)' % (
name,
keysym,
'u\'\\u%s\'' % first if first else None)
for name, (keysym, (first, second)) in syms),
',\n'.join(
' %s: %s' % (
'u\'\\u%s\'' % first,
'u\'\\u%s\'' % second)
for name, (keysym, (first, second)) in syms
if name.startswith(DEAD_PREFIX)
and first and second and first != second),
',\n'.join(
' \'%s\': 0x%s' % (name, keysym)
for name, (keysym, (first, second)) in syms
if name.startswith(KEYPAD_PREFIX))))
main()