├── .gitignore ├── LICENSE.txt ├── README.txt ├── examples ├── mouse.py └── mouselogger ├── pymouse ├── __init__.py ├── base.py ├── java_.py ├── mac.py ├── unix.py └── windows.py ├── setup.py └── tests ├── basic.py └── test_unix.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.pyc 3 | *.swp 4 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.txt: -------------------------------------------------------------------------------- 1 | PyMouse has been merged into PyUserInput at https://github.com/SavinaRoja/PyUserInput 2 | -------------------------------------------------------------------------------- /examples/mouse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import logging 4 | import daemon 5 | from socket import gethostname; 6 | from pymouse import PyMouse 7 | import random, time 8 | from signal import signal, SIGINT 9 | 10 | with daemon.DaemonContext(): 11 | 12 | def stop(signum, frame): 13 | cleanup_stop_thread(); 14 | sys.exit() 15 | signal(SIGINT, stop) 16 | 17 | try: 18 | from pymouse import PyMouseEvent 19 | 20 | class event(PyMouseEvent): 21 | def __init__(self): 22 | super(event, self).__init__() 23 | FORMAT = '%(asctime)-15s ' + gethostname() + ' touchlogger %(levelname)s %(message)s' 24 | logging.basicConfig(filename='/var/log/mouse.log', level=logging.DEBUG, format=FORMAT) 25 | 26 | def move(self, x, y): 27 | pass 28 | 29 | def click(self, x, y, button, press): 30 | if press: 31 | logging.info('{ "event": "click", "type": "press", "x": "' + str(x) + '", "y": "' + str(y) + '"}') 32 | else: 33 | logging.info('{ "event": "click", "type": "release", "x": "' + str(x) + '", "y": "' + str(y) + '"}') 34 | 35 | e = event() 36 | e.capture = False 37 | e.daemon = False 38 | e.start() 39 | 40 | except ImportError: 41 | logging.info('{ "event": "exception", "type": "ImportError", "value": "Mouse events unsupported"}') 42 | sys.exit() 43 | 44 | m = PyMouse() 45 | try: 46 | size = m.screen_size() 47 | logging.info('{ "event": "start", "type": "size", "value": "' + str(size) + '"}') 48 | except: 49 | logging.info('{ "event": "exception", "type": "size", "value": "undetermined problem"}') 50 | sys.exit() 51 | 52 | try: 53 | e.join() 54 | except KeyboardInterrupt: 55 | e.stop() 56 | sys.exit() 57 | 58 | -------------------------------------------------------------------------------- /examples/mouselogger: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | ### BEGIN INIT INFO 3 | # Provides: mouselogger 4 | # Default-Start: 2 3 4 5 5 | # Default-Stop: 0 1 6 6 | # Short-Description: Mouse Logger daemon 7 | # Description: This file should be used to construct scripts to be 8 | # placed in /etc/init.d. 9 | ### END INIT INFO 10 | 11 | # Author: David Suarez 12 | # 13 | 14 | # Do NOT "set -e" 15 | 16 | # PATH should only include /usr/* if it runs after the mountnfs.sh script 17 | PATH=/sbin:/usr/sbin:/bin:/usr/bin:/opt/wantudu/bin 18 | DESC="Mouse logger for X" 19 | NAME=mouselogger 20 | DAEMON=/opt/wantudu/bin/mouse.py 21 | DAEMON_ARGS="" 22 | PIDFILE=/var/run/$NAME.pid 23 | SCRIPTNAME=/etc/init.d/$NAME 24 | 25 | # Exit if the package is not installed 26 | [ -x "$DAEMON" ] || exit 0 27 | 28 | # Read configuration variable file if it is present 29 | [ -r /etc/default/$NAME ] && . /etc/default/$NAME 30 | 31 | # Load the VERBOSE setting and other rcS variables 32 | . /lib/init/vars.sh 33 | 34 | # Define LSB log_* functions. 35 | # Depend on lsb-base (>= 3.0-6) to ensure that this file is present. 36 | . /lib/lsb/init-functions 37 | 38 | # 39 | # Function that starts the daemon/service 40 | # 41 | do_start() 42 | { 43 | # Return 44 | # 0 if daemon has been started 45 | # 1 if daemon was already running 46 | # 2 if daemon could not be started 47 | start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \ 48 | || return 1 49 | start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \ 50 | $DAEMON_ARGS \ 51 | || return 2 52 | # Add code here, if necessary, that waits for the process to be ready 53 | # to handle requests from services started subsequently which depend 54 | # on this one. As a last resort, sleep for some time. 55 | } 56 | 57 | # 58 | # Function that stops the daemon/service 59 | # 60 | do_stop() 61 | { 62 | # Return 63 | # 0 if daemon has been stopped 64 | # 1 if daemon was already stopped 65 | # 2 if daemon could not be stopped 66 | # other if a failure occurred 67 | start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME 68 | RETVAL="$?" 69 | [ "$RETVAL" = 2 ] && return 2 70 | # Wait for children to finish too if this is a daemon that forks 71 | # and if the daemon is only ever run from this initscript. 72 | # If the above conditions are not satisfied then add some other code 73 | # that waits for the process to drop all resources that could be 74 | # needed by services started subsequently. A last resort is to 75 | # sleep for some time. 76 | start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON 77 | [ "$?" = 2 ] && return 2 78 | # Many daemons don't delete their pidfiles when they exit. 79 | rm -f $PIDFILE 80 | return "$RETVAL" 81 | } 82 | 83 | # 84 | # Function that sends a SIGHUP to the daemon/service 85 | # 86 | do_reload() { 87 | # 88 | # If the daemon can reload its configuration without 89 | # restarting (for example, when it is sent a SIGHUP), 90 | # then implement that here. 91 | # 92 | start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME 93 | return 0 94 | } 95 | 96 | case "$1" in 97 | start) 98 | [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME" 99 | do_start 100 | case "$?" in 101 | 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 102 | 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; 103 | esac 104 | ;; 105 | stop) 106 | [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME" 107 | do_stop 108 | case "$?" in 109 | 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 110 | 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; 111 | esac 112 | ;; 113 | status) 114 | status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $? 115 | ;; 116 | #reload|force-reload) 117 | # 118 | # If do_reload() is not implemented then leave this commented out 119 | # and leave 'force-reload' as an alias for 'restart'. 120 | # 121 | #log_daemon_msg "Reloading $DESC" "$NAME" 122 | #do_reload 123 | #log_end_msg $? 124 | #;; 125 | restart|force-reload) 126 | # 127 | # If the "reload" option is implemented then remove the 128 | # 'force-reload' alias 129 | # 130 | log_daemon_msg "Restarting $DESC" "$NAME" 131 | do_stop 132 | case "$?" in 133 | 0|1) 134 | do_start 135 | case "$?" in 136 | 0) log_end_msg 0 ;; 137 | 1) log_end_msg 1 ;; # Old process is still running 138 | *) log_end_msg 1 ;; # Failed to start 139 | esac 140 | ;; 141 | *) 142 | # Failed to stop 143 | log_end_msg 1 144 | ;; 145 | esac 146 | ;; 147 | *) 148 | #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2 149 | echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2 150 | exit 3 151 | ;; 152 | esac 153 | 154 | : 155 | -------------------------------------------------------------------------------- /pymouse/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: iso-8859-1 -*- 2 | 3 | # Copyright 2010 Pepijn de Vos 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """The goal of PyMouse is to have a cross-platform way to control the mouse. 18 | PyMouse should work on Windows, Mac and any Unix that has xlib. 19 | 20 | See http://github.com/pepijndevos/PyMouse for more information. 21 | """ 22 | 23 | import sys 24 | 25 | if sys.platform.startswith('java'): 26 | from java_ import PyMouse 27 | 28 | elif sys.platform == 'darwin': 29 | from mac import PyMouse, PyMouseEvent 30 | 31 | elif sys.platform == 'win32': 32 | from windows import PyMouse, PyMouseEvent 33 | 34 | else: 35 | from unix import PyMouse, PyMouseEvent 36 | 37 | -------------------------------------------------------------------------------- /pymouse/base.py: -------------------------------------------------------------------------------- 1 | # -*- coding: iso-8859-1 -*- 2 | 3 | # Copyright 2010 Pepijn de Vos 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """The goal of PyMouse is to have a cross-platform way to control the mouse. 18 | PyMouse should work on Windows, Mac and any Unix that has xlib. 19 | 20 | See http://github.com/pepijndevos/PyMouse for more information. 21 | """ 22 | 23 | from threading import Thread 24 | 25 | class PyMouseMeta(object): 26 | 27 | def press(self, x, y, button = 1): 28 | """Press the mouse on a givven x, y and button. 29 | Button is defined as 1 = left, 2 = right, 3 = middle.""" 30 | 31 | raise NotImplementedError 32 | 33 | def release(self, x, y, button = 1): 34 | """Release the mouse on a givven x, y and button. 35 | Button is defined as 1 = left, 2 = right, 3 = middle.""" 36 | 37 | raise NotImplementedError 38 | 39 | def click(self, x, y, button = 1, n = 1): 40 | """Click a mouse button n times on a given x, y. 41 | Button is defined as 1 = left, 2 = right, 3 = middle. 42 | """ 43 | 44 | for i in range(n): 45 | self.press(x, y, button) 46 | self.release(x, y, button) 47 | 48 | def move(self, x, y): 49 | """Move the mouse to a givven x and y""" 50 | 51 | raise NotImplementedError 52 | 53 | def position(self): 54 | """Get the current mouse position in pixels. 55 | Returns a tuple of 2 integers""" 56 | 57 | raise NotImplementedError 58 | 59 | def screen_size(self): 60 | """Get the current screen size in pixels. 61 | Returns a tuple of 2 integers""" 62 | 63 | raise NotImplementedError 64 | 65 | class PyMouseEventMeta(Thread): 66 | def __init__(self, capture=False, captureMove=False): 67 | Thread.__init__(self) 68 | self.daemon = True 69 | self.capture = capture 70 | self.captureMove = captureMove 71 | self.state = True 72 | 73 | def stop(self): 74 | self.state = False 75 | 76 | def click(self, x, y, button, press): 77 | """Subclass this method with your click event handler""" 78 | 79 | pass 80 | 81 | def move(self, x, y): 82 | """Subclass this method with your move event handler""" 83 | 84 | pass 85 | -------------------------------------------------------------------------------- /pymouse/java_.py: -------------------------------------------------------------------------------- 1 | # -*- coding: iso-8859-1 -*- 2 | 3 | # Copyright 2010 Pepijn de Vos 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from java.awt import Robot, Toolkit 18 | from java.awt.event import InputEvent 19 | from java.awt.MouseInfo import getPointerInfo 20 | from base import PyMouseMeta 21 | 22 | r = Robot() 23 | 24 | class PyMouse(PyMouseMeta): 25 | def press(self, x, y, button = 1): 26 | button_list = [None, InputEvent.BUTTON1_MASK, InputEvent.BUTTON3_MASK, InputEvent.BUTTON2_MASK] 27 | self.move(x, y) 28 | r.mousePress(button_list[button]) 29 | 30 | def release(self, x, y, button = 1): 31 | button_list = [None, InputEvent.BUTTON1_MASK, InputEvent.BUTTON3_MASK, InputEvent.BUTTON2_MASK] 32 | self.move(x, y) 33 | r.mouseRelease(button_list[button]) 34 | 35 | def move(self, x, y): 36 | r.mouseMove(x, y) 37 | 38 | def position(self): 39 | loc = getPointerInfo().getLocation() 40 | return loc.getX, loc.getY 41 | 42 | def screen_size(self): 43 | dim = Toolkit.getDefaultToolkit().getScreenSize() 44 | return dim.getWidth(), dim.getHeight() 45 | -------------------------------------------------------------------------------- /pymouse/mac.py: -------------------------------------------------------------------------------- 1 | # -*- coding: iso-8859-1 -*- 2 | 3 | # Copyright 2010 Pepijn de Vos 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from Quartz import * 18 | from AppKit import NSEvent 19 | from base import PyMouseMeta, PyMouseEventMeta 20 | 21 | pressID = [None, kCGEventLeftMouseDown, kCGEventRightMouseDown, kCGEventOtherMouseDown] 22 | releaseID = [None, kCGEventLeftMouseUp, kCGEventRightMouseUp, kCGEventOtherMouseUp] 23 | 24 | class PyMouse(PyMouseMeta): 25 | def press(self, x, y, button = 1): 26 | event = CGEventCreateMouseEvent(None, pressID[button], (x, y), button - 1) 27 | CGEventPost(kCGHIDEventTap, event) 28 | 29 | def release(self, x, y, button = 1): 30 | event = CGEventCreateMouseEvent(None, releaseID[button], (x, y), button - 1) 31 | CGEventPost(kCGHIDEventTap, event) 32 | 33 | def move(self, x, y): 34 | move = CGEventCreateMouseEvent(None, kCGEventMouseMoved, (x, y), 0) 35 | CGEventPost(kCGHIDEventTap, move) 36 | 37 | 38 | def position(self): 39 | loc = NSEvent.mouseLocation() 40 | return loc.x, CGDisplayPixelsHigh(0) - loc.y 41 | 42 | def screen_size(self): 43 | return CGDisplayPixelsWide(0), CGDisplayPixelsHigh(0) 44 | 45 | class PyMouseEvent(PyMouseEventMeta): 46 | def run(self): 47 | tap = CGEventTapCreate( 48 | kCGSessionEventTap, 49 | kCGHeadInsertEventTap, 50 | kCGEventTapOptionDefault, 51 | CGEventMaskBit(kCGEventMouseMoved) | 52 | CGEventMaskBit(kCGEventLeftMouseDown) | 53 | CGEventMaskBit(kCGEventLeftMouseUp) | 54 | CGEventMaskBit(kCGEventRightMouseDown) | 55 | CGEventMaskBit(kCGEventRightMouseUp) | 56 | CGEventMaskBit(kCGEventOtherMouseDown) | 57 | CGEventMaskBit(kCGEventOtherMouseUp), 58 | self.handler, 59 | None) 60 | 61 | loopsource = CFMachPortCreateRunLoopSource(None, tap, 0) 62 | loop = CFRunLoopGetCurrent() 63 | CFRunLoopAddSource(loop, loopsource, kCFRunLoopDefaultMode) 64 | CGEventTapEnable(tap, True) 65 | 66 | while self.state: 67 | CFRunLoopRunInMode(kCFRunLoopDefaultMode, 5, False) 68 | 69 | def handler(self, proxy, type, event, refcon): 70 | (x, y) = CGEventGetLocation(event) 71 | if type in pressID: 72 | self.click(x, y, pressID.index(type), True) 73 | elif type in releaseID: 74 | self.click(x, y, releaseID.index(type), False) 75 | else: 76 | self.move(x, y) 77 | 78 | if self.capture: 79 | CGEventSetType(event, kCGEventNull) 80 | 81 | return event 82 | -------------------------------------------------------------------------------- /pymouse/unix.py: -------------------------------------------------------------------------------- 1 | # -*- coding: iso-8859-1 -*- 2 | 3 | # Copyright 2010 Pepijn de Vos 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from Xlib.display import Display 18 | from Xlib import X 19 | from Xlib.ext.xtest import fake_input 20 | from Xlib.ext import record 21 | from Xlib.protocol import rq 22 | 23 | from base import PyMouseMeta, PyMouseEventMeta 24 | 25 | 26 | class PyMouse(PyMouseMeta): 27 | def __init__(self, display=None): 28 | PyMouseMeta.__init__(self) 29 | self.display = Display(display) 30 | self.display2 = Display(display) 31 | 32 | def press(self, x, y, button = 1): 33 | self.move(x, y) 34 | fake_input(self.display, X.ButtonPress, [None, 1, 3, 2, 4, 5][button]) 35 | self.display.sync() 36 | 37 | def release(self, x, y, button = 1): 38 | self.move(x, y) 39 | fake_input(self.display, X.ButtonRelease, [None, 1, 3, 2, 4, 5][button]) 40 | self.display.sync() 41 | 42 | def move(self, x, y): 43 | fake_input(self.display, X.MotionNotify, x=x, y=y) 44 | self.display.sync() 45 | 46 | def position(self): 47 | coord = self.display.screen().root.query_pointer()._data 48 | return coord["root_x"], coord["root_y"] 49 | 50 | def screen_size(self): 51 | width = self.display.screen().width_in_pixels 52 | height = self.display.screen().height_in_pixels 53 | return width, height 54 | 55 | class PyMouseEvent(PyMouseEventMeta): 56 | def __init__(self, display=None): 57 | PyMouseEventMeta.__init__(self) 58 | self.display = Display(display) 59 | self.display2 = Display(display) 60 | self.ctx = self.display2.record_create_context( 61 | 0, 62 | [record.AllClients], 63 | [{ 64 | 'core_requests': (0, 0), 65 | 'core_replies': (0, 0), 66 | 'ext_requests': (0, 0, 0, 0), 67 | 'ext_replies': (0, 0, 0, 0), 68 | 'delivered_events': (0, 0), 69 | 'device_events': (X.ButtonPressMask, X.ButtonReleaseMask), 70 | 'errors': (0, 0), 71 | 'client_started': False, 72 | 'client_died': False, 73 | }]) 74 | 75 | def run(self): 76 | if self.capture: 77 | self.display2.screen().root.grab_pointer(True, X.ButtonPressMask | X.ButtonReleaseMask, X.GrabModeAsync, X.GrabModeAsync, 0, 0, X.CurrentTime) 78 | 79 | self.display2.record_enable_context(self.ctx, self.handler) 80 | self.display2.record_free_context(self.ctx) 81 | 82 | def stop(self): 83 | self.display.record_disable_context(self.ctx) 84 | self.display.ungrab_pointer(X.CurrentTime) 85 | self.display.flush() 86 | self.display2.record_disable_context(self.ctx) 87 | self.display2.ungrab_pointer(X.CurrentTime) 88 | self.display2.flush() 89 | 90 | def handler(self, reply): 91 | data = reply.data 92 | while len(data): 93 | event, data = rq.EventField(None).parse_binary_value(data, self.display.display, None, None) 94 | 95 | if event.type == X.ButtonPress: 96 | self.click(event.root_x, event.root_y, (None, 1, 3, 2, 3, 3, 3)[event.detail], True) 97 | elif event.type == X.ButtonRelease: 98 | self.click(event.root_x, event.root_y, (None, 1, 3, 2, 3, 3, 3)[event.detail], False) 99 | else: 100 | self.move(event.root_x, event.root_y) 101 | 102 | 103 | -------------------------------------------------------------------------------- /pymouse/windows.py: -------------------------------------------------------------------------------- 1 | # -*- coding: iso-8859-1 -*- 2 | 3 | # Copyright 2010 Pepijn de Vos 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from ctypes import * 18 | import win32api,win32con 19 | from base import PyMouseMeta, PyMouseEventMeta 20 | import pythoncom, pyHook 21 | from time import sleep 22 | 23 | class POINT(Structure): 24 | _fields_ = [("x", c_ulong), 25 | ("y", c_ulong)] 26 | 27 | class PyMouse(PyMouseMeta): 28 | """MOUSEEVENTF_(button and action) constants 29 | are defined at win32con, buttonAction is that value""" 30 | def press(self, x, y, button = 1): 31 | buttonAction = 2**((2*button)-1) 32 | self.move(x,y) 33 | win32api.mouse_event(buttonAction, x, y) 34 | 35 | def release(self, x, y, button = 1): 36 | buttonAction = 2**((2*button)) 37 | self.move(x,y) 38 | win32api.mouse_event(buttonAction, x, y) 39 | 40 | def move(self, x, y): 41 | windll.user32.SetCursorPos(x, y) 42 | 43 | def position(self): 44 | pt = POINT() 45 | windll.user32.GetCursorPos(byref(pt)) 46 | return pt.x, pt.y 47 | 48 | def screen_size(self): 49 | width = windll.user32.GetSystemMetrics(0) 50 | height = windll.user32.GetSystemMetrics(1) 51 | return width, height 52 | 53 | class PyMouseEvent(PyMouseEventMeta): 54 | def __init__(self): 55 | PyMouseEventMeta.__init__(self) 56 | self.hm = pyHook.HookManager() 57 | 58 | def run(self): 59 | self.hm.MouseAllButtons = self._click 60 | self.hm.MouseMove = self._move 61 | self.hm.HookMouse() 62 | while self.state: 63 | sleep(0.01) 64 | pythoncom.PumpWaitingMessages() 65 | 66 | def stop(self): 67 | self.hm.UnhookMouse() 68 | self.state = False 69 | 70 | def _click(self, event): 71 | x,y = event.Position 72 | 73 | if event.Message == pyHook.HookConstants.WM_LBUTTONDOWN: 74 | self.click(x, y, 1, True) 75 | elif event.Message == pyHook.HookConstants.WM_LBUTTONUP: 76 | self.click(x, y, 1, False) 77 | elif event.Message == pyHook.HookConstants.WM_RBUTTONDOWN: 78 | self.click(x, y, 2, True) 79 | elif event.Message == pyHook.HookConstants.WM_RBUTTONUP: 80 | self.click(x, y, 2, False) 81 | elif event.Message == pyHook.HookConstants.WM_MBUTTONDOWN: 82 | self.click(x, y, 3, True) 83 | elif event.Message == pyHook.HookConstants.WM_MBUTTONUP: 84 | self.click(x, y, 3, False) 85 | return not self.capture 86 | 87 | def _move(self, event): 88 | x,y = event.Position 89 | self.move(x, y) 90 | return not self.captureMove 91 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: iso-8859-1 -*- 2 | 3 | # Copyright 2010 Pepijn de Vos 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from distutils.core import setup 18 | 19 | setup(name='PyMouse', 20 | version='1.0', 21 | description='Cross-platform mouse control', 22 | author='Pepijn de Vos', 23 | author_email='pepijndevos@gmail.com', 24 | url='http://github.com/pepijndevos/PyMouse', 25 | packages = ["pymouse"], 26 | classifiers = [ 27 | "Programming Language :: Python", 28 | "Development Status :: 4 - Beta", 29 | "Intended Audience :: Developers", 30 | "License :: OSI Approved :: Apache Software License", 31 | "Operating System :: MacOS :: MacOS X", 32 | "Operating System :: Microsoft :: Windows", 33 | "Operating System :: Unix", 34 | "Topic :: Software Development :: Libraries :: Python Modules" 35 | ] 36 | ) 37 | -------------------------------------------------------------------------------- /tests/basic.py: -------------------------------------------------------------------------------- 1 | # -*- coding: iso-8859-1 -*- 2 | 3 | # Copyright 2010 Pepijn de Vos 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from pymouse import PyMouse 18 | import random, time 19 | try: 20 | from pymouse import PyMouseEvent 21 | 22 | class event(PyMouseEvent): 23 | def move(self, x, y): 24 | print "Mouse moved to", x, y 25 | 26 | def click(self, x, y, button, press): 27 | if press: 28 | print "Mouse pressed at", x, y, "with button", button 29 | else: 30 | print "Mouse released at", x, y, "with button", button 31 | 32 | e = event() 33 | #e.capture = True 34 | e.start() 35 | 36 | except ImportError: 37 | print "Mouse events are not yet supported on your platform" 38 | 39 | m = PyMouse() 40 | try: 41 | size = m.screen_size() 42 | print "size: %s" % (str(size)) 43 | 44 | pos = (random.randint(0, size[0]), random.randint(0, size[1])) 45 | except: 46 | pos = (random.randint(0, 250), random.randint(0, 250)) 47 | 48 | print "Position: %s" % (str(pos)) 49 | 50 | m.move(pos[0], pos[1]) 51 | 52 | time.sleep(2) 53 | 54 | m.click(pos[0], pos[1], 1) 55 | 56 | time.sleep(2) 57 | 58 | m.click(pos[0], pos[1], 2) 59 | 60 | time.sleep(2) 61 | 62 | m.click(pos[0], pos[1], 3) 63 | 64 | try: 65 | e.stop() 66 | except: 67 | pass 68 | -------------------------------------------------------------------------------- /tests/test_unix.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Tested on linux. 3 | 4 | install: Xvfb, Xephyr, PyVirtualDisplay, nose 5 | 6 | on Ubuntu: 7 | 8 | sudo apt-get install python-nose 9 | sudo apt-get install xvfb 10 | sudo apt-get install xserver-xephyr 11 | sudo apt-get install python-setuptools 12 | sudo easy_install PyVirtualDisplay 13 | 14 | to start: 15 | 16 | nosetests -v 17 | ''' 18 | 19 | from nose.tools import eq_ 20 | from pymouse import PyMouse, PyMouseEvent 21 | from pyvirtualdisplay import Display 22 | from unittest import TestCase 23 | import time 24 | 25 | # 0 -> Xvfb 26 | # 1 -> Xephyr 27 | VISIBLE = 0 28 | 29 | screen_sizes = [ 30 | (10, 20), 31 | (100, 200), 32 | (765, 666), 33 | ] 34 | positions = [ 35 | (0, 5), 36 | (0, 0), 37 | (10, 20), 38 | (-10, -20), 39 | (5, 0), 40 | (2222, 2222), 41 | (9, 19), 42 | ] 43 | 44 | 45 | class Event(PyMouseEvent): 46 | def move(self, x, y): 47 | print "Mouse moved to", x, y 48 | self.pos = (x, y) 49 | 50 | def click(self, x, y, button, press): 51 | if press: 52 | print "Mouse pressed at", x, y, "with button", button 53 | else: 54 | print "Mouse released at", x, y, "with button", button 55 | 56 | def expect_pos(pos, size): 57 | def expect(x, m): 58 | x = max(0, x) 59 | x = min(m - 1, x) 60 | return x 61 | expected_pos = (expect(pos[0], size[0]), expect(pos[1], size[1])) 62 | return expected_pos 63 | 64 | class Test(TestCase): 65 | def test_size(self): 66 | for size in screen_sizes: 67 | with Display(visible=VISIBLE, size=size): 68 | mouse = PyMouse() 69 | eq_(size, mouse.screen_size()) 70 | 71 | def test_move(self): 72 | for size in screen_sizes: 73 | with Display(visible=VISIBLE, size=size): 74 | mouse = PyMouse() 75 | for p in positions: 76 | mouse.move(*p) 77 | eq_(expect_pos(p, size), mouse.position()) 78 | 79 | def test_event(self): 80 | for size in screen_sizes: 81 | with Display(visible=VISIBLE, size=size): 82 | time.sleep(3) # TODO: how long should we wait? 83 | mouse = PyMouse() 84 | event = Event() 85 | event.start() 86 | for p in positions: 87 | event.pos = None 88 | mouse.move(*p) 89 | time.sleep(0.1) # TODO: how long should we wait? 90 | print 'check ', expect_pos(p, size), '=', event.pos 91 | eq_(expect_pos(p, size), event.pos) 92 | event.stop() 93 | --------------------------------------------------------------------------------