PKË›–G^È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œ–G[ywCCpynput/_info.py# coding: utf8 __author__ = u'Moses Palmér' __version__ = (0, 3) 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ð›–G,ÚÜJÖÖ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 . import Xlib.display # Create a display to verify that we have an X connection display = Xlib.display.Display() display.close() del display 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€³†¸bbpynput/_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ð›–G×Î0Pžž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 Button, Controller, Listener else: Button = None Controller = None Listener = None if sys.platform == 'darwin': if Controller is None and Listener is None: from ._darwin import Button, Controller, Listener elif sys.platform == 'win32': if Controller is None and Listener is None: from ._win32 import Button, Controller, Listener else: if Controller is None and Listener is None: try: from ._xorg import Button, Controller, Listener except: pass if not Button or not Controller or not Listener: raise ImportError('this platform is not supported') PKð›–GŠÔ _™™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 from AppKit import NSEvent 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. """ left = _button_value('kCGEventLeft', 0) middle = _button_value('kCGEventOther', 2) right = _button_value('kCGEventRight', 1) class Controller(_base.Controller): 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 = ( 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 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ð›–G,Ý™^^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 Button(enum.Enum): """The various buttons. """ left = (MOUSEINPUT.LEFTUP, MOUSEINPUT.LEFTDOWN) middle = (MOUSEINPUT.MIDDLEUP, MOUSEINPUT.MIDDLEDOWN) right = (MOUSEINPUT.RIGHTUP, MOUSEINPUT.RIGHTDOWN) class Controller(_base.Controller): __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: x, y = self._position_get() self._notify('on_scroll', x, y, 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: (Button.left, True), WM_LBUTTONUP: (Button.left, 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)} #: 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ð›–G½rÆŒ°°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 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 class Controller(_base.Controller): def __init__(self): 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 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=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 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 = { Button.scroll_up.value: (0, 1), Button.scroll_down.value: (0, -1), Button.scroll_right.value: (1, 0), 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 __del__(self): if hasattr(self, '_display_stop'): self._display_stop.close() if hasattr(self, '_display_record'): self._display_record.close() 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, 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, Button(event.detail), False) else: self.on_move(x, y) PKð›–Go2Ь­­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 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 class Controller(object): """A controller for sending virtual mouse events to the system. """ @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 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. """ 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 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:`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ƒœ–GÖ91“==$pynput-0.3.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 Button, 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(Button.left) d.release(Button.left) # Double click; this is different from pressing and releasing twice on Mac # OSX d.click(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.3 - Cleanup ------------------------------------------------------------ * Moved ``pynput.mouse.Controller.Button`` to top-level. 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ƒœ–Gw¼ca"pynput-0.3.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.3"}PKƒœ–Gã1ïÐ..pynput-0.3.dist-info/pbr.json{"is_release": true, "git_version": "a9e2b60"}PKƒœ–G»Å¨é"pynput-0.3.dist-info/top_level.txtpynput PKdOG“×2pynput-0.3.dist-info/zip-safe PKƒœ–GŒ''\\pynput-0.3.dist-info/WHEELWheel-Version: 1.0 Generator: bdist_wheel (0.26.0) Root-Is-Purelib: true Tag: py2-none-any PKƒœ–G^0¶j® ® pynput-0.3.dist-info/METADATAMetadata-Version: 2.0 Name: pynput Version: 0.3 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 Button, 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(Button.left) d.release(Button.left) # Double click; this is different from pressing and releasing twice on Mac # OSX d.click(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.3 - Cleanup ------------------------------------------------------------ * Moved ``pynput.mouse.Controller.Button`` to top-level. 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ƒœ–GÃèb0••pynput-0.3.dist-info/RECORDpynput/__init__.py,sha256=S-QqApr9WyaH_v4ogz4lXYmcR6KU8NRq9L4EPCbY-_k,714 pynput/_info.py,sha256=SBFpzmi2a-CZHoDdUKWj8eu3taSX4T1FTnvc2WxDtQI,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=WxhNx0wsNpDsthfg908tliZlNmZAXcgjDA_NC0CuPjs,1750 pynput/mouse/__init__.py,sha256=DdehXOCv8aXmSpv9SCEJe9F5hNh1V6UbCNy7XzNB5l8,1438 pynput/mouse/_base.py,sha256=kzc8HZ9oZmby-SShDbRg1pju_Cn3oV529mCdbRLhqOs,8109 pynput/mouse/_darwin.py,sha256=BfSpUxJlBNtE47YIhsKtWTJtB4EAfX-Y4SSJ_gmUDcg,7321 pynput/mouse/_win32.py,sha256=zbnC-ziXLAtB3WSA593G09eWXJnN21qGlwzWm3MNHls,7518 pynput/mouse/_xorg.py,sha256=2u2BSelSFwTKATBJcM28HDCLyIJMhL5nHd1hGAsMuJc,5296 pynput-0.3.dist-info/DESCRIPTION.rst,sha256=izGWnnpR5eCzypapVzs4Gq3GwgRBa7vXrp6yRx-oPZQ,2109 pynput-0.3.dist-info/METADATA,sha256=rasXshVeuQPcUkq8KkH6-T83cdINqyWtGGHsElcKe-Y,2990 pynput-0.3.dist-info/RECORD,, pynput-0.3.dist-info/WHEEL,sha256=JTb7YztR8fkPg6aSjc571Q4eiVHCwmUDlX8PhuuqIIE,92 pynput-0.3.dist-info/metadata.json,sha256=q_pGx_NY49rzVTHaBPyqgTut8v4TMcpH7tSxThPVBVk,1045 pynput-0.3.dist-info/pbr.json,sha256=HJ6Pron0SvoCzm4c6G-NdbgqWKd-0u6aDDBfCMpLE18,46 pynput-0.3.dist-info/top_level.txt,sha256=DpJjYf-VkYaa_COk_yUczD0pHqsLndB9SjmwcQGkXJQ,7 pynput-0.3.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 PKË›–G^ÈA)ÊÊpynput/__init__.pyPKœ–G[ywCCúpynput/_info.pyPKû­YGæYŒëµµjpynput/_util/__init__.pyPKð›–G,ÚÜJÖÖUpynput/_util/xorg.pyPKû­YG€³†¸bb] pynput/_util/win32.pyPKð›–G×Î0Pžžò&pynput/mouse/__init__.pyPKð›–GŠÔ _™™Æ,pynput/mouse/_darwin.pyPKð›–G,Ý™^^”Ipynput/mouse/_win32.pyPKð›–G½rÆŒ°°&gpynput/mouse/_xorg.pyPKð›–Go2Ь­­ |pynput/mouse/_base.pyPKƒœ–GÖ91“==$é›pynput-0.3.dist-info/DESCRIPTION.rstPKƒœ–Gw¼ca"h¤pynput-0.3.dist-info/metadata.jsonPKƒœ–Gã1ïÐ..½¨pynput-0.3.dist-info/pbr.jsonPKƒœ–G»Å¨é"&©pynput-0.3.dist-info/top_level.txtPKdOG“×2m©pynput-0.3.dist-info/zip-safePKƒœ–GŒ''\\©©pynput-0.3.dist-info/WHEELPKƒœ–G^0¶j® ® =ªpynput-0.3.dist-info/METADATAPKƒœ–GÃèb0••&¶pynput-0.3.dist-info/RECORDPKô»