parent
82e5ff9874
commit
a580a64a69
@ -0,0 +1,32 @@
|
|||||||
|
# Init Section
|
||||||
|
gUserNameStr = "IMaslov" # User name
|
||||||
|
gDomainNameStr = "" # DOMAIN or EMPTY str
|
||||||
|
gDomainIsDefaultBool = True # If domain is exist and is default (default = you can type login without domain name)
|
||||||
|
|
||||||
|
def SettingsUpdate(inDict):
|
||||||
|
lRuleDomainUserDict = {
|
||||||
|
"MethodMatchURLBeforeList": [
|
||||||
|
{
|
||||||
|
"Method":"GET",
|
||||||
|
"MatchType":"Beginwith",
|
||||||
|
"URL":"/",
|
||||||
|
#"FlagAccessDefRequestGlobalAuthenticate": TestDef
|
||||||
|
"FlagAccess": True
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Method":"POST",
|
||||||
|
"MatchType":"Beginwith",
|
||||||
|
"URL":"/",
|
||||||
|
#"FlagAccessDefRequestGlobalAuthenticate": TestDef
|
||||||
|
"FlagAccess": True
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"ControlPanelKeyAllowedList": ["TestControlPanel", "RobotRDPActive","RobotScreenActive", "ControlPanel_Template"] # If empty - all is allowed
|
||||||
|
}
|
||||||
|
# Case add domain + user
|
||||||
|
inDict["Server"]["AccessUsers"]["RuleDomainUserDict"].update({(gDomainNameStr.upper(),gUserNameStr.upper()):lRuleDomainUserDict})
|
||||||
|
if gDomainIsDefaultBool:
|
||||||
|
# Case add default domain + user
|
||||||
|
inDict["Server"]["AccessUsers"]["RuleDomainUserDict"].update({("",gUserNameStr.upper()):lRuleDomainUserDict})
|
||||||
|
#Return current dict
|
||||||
|
return inDict
|
Binary file not shown.
@ -0,0 +1,674 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU 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
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
@ -0,0 +1,165 @@
|
|||||||
|
GNU LESSER GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||||
|
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.
|
@ -0,0 +1 @@
|
|||||||
|
pip
|
@ -0,0 +1,796 @@
|
|||||||
|
Metadata-Version: 2.1
|
||||||
|
Name: pynput
|
||||||
|
Version: 1.6.8
|
||||||
|
Summary: Monitor and control user input devices
|
||||||
|
Home-page: https://github.com/moses-palmer/pynput
|
||||||
|
Author: Moses Palmér
|
||||||
|
Author-email: moses.palmer@gmail.com
|
||||||
|
License: LGPLv3
|
||||||
|
Keywords: control mouse,mouse input,control keyboard,keyboard input
|
||||||
|
Platform: UNKNOWN
|
||||||
|
Classifier: Development Status :: 5 - Production/Stable
|
||||||
|
Classifier: Intended Audience :: Developers
|
||||||
|
Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
|
||||||
|
Classifier: Operating System :: MacOS :: MacOS X
|
||||||
|
Classifier: Operating System :: Microsoft :: Windows :: Windows NT/2000
|
||||||
|
Classifier: Operating System :: POSIX
|
||||||
|
Classifier: Programming Language :: Python
|
||||||
|
Classifier: Programming Language :: Python :: 2.7
|
||||||
|
Classifier: Programming Language :: Python :: 3.4
|
||||||
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
||||||
|
Classifier: Topic :: System :: Monitoring
|
||||||
|
Requires-Dist: six
|
||||||
|
Requires-Dist: python-xlib (>=0.17) ; "linux" in sys_platform
|
||||||
|
Requires-Dist: enum34 ; python_version == "2.7"
|
||||||
|
Requires-Dist: pyobjc-framework-Quartz (>=3.0) ; sys_platform == "darwin"
|
||||||
|
|
||||||
|
pynput
|
||||||
|
======
|
||||||
|
|
||||||
|
This library allows you to control and monitor input devices.
|
||||||
|
|
||||||
|
Currently, mouse and keyboard input and monitoring are supported.
|
||||||
|
|
||||||
|
See `here <https://pynput.readthedocs.io/en/latest/>`_ for the full
|
||||||
|
documentation.
|
||||||
|
|
||||||
|
|
||||||
|
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 Mac OSX
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
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('<ctrl>+<alt>+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('<ctrl>+<alt>+h pressed')
|
||||||
|
|
||||||
|
def on_activate_i():
|
||||||
|
print('<ctrl>+<alt>+i pressed')
|
||||||
|
|
||||||
|
with keyboard.GlobalHotKeys({
|
||||||
|
'<ctrl>+<alt>+h': on_activate_h,
|
||||||
|
'<ctrl>+<alt>+i': on_activate_i}) as h:
|
||||||
|
h.join()
|
||||||
|
|
||||||
|
|
||||||
|
Release Notes
|
||||||
|
=============
|
||||||
|
|
||||||
|
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 miniscule 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 depdendencies 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*.
|
||||||
|
|
||||||
|
|
@ -0,0 +1,45 @@
|
|||||||
|
pynput-1.6.8.dist-info/COPYING,sha256=jOtLnuWt7d5Hsx6XXB2QxzrSe2sWWh3NgMfFRetluQM,35147
|
||||||
|
pynput-1.6.8.dist-info/COPYING.LGPL,sha256=2n6rt7r999OuXp8iOqW9we7ORaxWncIbOwN1ILRGR2g,7651
|
||||||
|
pynput-1.6.8.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||||
|
pynput-1.6.8.dist-info/METADATA,sha256=YXg88mvIicEwjN9IVT_H4R_2d-uq93hDfTq37Fylz7g,26464
|
||||||
|
pynput-1.6.8.dist-info/RECORD,,
|
||||||
|
pynput-1.6.8.dist-info/WHEEL,sha256=h_aVn5OB2IERUjMbi2pucmR_zzWJtk303YXvhh60NJ8,110
|
||||||
|
pynput-1.6.8.dist-info/pbr.json,sha256=CAnWerrCQ6A-ekJTVVKkD9J-ia4q-xoZzQWKOlPcseQ,47
|
||||||
|
pynput-1.6.8.dist-info/top_level.txt,sha256=DpJjYf-VkYaa_COk_yUczD0pHqsLndB9SjmwcQGkXJQ,7
|
||||||
|
pynput-1.6.8.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
||||||
|
pynput/__init__.py,sha256=elRyfy1jmOK2UL0f8T69GaWPnveAhqBTcSsZi6Un3uE,1334
|
||||||
|
pynput/__pycache__/__init__.cpython-37.pyc,,
|
||||||
|
pynput/__pycache__/_info.cpython-37.pyc,,
|
||||||
|
pynput/_info.py,sha256=Hwa35n_bl4F_AxxYCD0AyJ_y3V7fpBlFtOPEyMprsoU,775
|
||||||
|
pynput/_util/__init__.py,sha256=A48qZZ8GF3boLbGiINGroDhARWzNVadnQJFNmQ_HZtk,12022
|
||||||
|
pynput/_util/__pycache__/__init__.cpython-37.pyc,,
|
||||||
|
pynput/_util/__pycache__/darwin.cpython-37.pyc,,
|
||||||
|
pynput/_util/__pycache__/win32.cpython-37.pyc,,
|
||||||
|
pynput/_util/__pycache__/win32_vks.cpython-37.pyc,,
|
||||||
|
pynput/_util/__pycache__/xorg.cpython-37.pyc,,
|
||||||
|
pynput/_util/__pycache__/xorg_keysyms.cpython-37.pyc,,
|
||||||
|
pynput/_util/darwin.py,sha256=jvMJyKSuH8afv8x8xDPQnoGP9wq5Z1RcXgD0yLY8U5g,8455
|
||||||
|
pynput/_util/win32.py,sha256=2USeAXPaOo18lbh3BSej8jfCc-Csw0dDGisqA3sgtOQ,17984
|
||||||
|
pynput/_util/win32_vks.py,sha256=6DDuKC1ikV1AwgMR8FoayP_0MxPaclPb15v_rl6NlxE,2894
|
||||||
|
pynput/_util/xorg.py,sha256=nKYLPsc5GBM9IpMg7pCfrJNA8Fdb2yPK4kgAwFT4jSo,14703
|
||||||
|
pynput/_util/xorg_keysyms.py,sha256=QAUQTPvGB8LrhcTutrpJ7rZUTwvPsZZPCD4UH-bS3fk,69338
|
||||||
|
pynput/keyboard/__init__.py,sha256=eJSSu_53QPqsVVlDAUzyh_h5lamsUmiQRe8n0EphkNY,7926
|
||||||
|
pynput/keyboard/__pycache__/__init__.cpython-37.pyc,,
|
||||||
|
pynput/keyboard/__pycache__/_base.cpython-37.pyc,,
|
||||||
|
pynput/keyboard/__pycache__/_darwin.cpython-37.pyc,,
|
||||||
|
pynput/keyboard/__pycache__/_win32.cpython-37.pyc,,
|
||||||
|
pynput/keyboard/__pycache__/_xorg.cpython-37.pyc,,
|
||||||
|
pynput/keyboard/_base.py,sha256=kmiKDaYiNmwNiqbx3zyJ-sU-ulDS-BQ2DmMiRA0mzjA,21072
|
||||||
|
pynput/keyboard/_darwin.py,sha256=GLNegrnkw-6fh5PL6ylBsnmhCw9zVWiNbmeqXMd7gbA,10934
|
||||||
|
pynput/keyboard/_win32.py,sha256=zbMTw2PvZORNRve_U7-5VjVHbKKXvWeFnHJTwiSegkk,10539
|
||||||
|
pynput/keyboard/_xorg.py,sha256=E5OPiCXUnt6uOcK16_NqXrddb251EgkvUtm9di7Vit4,21374
|
||||||
|
pynput/mouse/__init__.py,sha256=A43a6f-v7GuynK7UuPB_9waXX2O6Xl3YVsRPcwmroaI,3376
|
||||||
|
pynput/mouse/__pycache__/__init__.cpython-37.pyc,,
|
||||||
|
pynput/mouse/__pycache__/_base.cpython-37.pyc,,
|
||||||
|
pynput/mouse/__pycache__/_darwin.cpython-37.pyc,,
|
||||||
|
pynput/mouse/__pycache__/_win32.cpython-37.pyc,,
|
||||||
|
pynput/mouse/__pycache__/_xorg.cpython-37.pyc,,
|
||||||
|
pynput/mouse/_base.py,sha256=lYuhI2gf_s9q41-a1E_EOR-I3_ZRwsxJmj09gfijVaU,8432
|
||||||
|
pynput/mouse/_darwin.py,sha256=HNxeSpy6HhT3Lg4oMm8P7KywGyiqsX6_xRE2Wp1-XuI,6961
|
||||||
|
pynput/mouse/_win32.py,sha256=dQfOOe4oM3IROoxNhiT_PUAG-G3Xfguoo64_HqlyaE8,5987
|
||||||
|
pynput/mouse/_xorg.py,sha256=Rwix3AplznT1aJXLpRihn_azwydN_B9i-097WhPw7AQ,5242
|
@ -0,0 +1,6 @@
|
|||||||
|
Wheel-Version: 1.0
|
||||||
|
Generator: bdist_wheel (0.33.4)
|
||||||
|
Root-Is-Purelib: true
|
||||||
|
Tag: py2-none-any
|
||||||
|
Tag: py3-none-any
|
||||||
|
|
@ -0,0 +1 @@
|
|||||||
|
{"is_release": false, "git_version": "2d6ab69"}
|
@ -0,0 +1 @@
|
|||||||
|
pynput
|
@ -0,0 +1 @@
|
|||||||
|
|
@ -0,0 +1,41 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
The 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
|
@ -0,0 +1,19 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pystray
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
__author__ = u'Moses Palmér'
|
||||||
|
__version__ = (1, 6, 8)
|
@ -0,0 +1,386 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
General utility functions and classes.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# pylint: disable=R0903
|
||||||
|
# We implement minimal mixins
|
||||||
|
|
||||||
|
# pylint: disable=W0212
|
||||||
|
# We implement an internal API
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import functools
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
|
||||||
|
import six
|
||||||
|
|
||||||
|
from six.moves import queue
|
||||||
|
|
||||||
|
|
||||||
|
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)))
|
||||||
|
|
||||||
|
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
|
||||||
|
"""
|
||||||
|
event = self._event_queue.get(timeout=timeout)
|
||||||
|
return event if event is not self._sentinel else 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)
|
@ -0,0 +1,274 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
Utility functions and classes for the *Darwin* backend.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# pylint: disable=C0103
|
||||||
|
# pylint: disable=R0903
|
||||||
|
# This module contains wrapper classes
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import ctypes
|
||||||
|
import ctypes.util
|
||||||
|
import six
|
||||||
|
|
||||||
|
import objc
|
||||||
|
import CoreFoundation
|
||||||
|
import Quartz
|
||||||
|
|
||||||
|
from . import AbstractListener
|
||||||
|
|
||||||
|
|
||||||
|
#: The objc module as a library handle
|
||||||
|
OBJC = ctypes.PyDLL(objc._objc.__file__)
|
||||||
|
|
||||||
|
OBJC.PyObjCObject_New.restype = ctypes.py_object
|
||||||
|
OBJC.PyObjCObject_New.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]
|
||||||
|
|
||||||
|
|
||||||
|
def _wrap_value(value):
|
||||||
|
"""Converts a pointer to a *Python objc* value.
|
||||||
|
|
||||||
|
:param value: The pointer to convert.
|
||||||
|
|
||||||
|
:return: a wrapped value
|
||||||
|
"""
|
||||||
|
return OBJC.PyObjCObject_New(value, 0, 1)
|
||||||
|
|
||||||
|
|
||||||
|
@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()
|
||||||
|
|
||||||
|
def _run(self):
|
||||||
|
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 *Mac OSX* 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()
|
@ -0,0 +1,592 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
Utility functions and classes for the *win32* backend.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# pylint: disable=C0103
|
||||||
|
# We want to make it obvious how structs are related
|
||||||
|
|
||||||
|
# pylint: disable=R0903
|
||||||
|
# This module contains a number of structs
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import ctypes
|
||||||
|
import itertools
|
||||||
|
import threading
|
||||||
|
|
||||||
|
from ctypes import (
|
||||||
|
windll,
|
||||||
|
wintypes)
|
||||||
|
|
||||||
|
from . import AbstractListener, win32_vks as VK
|
||||||
|
|
||||||
|
|
||||||
|
# LPDWORD is not in ctypes.wintypes on Python 2
|
||||||
|
if not hasattr(wintypes, 'LPDWORD'):
|
||||||
|
wintypes.LPDWORD = ctypes.POINTER(wintypes.DWORD)
|
||||||
|
|
||||||
|
|
||||||
|
class MOUSEINPUT(ctypes.Structure):
|
||||||
|
"""Contains information about a simulated mouse event.
|
||||||
|
"""
|
||||||
|
MOVE = 0x0001
|
||||||
|
LEFTDOWN = 0x0002
|
||||||
|
LEFTUP = 0x0004
|
||||||
|
RIGHTDOWN = 0x0008
|
||||||
|
RIGHTUP = 0x0010
|
||||||
|
MIDDLEDOWN = 0x0020
|
||||||
|
MIDDLEUP = 0x0040
|
||||||
|
XDOWN = 0x0080
|
||||||
|
XUP = 0x0100
|
||||||
|
WHEEL = 0x0800
|
||||||
|
HWHEEL = 0x1000
|
||||||
|
ABSOLUTE = 0x8000
|
||||||
|
|
||||||
|
XBUTTON1 = 0x0001
|
||||||
|
XBUTTON2 = 0x0002
|
||||||
|
|
||||||
|
_fields_ = [
|
||||||
|
('dx', wintypes.LONG),
|
||||||
|
('dy', wintypes.LONG),
|
||||||
|
('mouseData', wintypes.DWORD),
|
||||||
|
('dwFlags', wintypes.DWORD),
|
||||||
|
('time', wintypes.DWORD),
|
||||||
|
('dwExtraInfo', ctypes.c_void_p)]
|
||||||
|
|
||||||
|
|
||||||
|
class KEYBDINPUT(ctypes.Structure):
|
||||||
|
"""Contains information about a simulated keyboard event.
|
||||||
|
"""
|
||||||
|
EXTENDEDKEY = 0x0001
|
||||||
|
KEYUP = 0x0002
|
||||||
|
SCANCODE = 0x0008
|
||||||
|
UNICODE = 0x0004
|
||||||
|
|
||||||
|
_fields_ = [
|
||||||
|
('wVk', wintypes.WORD),
|
||||||
|
('wScan', wintypes.WORD),
|
||||||
|
('dwFlags', wintypes.DWORD),
|
||||||
|
('time', wintypes.DWORD),
|
||||||
|
('dwExtraInfo', ctypes.c_void_p)]
|
||||||
|
|
||||||
|
|
||||||
|
class HARDWAREINPUT(ctypes.Structure):
|
||||||
|
"""Contains information about a simulated message generated by an input
|
||||||
|
device other than a keyboard or mouse.
|
||||||
|
"""
|
||||||
|
_fields_ = [
|
||||||
|
('uMsg', wintypes.DWORD),
|
||||||
|
('wParamL', wintypes.WORD),
|
||||||
|
('wParamH', wintypes.WORD)]
|
||||||
|
|
||||||
|
|
||||||
|
class INPUT_union(ctypes.Union):
|
||||||
|
"""Represents the union of input types in :class:`INPUT`.
|
||||||
|
"""
|
||||||
|
_fields_ = [
|
||||||
|
('mi', MOUSEINPUT),
|
||||||
|
('ki', KEYBDINPUT),
|
||||||
|
('hi', HARDWAREINPUT)]
|
||||||
|
|
||||||
|
|
||||||
|
class INPUT(ctypes.Structure):
|
||||||
|
"""Used by :attr:`SendInput` to store information for synthesizing input
|
||||||
|
events such as keystrokes, mouse movement, and mouse clicks.
|
||||||
|
"""
|
||||||
|
MOUSE = 0
|
||||||
|
KEYBOARD = 1
|
||||||
|
HARDWARE = 2
|
||||||
|
|
||||||
|
_fields_ = [
|
||||||
|
('type', wintypes.DWORD),
|
||||||
|
('value', INPUT_union)]
|
||||||
|
|
||||||
|
|
||||||
|
LPINPUT = ctypes.POINTER(INPUT)
|
||||||
|
|
||||||
|
VkKeyScan = windll.user32.VkKeyScanW
|
||||||
|
VkKeyScan.argtypes = (
|
||||||
|
wintypes.WCHAR,)
|
||||||
|
|
||||||
|
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.DECIMAL, vks[VK.DECIMAL], 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()
|
@ -0,0 +1,179 @@
|
|||||||
|
# coding: utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
# pylint: disable=C0111,C0302
|
||||||
|
|
||||||
|
LBUTTON = 1
|
||||||
|
RBUTTON = 2
|
||||||
|
CANCEL = 3
|
||||||
|
MBUTTON = 4
|
||||||
|
XBUTTON1 = 5
|
||||||
|
XBUTTON2 = 6
|
||||||
|
BACK = 8
|
||||||
|
TAB = 9
|
||||||
|
CLEAR = 12
|
||||||
|
RETURN = 13
|
||||||
|
SHIFT = 16
|
||||||
|
CONTROL = 17
|
||||||
|
MENU = 18
|
||||||
|
PAUSE = 19
|
||||||
|
CAPITAL = 20
|
||||||
|
KANA = 21
|
||||||
|
HANGEUL = 21
|
||||||
|
HANGUL = 21
|
||||||
|
JUNJA = 23
|
||||||
|
FINAL = 24
|
||||||
|
HANJA = 25
|
||||||
|
KANJI = 25
|
||||||
|
ESCAPE = 27
|
||||||
|
CONVERT = 28
|
||||||
|
NONCONVERT = 29
|
||||||
|
ACCEPT = 30
|
||||||
|
MODECHANGE = 31
|
||||||
|
SPACE = 32
|
||||||
|
PRIOR = 33
|
||||||
|
NEXT = 34
|
||||||
|
END = 35
|
||||||
|
HOME = 36
|
||||||
|
LEFT = 37
|
||||||
|
UP = 38
|
||||||
|
RIGHT = 39
|
||||||
|
DOWN = 40
|
||||||
|
SELECT = 41
|
||||||
|
PRINT = 42
|
||||||
|
EXECUTE = 43
|
||||||
|
SNAPSHOT = 44
|
||||||
|
INSERT = 45
|
||||||
|
DELETE = 46
|
||||||
|
HELP = 47
|
||||||
|
LWIN = 91
|
||||||
|
RWIN = 92
|
||||||
|
APPS = 93
|
||||||
|
SLEEP = 95
|
||||||
|
NUMPAD0 = 96
|
||||||
|
NUMPAD1 = 97
|
||||||
|
NUMPAD2 = 98
|
||||||
|
NUMPAD3 = 99
|
||||||
|
NUMPAD4 = 100
|
||||||
|
NUMPAD5 = 101
|
||||||
|
NUMPAD6 = 102
|
||||||
|
NUMPAD7 = 103
|
||||||
|
NUMPAD8 = 104
|
||||||
|
NUMPAD9 = 105
|
||||||
|
MULTIPLY = 106
|
||||||
|
ADD = 107
|
||||||
|
SEPARATOR = 108
|
||||||
|
SUBTRACT = 109
|
||||||
|
DECIMAL = 110
|
||||||
|
DIVIDE = 111
|
||||||
|
F1 = 112
|
||||||
|
F2 = 113
|
||||||
|
F3 = 114
|
||||||
|
F4 = 115
|
||||||
|
F5 = 116
|
||||||
|
F6 = 117
|
||||||
|
F7 = 118
|
||||||
|
F8 = 119
|
||||||
|
F9 = 120
|
||||||
|
F10 = 121
|
||||||
|
F11 = 122
|
||||||
|
F12 = 123
|
||||||
|
F13 = 124
|
||||||
|
F14 = 125
|
||||||
|
F15 = 126
|
||||||
|
F16 = 127
|
||||||
|
F17 = 128
|
||||||
|
F18 = 129
|
||||||
|
F19 = 130
|
||||||
|
F20 = 131
|
||||||
|
F21 = 132
|
||||||
|
F22 = 133
|
||||||
|
F23 = 134
|
||||||
|
F24 = 135
|
||||||
|
NUMLOCK = 144
|
||||||
|
SCROLL = 145
|
||||||
|
OEM_NEC_EQUAL = 146
|
||||||
|
OEM_FJ_JISHO = 146
|
||||||
|
OEM_FJ_MASSHOU = 147
|
||||||
|
OEM_FJ_TOUROKU = 148
|
||||||
|
OEM_FJ_LOYA = 149
|
||||||
|
OEM_FJ_ROYA = 150
|
||||||
|
LSHIFT = 160
|
||||||
|
RSHIFT = 161
|
||||||
|
LCONTROL = 162
|
||||||
|
RCONTROL = 163
|
||||||
|
LMENU = 164
|
||||||
|
RMENU = 165
|
||||||
|
BROWSER_BACK = 166
|
||||||
|
BROWSER_FORWARD = 167
|
||||||
|
BROWSER_REFRESH = 168
|
||||||
|
BROWSER_STOP = 169
|
||||||
|
BROWSER_SEARCH = 170
|
||||||
|
BROWSER_FAVORITES = 171
|
||||||
|
BROWSER_HOME = 172
|
||||||
|
VOLUME_MUTE = 173
|
||||||
|
VOLUME_DOWN = 174
|
||||||
|
VOLUME_UP = 175
|
||||||
|
MEDIA_NEXT_TRACK = 176
|
||||||
|
MEDIA_PREV_TRACK = 177
|
||||||
|
MEDIA_STOP = 178
|
||||||
|
MEDIA_PLAY_PAUSE = 179
|
||||||
|
LAUNCH_MAIL = 180
|
||||||
|
LAUNCH_MEDIA_SELECT = 181
|
||||||
|
LAUNCH_APP1 = 182
|
||||||
|
LAUNCH_APP2 = 183
|
||||||
|
OEM_1 = 186
|
||||||
|
OEM_PLUS = 187
|
||||||
|
OEM_COMMA = 188
|
||||||
|
OEM_MINUS = 189
|
||||||
|
OEM_PERIOD = 190
|
||||||
|
OEM_2 = 191
|
||||||
|
OEM_3 = 192
|
||||||
|
OEM_4 = 219
|
||||||
|
OEM_5 = 220
|
||||||
|
OEM_6 = 221
|
||||||
|
OEM_7 = 222
|
||||||
|
OEM_8 = 223
|
||||||
|
OEM_AX = 225
|
||||||
|
OEM_102 = 226
|
||||||
|
ICO_HELP = 227
|
||||||
|
ICO_00 = 228
|
||||||
|
PROCESSKEY = 229
|
||||||
|
ICO_CLEAR = 230
|
||||||
|
PACKET = 231
|
||||||
|
OEM_RESET = 233
|
||||||
|
OEM_JUMP = 234
|
||||||
|
OEM_PA1 = 235
|
||||||
|
OEM_PA2 = 236
|
||||||
|
OEM_PA3 = 237
|
||||||
|
OEM_WSCTRL = 238
|
||||||
|
OEM_CUSEL = 239
|
||||||
|
OEM_ATTN = 240
|
||||||
|
OEM_FINISH = 241
|
||||||
|
OEM_COPY = 242
|
||||||
|
OEM_AUTO = 243
|
||||||
|
OEM_ENLW = 244
|
||||||
|
OEM_BACKTAB = 245
|
||||||
|
ATTN = 246
|
||||||
|
CRSEL = 247
|
||||||
|
EXSEL = 248
|
||||||
|
EREOF = 249
|
||||||
|
PLAY = 250
|
||||||
|
ZOOM = 251
|
||||||
|
NONAME = 252
|
||||||
|
PA1 = 253
|
||||||
|
OEM_CLEAR = 254
|
@ -0,0 +1,480 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
Utility functions and classes for the *Xorg* backend.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# pylint: disable=R0903
|
||||||
|
# We implement stubs
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import functools
|
||||||
|
import itertools
|
||||||
|
import operator
|
||||||
|
import Xlib.display
|
||||||
|
import Xlib.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():
|
||||||
|
display = Xlib.display.Display()
|
||||||
|
display.close()
|
||||||
|
_check()
|
||||||
|
del _check
|
||||||
|
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
:retur: 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 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
|
||||||
|
keysym = Xlib.XK.string_to_keysym(symbol)
|
||||||
|
if keysym:
|
||||||
|
return keysym
|
||||||
|
|
||||||
|
# If that fails, try checking a module attribute of Xlib.keysymdef.xkb
|
||||||
|
if not keysym:
|
||||||
|
try:
|
||||||
|
return getattr(Xlib.keysymdef.xkb, 'XK_' + symbol, 0)
|
||||||
|
except AttributeError:
|
||||||
|
return 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()
|
||||||
|
with display_manager(self._display_stop) 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_record) 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_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()
|
||||||
|
# pylint: disable=W0702; we must ignore errors
|
||||||
|
try:
|
||||||
|
with display_manager(self._display_stop) as dm:
|
||||||
|
dm.record_disable_context(self._context)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
# pylint: enable=W0702
|
||||||
|
|
||||||
|
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
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,253 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
The module containing keyboard classes.
|
||||||
|
|
||||||
|
See the documentation for more information.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# pylint: disable=C0103
|
||||||
|
# KeyCode, Key, Controller and Listener are not constants
|
||||||
|
|
||||||
|
import itertools
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
if os.environ.get('__PYNPUT_GENERATE_DOCUMENTATION') == 'yes':
|
||||||
|
from ._base import KeyCode, Key, Controller, Listener
|
||||||
|
else:
|
||||||
|
KeyCode = None
|
||||||
|
Key = None
|
||||||
|
Controller = None
|
||||||
|
Listener = None
|
||||||
|
|
||||||
|
from pynput._util import Events
|
||||||
|
|
||||||
|
|
||||||
|
if sys.platform == 'darwin':
|
||||||
|
if not KeyCode and not Key and not Controller and not Listener:
|
||||||
|
from ._darwin import KeyCode, Key, Controller, Listener
|
||||||
|
|
||||||
|
elif sys.platform == 'win32':
|
||||||
|
if not KeyCode and not Key and not Controller and not Listener:
|
||||||
|
from ._win32 import KeyCode, Key, Controller, Listener
|
||||||
|
|
||||||
|
else:
|
||||||
|
if not KeyCode and not Key and not Controller and not Listener:
|
||||||
|
try:
|
||||||
|
from ._xorg import KeyCode, Key, Controller, Listener
|
||||||
|
except ImportError:
|
||||||
|
# For now, since we only support Xlib anyway, we re-raise these
|
||||||
|
# errors to allow users to determine the cause of failures to import
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
if not KeyCode or not Key or not Controller or not Listener:
|
||||||
|
raise ImportError('this platform is not supported')
|
||||||
|
|
||||||
|
|
||||||
|
# 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 releesed.
|
||||||
|
"""
|
||||||
|
_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 ``'<ctrl>'``.
|
||||||
|
|
||||||
|
Keyboard keys are case-insensitive.
|
||||||
|
|
||||||
|
:raises ValueError: if a part of the keys string is invalid, or if it
|
||||||
|
contains multiple equal parts
|
||||||
|
"""
|
||||||
|
def parts():
|
||||||
|
start = 0
|
||||||
|
for i, c in enumerate(keys):
|
||||||
|
if c == '+' and i != start:
|
||||||
|
yield keys[start:i]
|
||||||
|
start = i + 1
|
||||||
|
if start == len(keys):
|
||||||
|
raise ValueError(keys)
|
||||||
|
else:
|
||||||
|
yield keys[start:]
|
||||||
|
|
||||||
|
def parse(s):
|
||||||
|
if len(s) == 1:
|
||||||
|
return KeyCode.from_char(s.lower())
|
||||||
|
elif len(s) > 2 and (s[0], s[-1]) == ('<', '>'):
|
||||||
|
try:
|
||||||
|
return Key[s[1:-1].lower()]
|
||||||
|
except KeyError:
|
||||||
|
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(raw_parts) != len(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))
|
@ -0,0 +1,702 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
This module contains the base implementation.
|
||||||
|
|
||||||
|
The actual interface to keyboard classes is defined here, but the
|
||||||
|
implementation is located in a platform dependent module.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# pylint: disable=R0903
|
||||||
|
# We implement stubs
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import enum
|
||||||
|
import threading
|
||||||
|
import unicodedata
|
||||||
|
|
||||||
|
import six
|
||||||
|
|
||||||
|
from pynput._util import AbstractListener
|
||||||
|
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:
|
||||||
|
self.combining = unicodedata.lookup(
|
||||||
|
'COMBINING ' + unicodedata.name(self.char))
|
||||||
|
if 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
|
||||||
|
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
self._update_modifiers(resolved, False)
|
||||||
|
|
||||||
|
# Ignore released dead keys
|
||||||
|
if resolved.is_dead:
|
||||||
|
return
|
||||||
|
|
||||||
|
self._handle(resolved, False)
|
||||||
|
|
||||||
|
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_``, ``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.
|
||||||
|
|
||||||
|
``win32_event_filter``
|
||||||
|
A callable taking the arguments ``(msg, data)``, where ``msg`` is
|
||||||
|
the current message, and ``data`` associated data as a
|
||||||
|
`KBLLHOOKSTRUCT <https://msdn.microsoft.com/en-us/library/windows/desktop/ms644967(v=vs.85).aspx>`_.
|
||||||
|
|
||||||
|
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__)
|
||||||
|
prefix = self.__class__.__module__.rsplit('.', 1)[-1][1:] + '_'
|
||||||
|
self._options = {
|
||||||
|
key[len(prefix):]: value
|
||||||
|
for key, value in kwargs.items()
|
||||||
|
if key.startswith(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
|
||||||
|
slao 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]
|
||||||
|
else:
|
||||||
|
return key
|
@ -0,0 +1,336 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
The keyboard implementation for *OSX*.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# 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 . 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)
|
||||||
|
if length > 0:
|
||||||
|
return KeyCode.from_char(chars, vk=vk)
|
||||||
|
|
||||||
|
# ...and fall back on a virtual key code
|
||||||
|
return KeyCode.from_vk(vk)
|
@ -0,0 +1,340 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
The keyboard implementation for *Windows*.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# pylint: disable=C0111
|
||||||
|
# The documentation is extracted from the base classes
|
||||||
|
|
||||||
|
# pylint: disable=R0903
|
||||||
|
# We implement stubs
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import ctypes
|
||||||
|
import enum
|
||||||
|
import six
|
||||||
|
|
||||||
|
from ctypes import wintypes
|
||||||
|
|
||||||
|
import pynput._util.win32_vks as VK
|
||||||
|
|
||||||
|
from pynput._util import AbstractListener
|
||||||
|
from pynput._util.win32 import (
|
||||||
|
INPUT,
|
||||||
|
INPUT_union,
|
||||||
|
KEYBDINPUT,
|
||||||
|
KeyTranslator,
|
||||||
|
ListenerMixin,
|
||||||
|
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 0
|
||||||
|
flags = 0
|
||||||
|
else:
|
||||||
|
res = VkKeyScan(self.char)
|
||||||
|
if (res >> 8) & 0xFF == 0:
|
||||||
|
vk = res & 0xFF
|
||||||
|
scan = self._scan or 0
|
||||||
|
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)
|
||||||
|
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 paramter 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)
|
@ -0,0 +1,638 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
The keyboard implementation for *Xorg*.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# pylint: disable=C0111
|
||||||
|
# The documentation is extracted from the base classes
|
||||||
|
|
||||||
|
# pylint: disable=R0903
|
||||||
|
# We implement stubs
|
||||||
|
|
||||||
|
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,
|
||||||
|
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 named 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 ``'XF86Audio'`` prepended.
|
||||||
|
|
||||||
|
:return: a key code
|
||||||
|
"""
|
||||||
|
return cls._from_symbol('XF86Audio' + 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
|
||||||
|
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
|
||||||
|
"""
|
||||||
|
symbol = CHARS.get(key.char, None)
|
||||||
|
if symbol is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 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)
|
@ -0,0 +1,123 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
The module containing mouse classes.
|
||||||
|
|
||||||
|
See the documentation for more information.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# pylint: disable=C0103
|
||||||
|
# Button, Controller and Listener are not constants
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
if os.environ.get('__PYNPUT_GENERATE_DOCUMENTATION') == 'yes':
|
||||||
|
from ._base import Button, Controller, Listener
|
||||||
|
else:
|
||||||
|
Button = None
|
||||||
|
Controller = None
|
||||||
|
Listener = None
|
||||||
|
|
||||||
|
from pynput._util import Events
|
||||||
|
|
||||||
|
|
||||||
|
if sys.platform == 'darwin':
|
||||||
|
if not Button and not Controller and not Listener:
|
||||||
|
from ._darwin import Button, Controller, Listener
|
||||||
|
|
||||||
|
elif sys.platform == 'win32':
|
||||||
|
if not Button and not Controller and not Listener:
|
||||||
|
from ._win32 import Button, Controller, Listener
|
||||||
|
|
||||||
|
else:
|
||||||
|
if not Button and not Controller and not Listener:
|
||||||
|
try:
|
||||||
|
from ._xorg import Button, Controller, Listener
|
||||||
|
except ImportError:
|
||||||
|
# For now, since we only support Xlib anyway, we re-raise these
|
||||||
|
# errors to allow users to determine the cause of failures to import
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
if not Button or not Controller or not Listener:
|
||||||
|
raise ImportError('this platform is not supported')
|
||||||
|
|
||||||
|
|
||||||
|
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 scoll 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)
|
@ -0,0 +1,263 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
This module contains the base implementation.
|
||||||
|
|
||||||
|
The actual interface to 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
|
||||||
|
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 x: 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 <https://msdn.microsoft.com/en-us/library/windows/desktop/ms644970(v=vs.85).aspx>`_.
|
||||||
|
|
||||||
|
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__)
|
||||||
|
prefix = self.__class__.__module__.rsplit('.', 1)[-1][1:] + '_'
|
||||||
|
self._options = {
|
||||||
|
key[len(prefix):]: value
|
||||||
|
for key, value in kwargs.items()
|
||||||
|
if key.startswith(prefix)}
|
||||||
|
super(Listener, self).__init__(
|
||||||
|
on_move=on_move, on_click=on_click, on_scroll=on_scroll,
|
||||||
|
suppress=suppress)
|
||||||
|
# pylint: enable=W0223
|
@ -0,0 +1,217 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
The mouse implementation for *OSX*.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# 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 shuld 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 = 5
|
||||||
|
|
||||||
|
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)
|
||||||
|
while dx != 0 or dy != 0:
|
||||||
|
xval = 1 if dx > 0 else -1 if dx < 0 else 0
|
||||||
|
dx -= xval
|
||||||
|
yval = 1 if dy > 0 else -1 if dy < 0 else 0
|
||||||
|
dy -= yval
|
||||||
|
|
||||||
|
Quartz.CGEventPost(
|
||||||
|
Quartz.kCGHIDEventTap,
|
||||||
|
Quartz.CGEventCreateScrollWheelEvent(
|
||||||
|
None,
|
||||||
|
Quartz.kCGScrollEventUnitPixel,
|
||||||
|
2,
|
||||||
|
yval * self._SCROLL_SPEED,
|
||||||
|
xval * 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 *Mac OSX* 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)
|
@ -0,0 +1,196 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
The 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)
|
||||||
|
middle = (MOUSEINPUT.MIDDLEUP, MOUSEINPUT.MIDDLEDOWN)
|
||||||
|
right = (MOUSEINPUT.RIGHTUP, MOUSEINPUT.RIGHTDOWN)
|
||||||
|
|
||||||
|
|
||||||
|
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])))),
|
||||||
|
ctypes.sizeof(INPUT))
|
||||||
|
|
||||||
|
def _release(self, button):
|
||||||
|
SendInput(
|
||||||
|
1,
|
||||||
|
ctypes.byref(INPUT(
|
||||||
|
type=INPUT.MOUSE,
|
||||||
|
value=INPUT_union(
|
||||||
|
mi=MOUSEINPUT(
|
||||||
|
dwFlags=button.value[0])))),
|
||||||
|
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
|
||||||
|
|
||||||
|
#: 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 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.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)
|
@ -0,0 +1,174 @@
|
|||||||
|
# coding=utf-8
|
||||||
|
# pynput
|
||||||
|
# Copyright (C) 2015-2019 Moses Palmér
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify it under
|
||||||
|
# the terms of the GNU Lesser General Public License as published by the Free
|
||||||
|
# Software Foundation, either version 3 of the License, or (at your option) any
|
||||||
|
# later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful, but WITHOUT
|
||||||
|
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
||||||
|
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
|
||||||
|
# details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU Lesser General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
"""
|
||||||
|
The keyboard implementation for *Xorg*.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# pylint: disable=C0111
|
||||||
|
# The documentation is extracted from the base classes
|
||||||
|
|
||||||
|
|
||||||
|
# pylint: disable=E1101,E1102
|
||||||
|
# We dynamically generate the Button class
|
||||||
|
|
||||||
|
# pylint: disable=R0903
|
||||||
|
# We implement stubs
|
||||||
|
|
||||||
|
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
|
@ -0,0 +1,2 @@
|
|||||||
|
..\..\Resources\WPy64-3720\python-3.7.2.amd64\python.exe WorkLogger.py
|
||||||
|
pause >nul
|
@ -0,0 +1,63 @@
|
|||||||
|
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)))
|
||||||
|
print(button)
|
||||||
|
if not pressed:
|
||||||
|
# Stop listener
|
||||||
|
return True
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
|
||||||
|
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 True
|
||||||
|
|
||||||
|
# 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()
|
Loading…
Reference in new issue