/usr/lib/python2.7/dist-packages/autopilot/input/_X11.py is in python-autopilot 1.4.1+15.10.20150911-0ubuntu2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 | # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
#
# Autopilot Functional Test Tool
# Copyright (C) 2012, 2013, 2014 Canonical
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""A collection of emulators for X11 - namely keyboards and mice.
In the future we may also need other devices.
"""
from __future__ import absolute_import
import logging
import six
from autopilot.display import is_point_on_any_screen, move_mouse_to_screen
from autopilot.utilities import (
Silence,
sleep,
StagnantStateDetector,
)
from autopilot.input import (
Keyboard as KeyboardBase,
Mouse as MouseBase,
)
from Xlib import X, XK
from Xlib.display import Display
from Xlib.ext.xtest import fake_input
_PRESSED_KEYS = []
_PRESSED_MOUSE_BUTTONS = []
_DISPLAY = None
_logger = logging.getLogger(__name__)
def get_display():
"""Return the Xlib display object.
It is created (silently) if it doesn't exist.
"""
global _DISPLAY
if _DISPLAY is None:
with Silence():
_DISPLAY = Display()
return _DISPLAY
def reset_display():
global _DISPLAY
_DISPLAY = None
class Keyboard(KeyboardBase):
"""Wrapper around xlib to make faking keyboard input possible."""
_special_X_keysyms = {
' ': "space",
'\t': "Tab",
'\n': "Return", # for some reason this needs to be cr, not lf
'\r': "Return",
'\e': "Escape",
'\b': "BackSpace",
'!': "exclam",
'#': "numbersign",
'%': "percent",
'$': "dollar",
'&': "ampersand",
'"': "quotedbl",
'\'': "apostrophe",
'(': "parenleft",
')': "parenright",
'*': "asterisk",
'=': "equal",
'+': "plus",
',': "comma",
'-': "minus",
'.': "period",
'/': "slash",
':': "colon",
';': "semicolon",
'<': "less",
'>': "greater",
'?': "question",
'@': "at",
'[': "bracketleft",
']': "bracketright",
'\\': "backslash",
'^': "asciicircum",
'_': "underscore",
'`': "grave",
'{': "braceleft",
'|': "bar",
'}': "braceright",
'~': "asciitilde"
}
_keysym_translations = {
'Control': 'Control_L',
'Ctrl': 'Control_L',
'Alt': 'Alt_L',
'AltR': 'Alt_R',
'Super': 'Super_L',
'Shift': 'Shift_L',
'Enter': 'Return',
'Space': ' ',
'Backspace': 'BackSpace',
}
def __init__(self):
super(Keyboard, self).__init__()
self.shifted_keys = [k[1] for k in get_display()._keymap_codes if k]
def press(self, keys, delay=0.2):
"""Send key press events only.
:param string keys: Keys you want pressed.
Example::
press('Alt+F2')
presses the 'Alt' and 'F2' keys.
"""
if not isinstance(keys, six.string_types):
raise TypeError("'keys' argument must be a string.")
_logger.debug("Pressing keys %r with delay %f", keys, delay)
for key in self.__translate_keys(keys):
self.__perform_on_key(key, X.KeyPress)
sleep(delay)
def release(self, keys, delay=0.2):
"""Send key release events only.
:param string keys: Keys you want released.
Example::
release('Alt+F2')
releases the 'Alt' and 'F2' keys.
"""
if not isinstance(keys, six.string_types):
raise TypeError("'keys' argument must be a string.")
_logger.debug("Releasing keys %r with delay %f", keys, delay)
# release keys in the reverse order they were pressed in.
keys = self.__translate_keys(keys)
keys.reverse()
for key in keys:
self.__perform_on_key(key, X.KeyRelease)
sleep(delay)
def press_and_release(self, keys, delay=0.2):
"""Press and release all items in 'keys'.
This is the same as calling 'press(keys);release(keys)'.
:param string keys: Keys you want pressed and released.
Example::
press_and_release('Alt+F2')
presses both the 'Alt' and 'F2' keys, and then releases both keys.
"""
self.press(keys, delay)
self.release(keys, delay)
def type(self, string, delay=0.1):
"""Simulate a user typing a string of text.
.. note:: Only 'normal' keys can be typed with this method. Control
characters (such as 'Alt' will be interpreted as an 'A', and 'l',
and a 't').
"""
if not isinstance(string, six.string_types):
raise TypeError("'keys' argument must be a string.")
_logger.debug("Typing text %r", string)
for key in string:
# Don't call press or release here, as they translate keys to
# keysyms.
self.__perform_on_key(key, X.KeyPress)
sleep(delay)
self.__perform_on_key(key, X.KeyRelease)
sleep(delay)
@classmethod
def on_test_end(cls, test_instance):
"""Generate KeyRelease events for any un-released keys.
.. important:: Ensure you call this at the end of any test to release
any keys that were pressed and not released.
"""
global _PRESSED_KEYS
for keycode in _PRESSED_KEYS:
_logger.warning(
"Releasing key %r as part of cleanup call.", keycode)
fake_input(get_display(), X.KeyRelease, keycode)
_PRESSED_KEYS = []
def __perform_on_key(self, key, event):
if not isinstance(key, six.string_types):
raise TypeError("Key parameter must be a string")
keycode = 0
shift_mask = 0
keycode, shift_mask = self.__char_to_keycode(key)
if shift_mask != 0:
fake_input(get_display(), event, 50)
if event == X.KeyPress:
_logger.debug("Sending press event for key: %s", key)
_PRESSED_KEYS.append(keycode)
elif event == X.KeyRelease:
_logger.debug("Sending release event for key: %s", key)
if keycode in _PRESSED_KEYS:
_PRESSED_KEYS.remove(keycode)
else:
_logger.warning(
"Generating release event for keycode %d that was not "
"pressed.", keycode)
fake_input(get_display(), event, keycode)
get_display().sync()
def __get_keysym(self, key):
keysym = XK.string_to_keysym(key)
if keysym == 0:
# Unfortunately, although this works to get the correct keysym
# i.e. keysym for '#' is returned as "numbersign"
# the subsequent display.keysym_to_keycode("numbersign") is 0.
keysym = XK.string_to_keysym(self._special_X_keysyms[key])
return keysym
def __is_shifted(self, key):
return len(key) == 1 and ord(key) in self.shifted_keys and key != '<'
def __char_to_keycode(self, key):
keysym = self.__get_keysym(key)
keycode = get_display().keysym_to_keycode(keysym)
if keycode == 0:
_logger.warning("Sorry, can't map '%s'", key)
if (self.__is_shifted(key)):
shift_mask = X.ShiftMask
else:
shift_mask = 0
return keycode, shift_mask
def __translate_keys(self, key_string):
if len(key_string) > 1:
return [self._keysym_translations.get(k, k)
for k in key_string.split('+')]
else:
# workaround that lets us press_and_release '+' by itself.
return [self._keysym_translations.get(key_string, key_string)]
class Mouse(MouseBase):
"""Wrapper around xlib to make moving the mouse easier."""
def __init__(self):
super(Mouse, self).__init__()
# Try to access the screen to see if X11 mouse is supported
get_display()
@property
def x(self):
"""Mouse position X coordinate."""
return self.position()[0]
@property
def y(self):
"""Mouse position Y coordinate."""
return self.position()[1]
def press(self, button=1):
"""Press mouse button at current mouse location."""
_logger.debug("Pressing mouse button %d", button)
_PRESSED_MOUSE_BUTTONS.append(button)
fake_input(get_display(), X.ButtonPress, button)
get_display().sync()
def release(self, button=1):
"""Releases mouse button at current mouse location."""
_logger.debug("Releasing mouse button %d", button)
if button in _PRESSED_MOUSE_BUTTONS:
_PRESSED_MOUSE_BUTTONS.remove(button)
else:
_logger.warning(
"Generating button release event or button %d that was not "
"pressed.", button)
fake_input(get_display(), X.ButtonRelease, button)
get_display().sync()
def click(self, button=1, press_duration=0.10):
"""Click mouse at current location."""
self.press(button)
sleep(press_duration)
self.release(button)
def move(self, x, y, animate=True, rate=10, time_between_events=0.01):
"""Moves mouse to location (x, y).
Callers should avoid specifying the *rate* or *time_between_events*
parameters unless they need a specific rate of movement.
"""
def perform_move(x, y, sync):
fake_input(
get_display(),
X.MotionNotify,
sync,
X.CurrentTime,
X.NONE,
x=int(x),
y=int(y))
get_display().sync()
sleep(time_between_events)
dest_x, dest_y = int(x), int(y)
_logger.debug(
"Moving mouse to position %d,%d %s animation.", dest_x, dest_y,
"with" if animate else "without")
if not animate:
perform_move(dest_x, dest_y, False)
return
coordinate_valid = is_point_on_any_screen((dest_x, dest_y))
if x < -1000 or y < -1000:
raise ValueError(
"Invalid mouse coordinates: %d, %d" % (dest_x, dest_y))
loop_detector = StagnantStateDetector(threshold=1000)
curr_x, curr_y = self.position()
while curr_x != dest_x or curr_y != dest_y:
dx = abs(dest_x - curr_x)
dy = abs(dest_y - curr_y)
intx = float(dx) / max(dx, dy)
inty = float(dy) / max(dx, dy)
step_x = min(rate * intx, dx)
step_y = min(rate * inty, dy)
if dest_x < curr_x:
step_x *= -1
if dest_y < curr_y:
step_y *= -1
perform_move(step_x, step_y, True)
if coordinate_valid:
curr_x, curr_y = self.position()
else:
curr_x += step_x
curr_y += step_y
try:
loop_detector.check_state(curr_x, curr_y)
except StagnantStateDetector.StagnantState as e:
e.args = ("Mouse cursor is stuck.", )
raise
def move_to_object(self, object_proxy):
"""Attempts to move the mouse to 'object_proxy's centre point.
It does this by looking for several attributes, in order. The first
attribute found will be used. The attributes used are (in order):
* globalRect (x,y,w,h)
* center_x, center_y
* x, y, w, h
:raises: **ValueError** if none of these attributes are found, or if an
attribute is of an incorrect type.
"""
try:
x, y, w, h = object_proxy.globalRect
_logger.debug("Moving to object's globalRect coordinates.")
self.move(x+w/2, y+h/2)
return
except AttributeError:
pass
except (TypeError, ValueError):
raise ValueError(
"Object '%r' has globalRect attribute, but it is not of the "
"correct type" % object_proxy)
try:
x, y = object_proxy.center_x, object_proxy.center_y
_logger.debug("Moving to object's center_x, center_y coordinates.")
self.move(x, y)
return
except AttributeError:
pass
except (TypeError, ValueError):
raise ValueError(
"Object '%r' has center_x, center_y attributes, but they are "
"not of the correct type" % object_proxy)
try:
x, y, w, h = (
object_proxy.x, object_proxy.y, object_proxy.w, object_proxy.h)
_logger.debug(
"Moving to object's center point calculated from x,y,w,h "
"attributes.")
self.move(x+w/2, y+h/2)
return
except AttributeError:
raise ValueError(
"Object '%r' does not have any recognised position "
"attributes" % object_proxy)
except (TypeError, ValueError):
raise ValueError(
"Object '%r' has x,y attribute, but they are not of the "
"correct type" % object_proxy)
def position(self):
"""
Returns the current position of the mouse pointer.
:return: (x,y) tuple
"""
coord = get_display().screen().root.query_pointer()._data
x, y = coord["root_x"], coord["root_y"]
return x, y
def drag(self, x1, y1, x2, y2, rate=10, time_between_events=0.01):
"""Perform a press, move and release.
This is to keep a common API between Mouse and Finger as long as
possible.
The pointer will be dragged from the starting point to the ending point
with multiple moves. The number of moves, and thus the time that it
will take to complete the drag can be altered with the `rate`
parameter.
:param x1: The point on the x axis where the drag will start from.
:param y1: The point on the y axis where the drag will starts from.
:param x2: The point on the x axis where the drag will end at.
:param y2: The point on the y axis where the drag will end at.
:param rate: The number of pixels the mouse will be moved per
iteration. Default is 10 pixels. A higher rate will make the drag
faster, and lower rate will make it slower.
:param time_between_events: The number of seconds that the drag will
wait between iterations.
"""
self.move(x1, y1)
self.press()
self.move(x2, y2, rate=rate, time_between_events=time_between_events)
self.release()
@classmethod
def on_test_end(cls, test_instance):
"""Put mouse in a known safe state."""
global _PRESSED_MOUSE_BUTTONS
for btn in _PRESSED_MOUSE_BUTTONS:
_logger.debug("Releasing mouse button %d as part of cleanup", btn)
fake_input(get_display(), X.ButtonRelease, btn)
_PRESSED_MOUSE_BUTTONS = []
move_mouse_to_screen(0)
|