PK ûYG^ÈA)Ê Ê pynput/__init__.py# coding=utf-8
# pynput
# Copyright (C) 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see .
from . import mouse
PK oW\G#1»vC C pynput/_info.py# coding: utf8
__author__ = u'Moses Palmér'
__version__ = (0, 2)
PK ûYGæYŒëµ µ pynput/_util/__init__.py# coding=utf-8
# pynput
# Copyright (C) 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see .
PK ûYGÙæ÷IH H pynput/_util/xorg.py# coding=utf-8
# pynput
# Copyright (C) 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see .
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
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
"""
from contextlib import contextmanager
@contextmanager
def manager():
errors = []
def handler(*args):
errors.append(args)
old_handler = display.set_error_handler(handler)
yield display
display.sync()
display.set_error_handler(old_handler)
if errors:
raise X11Error(errors)
return manager()
PK ûYG€³†¸b b pynput/_util/win32.py# coding=utf-8
# pynput
# Copyright (C) 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see .
import ctypes
import threading
from ctypes import windll, wintypes
class MessageLoop(object):
"""A class representing a message loop.
"""
#: The message that signals this loop to terminate
WM_STOP = 0x0401
_GetMessage = windll.user32.GetMessageW
_PeekMessage = windll.user32.PeekMessageW
_PostThreadMessage = windll.user32.PostThreadMessageW
PM_NOREMOVE = 0
def __init__(
self,
initialize=lambda message_loop: None,
finalize=lambda message_loop: None):
self._threadid = None
self._initialize = initialize
self._finalize = finalize
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._finalize(self)
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)
# Let the called perform initialisation
self._initialize(self)
# 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()
self._PostThreadMessage(self._threadid, self.WM_STOP, 0, 0)
if self.thread != threading.current_thread():
self.thread.join()
class SystemHook(object):
"""A class to handle Windows hooks.
"""
_SetWindowsHookEx = windll.user32.SetWindowsHookExW
_UnhookWindowsHookEx = windll.user32.UnhookWindowsHookEx
_CallNextHookEx = windll.user32.CallNextHookEx
_HOOKPROC = wintypes.WINFUNCTYPE(
wintypes.LPARAM,
ctypes.c_int32, wintypes.WPARAM, wintypes.LPARAM)
#: The registered hook procedures
_HOOKS = {}
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()
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, type, value, traceback):
key = threading.current_thread()
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()
self = SystemHook._HOOKS.get(key, None)
if self:
self.on_hook(code, msg, lpdata)
# Always call the next hook
return SystemHook._CallNextHookEx(0, code, msg, lpdata)
GetCurrentThreadId = windll.kernel32.GetCurrentThreadId
SendInput = windll.user32.SendInput
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)]
PK 8W\GVû]^ ^ pynput/mouse/__init__.py# coding=utf-8
# pynput
# Copyright (C) 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see .
import os
import sys
if os.environ.get('__PYNPUT_GENERATE_DOCUMENTATION') == 'yes':
from ._base import Controller, Listener
else:
Controller = None
Listener = None
if sys.platform == 'darwin':
if Controller is None and Listener is None:
from ._darwin import Controller, Listener
elif sys.platform == 'win32':
if Controller is None and Listener is None:
from ._win32 import Controller, Listener
else:
if Controller is None and Listener is None:
try:
from ._xorg import Controller, Listener
except:
pass
if not Controller or not Listener:
raise ImportError('this platform is not supported')
PK ûYGÚŠí í pynput/mouse/_darwin.py# coding=utf-8
# pynput
# Copyright (C) 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see .
import enum
import Quartz
import threading
from AppKit import NSEvent, NSScreen
from . import _base
def _button_value(base_name, mouse_button):
"""Generates the value tuple for a :class:`Controller.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 Controller(_base.Controller):
class Button(enum.Enum):
"""The various buttons.
"""
left = _button_value('kCGEventLeft', 0)
middle = _button_value('kCGEventOther', 2)
right = _button_value('kCGEventRight', 1)
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
except TypeError:
mouse_type = Quartz.kCGEventMouseMoved
mouse_button = 0
Quartz.CGEventPost(
Quartz.kCGHIDEventTap,
Quartz.CGEventCreateMouseEvent(
None,
mouse_type,
pos,
mouse_button))
def _scroll(self, dx, 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 * 1,
xval * 1))
def _press(self, button):
(press, release, drag), 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):
(press, release, drag), 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, type, value, traceback):
self._click = None
class Listener(_base.Listener):
#: The events that we listen to
_TAP_EVENTS = (
0
| Quartz.CGEventMaskBit(Quartz.kCGEventMouseMoved)
| Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseDown)
| Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseUp)
| Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseDown)
| Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseUp)
| Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseDown)
| Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseUp)
| Quartz.CGEventMaskBit(Quartz.kCGEventScrollWheel))
def __init__(self, *args, **kwargs):
super(Listener, self).__init__(*args, **kwargs)
self._loop = None
def _run(self):
try:
tap = Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap,
Quartz.kCGHeadInsertEventTap,
Quartz.kCGEventTapOptionDefault,
self._TAP_EVENTS,
self._handler,
None)
loop_source = Quartz.CFMachPortCreateRunLoopSource(
None, tap, 0)
self._loop = Quartz.CFRunLoopGetCurrent()
Quartz.CFRunLoopAddSource(
self._loop, loop_source, Quartz.kCFRunLoopDefaultMode)
Quartz.CGEventTapEnable(tap, True)
while True:
result = Quartz.CFRunLoopRunInMode(
Quartz.kCFRunLoopDefaultMode, 1, False)
if result != Quartz.kCFRunLoopRunTimedOut:
break
finally:
self._loop = None
def _stop(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
Quartz.CFRunLoopStop(self._loop)
@_base.Listener._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.
"""
(x, y) = Quartz.CGEventGetLocation(event)
try:
# Quickly detect the most common event type
if event_type == Quartz.kCGEventMouseMoved:
self.on_move(x, y)
elif event_type == Quartz.kCGEventScrollWheel:
dx = Quartz.CGEventGetIntegerValueField(
event,
Quartz.kCGScrollWheelEventDeltaAxis2)
dy = Quartz.CGEventGetIntegerValueField(
event,
Quartz.kCGScrollWheelEventDeltaAxis1)
self.on_scroll(x, y, dx, dy)
else:
for button in Controller.Button:
(press, release, drag), mouse_button = button.value
# Press and release generate click events, and drag
# generates move events
if event_type in (press, release):
self.on_click(x, y, button, event_type == press)
elif event_type == drag:
self.on_move(x, y)
except self.StopException:
self.stop()
return event
PK ûYGÚY
ds s pynput/mouse/_win32.py# coding=utf-8
# pynput
# Copyright (C) 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see .
import enum
from pynput._util.win32 import *
from . import _base
class Controller(_base.Controller):
class Button(enum.Enum):
"""The various buttons.
"""
left = (MOUSEINPUT.LEFTUP, MOUSEINPUT.LEFTDOWN)
middle = (MOUSEINPUT.MIDDLEUP, MOUSEINPUT.MIDDLEDOWN)
right = (MOUSEINPUT.RIGHTUP, MOUSEINPUT.RIGHTDOWN)
__GetCursorPos = windll.user32.GetCursorPos
__SetCursorPos = windll.user32.SetCursorPos
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):
self.__SetCursorPos(*pos)
self._notify('on_move', *pos)
def _scroll(self, dx, dy):
if dy:
SendInput(
1,
ctypes.byref(INPUT(
type=INPUT.MOUSE,
value=INPUT_union(
mouse=MOUSEINPUT(
dwFlags=MOUSEINPUT.WHEEL,
mouseData=dy)))),
ctypes.sizeof(INPUT))
if dx:
SendInput(
1,
ctypes.byref(INPUT(
type=INPUT.MOUSE,
value=INPUT_union(
mouse=MOUSEINPUT(
dwFlags=MOUSEINPUT.HWHEEL,
mouseData=dy)))),
ctypes.sizeof(INPUT))
if dx or dy:
self._notify('on_scroll', dx, dy)
def _press(self, button):
SendInput(
1,
ctypes.byref(INPUT(
type=INPUT.MOUSE,
value=INPUT_union(
mouse=MOUSEINPUT(
dwFlags=button.value[0])))),
ctypes.sizeof(INPUT))
x, y = self.position
self._notify('on_click', x, y, button, True)
def _release(self, button):
SendInput(
1,
ctypes.byref(INPUT(
type=INPUT.MOUSE,
value=INPUT_union(
mouse=MOUSEINPUT(
dwFlags=button.value[1])))),
ctypes.sizeof(INPUT))
x, y = self.position
self._notify('on_click', x, y, button, False)
def _notify(self, action, *args):
"""Sends a notification to all currently running instances of
:class:`Listener`.
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 Listener.listeners():
try:
getattr(listener, action)(*args)
except Listener.StopException:
stopped.append(listener)
for listener in stopped:
listener.stop()
class Listener(_base.Listener):
#: The Windows hook ID for low level mouse events
WH_MOUSE_LL = 14
HC_ACTION = 0
WM_LBUTTONDOWN = 0x0201
WM_LBUTTONUP = 0x0202
WM_MOUSEMOVE = 0x0200
WM_MOUSEWHEEL = 0x020A
WM_MOUSEHWHEEL = 0x020E
WM_RBUTTONDOWN = 0x0204
WM_RBUTTONUP = 0x0205
WHEEL_DELTA = 120
#: A mapping from messages to button events
CLICK_BUTTONS = {
WM_LBUTTONDOWN: (Controller.Button.left, True),
WM_LBUTTONUP: (Controller.Button.left, False),
WM_RBUTTONDOWN: (Controller.Button.right, True),
WM_RBUTTONUP: (Controller.Button.right, False)}
#: A mapping from messages to scroll vectors
SCROLL_BUTTONS = {
WM_MOUSEWHEEL: (0, 1),
WM_MOUSEHWHEEL: (1, 0)}
#: The currently running listeners
__listeners = set()
#: The lock protecting access to the :attr:`_listeners`
__listener_lock = threading.Lock()
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._message_loop = MessageLoop()
def _run(self):
self.__add_listener(self)
try:
self._message_loop.start()
with SystemHook(self.WH_MOUSE_LL, self._handler):
# Just pump messages
for msg in self._message_loop:
if not self.running:
break
finally:
self.__remove_listener(self)
def _stop(self):
self._message_loop.stop()
@_base.Listener._emitter
def _handler(self, code, msg, lpdata):
"""The callback registered with *Windows* for mouse events.
This method will call the callbacks registered on initialisation.
"""
if code != self.HC_ACTION:
return
data = ctypes.cast(lpdata, self.LPMSLLHOOKSTRUCT).contents
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]
d = wintypes.SHORT(data.mouseData >> 16).value // self.WHEEL_DELTA
self.on_scroll(data.pt.x, data.pt.y, d * mx, d * my)
@classmethod
def __add_listener(self, listener):
"""Adds a listener to the set of running listeners.
:param Listener listener: The listener to add.
"""
with self.__listener_lock:
self.__listeners.add(listener)
@classmethod
def __remove_listener(self, listener):
"""Removes a listener from the set of running listeners.
:param Listener listener: The listener to remove.
"""
with self.__listener_lock:
self.__listeners.remove(listener)
@classmethod
def listeners(self):
"""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 self.__listeners:
return
with self.__listener_lock:
for listener in self.__listeners:
yield listener
PK ûYGz\L˜² ² pynput/mouse/_xorg.py# coding=utf-8
# pynput
# Copyright (C) 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see .
import enum
import Xlib.display
import Xlib.ext
import Xlib.ext.xtest
import Xlib.X
import Xlib.protocol
from pynput._util.xorg import *
from . import _base
# Create a display to verify that we have an X connection
display = Xlib.display.Display()
display.close()
del display
class Controller(_base.Controller):
class Button(enum.Enum):
"""The various buttons.
"""
left = 1
middle = 2
right = 3
scroll_up = 4
scroll_down = 5
scroll_left = 6
scroll_right = 7
def __init__(self):
self._display = Xlib.display.Display()
def _position_get(self):
with display_manager(self._display) as d:
data = d.screen().root.query_pointer()._data
return (data["root_x"], data["root_y"])
def _position_set(self, pos):
x, y = pos
with display_manager(self._display) as d:
Xlib.ext.xtest.fake_input(d, Xlib.X.MotionNotify, x=x, y=y)
def _scroll(self, dx, dy):
if dy:
self.click(
button=self.Button.scroll_up if dy > 0
else self.Button.scroll_down,
count=abs(dy))
if dx:
self.click(
button=self.Button.scroll_right if dx > 0
else self.Button.scroll_left,
count=abs(dx))
def _press(self, button):
with display_manager(self._display) as d:
Xlib.ext.xtest.fake_input(d, Xlib.X.ButtonPress, button.value)
def _release(self, button):
with display_manager(self._display) as d:
Xlib.ext.xtest.fake_input(d, Xlib.X.ButtonRelease, button.value)
class Listener(_base.Listener):
#: A mapping from button values to scroll directions
SCROLL_BUTTONS = {
Controller.Button.scroll_up.value: (0, 1),
Controller.Button.scroll_down.value: (0, -1),
Controller.Button.scroll_right.value: (1, 0),
Controller.Button.scroll_left.value: (-1, 0)}
def __init__(self, *args, **kwargs):
super(Listener, self).__init__(*args, **kwargs)
self._display_stop = Xlib.display.Display()
self._display_record = Xlib.display.Display()
with display_manager(self._display_record) as d:
self._context = d.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': (
Xlib.X.ButtonPressMask,
Xlib.X.ButtonReleaseMask),
'errors': (0, 0),
'client_started': False,
'client_died': False}])
def _run(self):
with display_manager(self._display_record) as d:
d.record_enable_context(
self._context, self._handler)
d.record_free_context(self._context)
def _stop(self):
self._display_stop.sync()
with display_manager(self._display_stop) as d:
d.record_disable_context(self._context)
@_base.Listener._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.
"""
# We use this instance for parsing the binary data
e = Xlib.protocol.rq.EventField(None)
data = events.data
while len(data):
event, data = e.parse_binary_value(
data, self._display_record.display, None, None)
x = event.root_x
y = 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(x, y, *scroll)
else:
self.on_click(x, y, Controller.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(x, y, Controller.Button(event.detail), False)
else:
self.on_move(x, y)
PK 8W\GO8f pynput/mouse/_base.py# coding=utf-8
# pynput
# Copyright (C) 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see .
import enum
import functools
import threading
class Controller(object):
"""A controller for sending virtual mouse events to the system.
"""
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.
"""
#: The left button
left = 1
#: The middle button
middle = 2
#: The right button
right = 3
@property
def position(self):
"""The current position of the mouse pointer.
This is the tuple ``(x, y)``.
"""
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.
"""
self._scroll(dx, dy)
def press(self, button):
"""Emits a button press event at the current position.
:param Controller.Button button: The button to press.
"""
self._press(button)
def release(self, button):
"""Emits a button release event at the current position.
:param Controller.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.
"""
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 a press and release events.
:param Controller.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, 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()
class Listener(threading.Thread):
"""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:
with_statements()
finally:
listener.stop()
: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:`Controller.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.
"""
class StopException(Exception):
"""If an event listener callback raises this exception, the current
listener is stopped.
Its first argument must be set to the :class:`Listener` to stop.
"""
pass
def __init__(self, on_move=None, on_click=None, on_scroll=None):
super(Listener, self).__init__()
def wrapper(f):
def inner(*args):
if f(*args) is False:
raise self.StopException(self)
return inner
self._running = False
self._thread = threading.current_thread()
self.on_move = wrapper(on_move or (lambda *a: None))
self.on_click = wrapper(on_click or (lambda *a: None))
self.on_scroll = wrapper(on_scroll or (lambda *a: None))
@property
def running(self):
"""Whether the listener is currently running.
"""
return self._running
def stop(self):
"""Stops listening for mouse events.
When this method returns, the listening thread will have stopped.
"""
if self._running:
self._running = False
self._stop()
if threading.current_thread() != self._thread:
self.join()
def __enter__(self):
self.start()
return self
def __exit__(self, type, value, traceback):
self.stop()
def run(self):
"""The thread runner method.
"""
self._running = True
self._thread = threading.current_thread()
self._run()
@classmethod
def _emitter(self, f):
"""A decorator to mark a method as the one emitting the callbacks.
This decorator will wrap the method and catch :class:`StopException`.
If this exception is caught, the listener will be stopped.
"""
@functools.wraps(f)
def inner(*args, **kwargs):
try:
f(*args, **kwargs)
except self.StopException as e:
e.args[0].stop()
return inner
def _run(self):
"""The implementation of the :meth:`start` method.
This is a platform dependent implementation.
"""
raise NotImplementedError()
def _stop(self):
"""The implementation of the :meth:`stop` method.
This is a platform dependent implementation.
"""
raise NotImplementedError()
PK }W\G<Úýè³ ³ $ pynput-0.2.dist-info/DESCRIPTION.rstpynput
======
This library allows you to control and monitor input devices.
Currently, only mouse input is supported.
Controlling the mouse
---------------------
Use ``pynput.mouse.Controller`` like this::
from pynput.mouse import Controller, Listener
d = Controller()
# Read pointer position
print('The current pointer position is {0}'.format(
d.position))
# Set pointer position
d.position = (10, 20)
print('Now we have moved it to {0}'.format(
d.position))
# Move pointer relative to current position
d.move(5, -5)
# Press and release
d.press(d.Button.left)
d.release(d.Button.left)
# Double click; this is different from pressing and releasing twice on Mac
# OSX
d.click(d.Button.left, 2)
# Scroll two steps down
d.scroll(0, 2)
Monitoring the mouse
--------------------
Use ``pynput.mouse.Listener`` like this::
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(dx, dy):
print('Scrolled {0}'.format(
(x, y)))
# Collect events until released
with Listener(
on_move=on_move,
on_click=on_click,
on_scroll=on_scroll) as l:
l.join()
A mouse listener is a ``threading.Thread``, and all callbacks will be invoked
from the thread.
Call ``pynput.mouse.Listener.stop`` from anywhere, or raise
``pynput.mouse.Listener.StopException`` or return ``False`` from a callback to
stop the listener.
Release Notes
=============
v0.2 - Initial Release
----------------------
* Support for controlling the mouse on *Linux*, *Mac OSX* and *Windows*.
* Support for monitoring the mouse on *Linux*, *Mac OSX* and *Windows*.
PK }W\G@Ö¡` " pynput-0.2.dist-info/metadata.json{"classifiers": ["Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows :: Windows NT/2000", "Operating System :: POSIX", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Monitoring"], "extensions": {"python.details": {"contacts": [{"email": "moses.palmer@gmail.com", "name": "Moses Palm\u00c3\u00a9r", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst"}, "project_urls": {"Home": "https://github.com/moses-palmer/pynput"}}}, "extras": [], "generator": "bdist_wheel (0.26.0)", "keywords": ["control", "mouse", "mouse", "input"], "license": "GPLv3", "metadata_version": "2.0", "name": "pynput", "run_requires": [{"requires": ["enum34"]}], "summary": "Monitor and control user input devices", "version": "0.2"}PK }W\G4J. . pynput-0.2.dist-info/pbr.json{"is_release": true, "git_version": "da3404e"}PK }W\G»Å¨é " pynput-0.2.dist-info/top_level.txtpynput
PK dOG“×2 pynput-0.2.dist-info/zip-safe
PK }W\GŒ''\ \ pynput-0.2.dist-info/WHEELWheel-Version: 1.0
Generator: bdist_wheel (0.26.0)
Root-Is-Purelib: true
Tag: py2-none-any
PK }W\GópÅ´$ $ pynput-0.2.dist-info/METADATAMetadata-Version: 2.0
Name: pynput
Version: 0.2
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: GPLv3
Keywords: control mouse,mouse input
Platform: UNKNOWN
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
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: enum34
pynput
======
This library allows you to control and monitor input devices.
Currently, only mouse input is supported.
Controlling the mouse
---------------------
Use ``pynput.mouse.Controller`` like this::
from pynput.mouse import Controller, Listener
d = Controller()
# Read pointer position
print('The current pointer position is {0}'.format(
d.position))
# Set pointer position
d.position = (10, 20)
print('Now we have moved it to {0}'.format(
d.position))
# Move pointer relative to current position
d.move(5, -5)
# Press and release
d.press(d.Button.left)
d.release(d.Button.left)
# Double click; this is different from pressing and releasing twice on Mac
# OSX
d.click(d.Button.left, 2)
# Scroll two steps down
d.scroll(0, 2)
Monitoring the mouse
--------------------
Use ``pynput.mouse.Listener`` like this::
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(dx, dy):
print('Scrolled {0}'.format(
(x, y)))
# Collect events until released
with Listener(
on_move=on_move,
on_click=on_click,
on_scroll=on_scroll) as l:
l.join()
A mouse listener is a ``threading.Thread``, and all callbacks will be invoked
from the thread.
Call ``pynput.mouse.Listener.stop`` from anywhere, or raise
``pynput.mouse.Listener.StopException`` or return ``False`` from a callback to
stop the listener.
Release Notes
=============
v0.2 - Initial Release
----------------------
* Support for controlling the mouse on *Linux*, *Mac OSX* and *Windows*.
* Support for monitoring the mouse on *Linux*, *Mac OSX* and *Windows*.
PK }W\GŸ• • pynput-0.2.dist-info/RECORDpynput/__init__.py,sha256=S-QqApr9WyaH_v4ogz4lXYmcR6KU8NRq9L4EPCbY-_k,714
pynput/_info.py,sha256=Vc0pCY8TWh_0sjZpyFLO8m7edrRXxIY9QptCMSXF3aE,67
pynput/_util/__init__.py,sha256=mRlq3NQSSG2IaeLmK0UE1ILK2afNIkrfwfFrK_DTvuc,693
pynput/_util/win32.py,sha256=Q-SgfathmnGeIn34_yoeXL-RCE9MYfl-RSfaDFfN_AE,6498
pynput/_util/xorg.py,sha256=xLj5Hef35iewr4dbylhNyaPHHyZcViUwIzb4Y4SdrKw,1608
pynput/mouse/__init__.py,sha256=mS5dEaFe9bPSOoT84DqKsQfgaL6lnn9wFegJSY9f-_Y,1374
pynput/mouse/_base.py,sha256=WEeW84bPveKRq1uQWNRzhEHGnEcgwhNwj3IiazdSa00,8200
pynput/mouse/_darwin.py,sha256=VlRAgOBeujhCk-XFNs5Xo6Q5na1SGYrp2-YzmocnkNU,7405
pynput/mouse/_win32.py,sha256=E3iyIhxv7TpyUJ-vaW887iLlIXuUgLddc5xBPn8cPDY,7539
pynput/mouse/_xorg.py,sha256=5zhhSrlaMithxKlubNCAuMeBs0pw2575zDMawJv0Q0s,5298
pynput-0.2.dist-info/DESCRIPTION.rst,sha256=E96o6d-kMn4pIQ6BqaYO_m5hfGLmsxSw6yB-v-Kt2iY,1971
pynput-0.2.dist-info/METADATA,sha256=q9nyAOr6Hj2Kbu-4VbIESL347OnWNRjFcMK-PA_CnM0,2852
pynput-0.2.dist-info/RECORD,,
pynput-0.2.dist-info/WHEEL,sha256=JTb7YztR8fkPg6aSjc571Q4eiVHCwmUDlX8PhuuqIIE,92
pynput-0.2.dist-info/metadata.json,sha256=OR-CX2O_m_Ne7d1XQouAvSuZ1yRBwpJeo2LMbK_xGvw,1045
pynput-0.2.dist-info/pbr.json,sha256=GMjThxy6oRiz6zos6ifjIFIsOv-d9A7S5QkCNEBwQXQ,46
pynput-0.2.dist-info/top_level.txt,sha256=DpJjYf-VkYaa_COk_yUczD0pHqsLndB9SjmwcQGkXJQ,7
pynput-0.2.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
PK ûYG^ÈA)Ê Ê pynput/__init__.pyPK oW\G#1»vC C ú pynput/_info.pyPK ûYGæYŒëµ µ j pynput/_util/__init__.pyPK ûYGÙæ÷IH H U pynput/_util/xorg.pyPK ûYG€³†¸b b Ï pynput/_util/win32.pyPK 8W\GVû]^ ^ d&