summaryrefslogtreecommitdiffstats
path: root/tools/site_compare/drivers
diff options
context:
space:
mode:
authormaruel@chromium.org <maruel@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98>2009-03-05 12:46:38 +0000
committermaruel@chromium.org <maruel@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98>2009-03-05 12:46:38 +0000
commitf0a51fb571f46531025fa09240bbc3e1af925e84 (patch)
tree558b4f0e737fda4b9ab60f252c9c23b8a4ca523e /tools/site_compare/drivers
parent6390be368205705f49ead3cec40396519f13b889 (diff)
downloadchromium_src-f0a51fb571f46531025fa09240bbc3e1af925e84.zip
chromium_src-f0a51fb571f46531025fa09240bbc3e1af925e84.tar.gz
chromium_src-f0a51fb571f46531025fa09240bbc3e1af925e84.tar.bz2
Fixes CRLF and trailing white spaces.
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@10982 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'tools/site_compare/drivers')
-rw-r--r--tools/site_compare/drivers/__init__.py2
-rw-r--r--tools/site_compare/drivers/win32/keyboard.py66
-rw-r--r--tools/site_compare/drivers/win32/mouse.py80
-rw-r--r--tools/site_compare/drivers/win32/windowing.py110
4 files changed, 129 insertions, 129 deletions
diff --git a/tools/site_compare/drivers/__init__.py b/tools/site_compare/drivers/__init__.py
index befc1353..fa9f1c2 100644
--- a/tools/site_compare/drivers/__init__.py
+++ b/tools/site_compare/drivers/__init__.py
@@ -9,7 +9,7 @@ __author__ = 'jhaas@google.com (Jonathan Haas)'
import sys
platform_dir = sys.platform
-
+
keyboard = __import__(platform_dir+".keyboard", globals(), locals(), [''])
mouse = __import__(platform_dir+".mouse", globals(), locals(), [''])
windowing = __import__(platform_dir+".windowing", globals(), locals(), [''])
diff --git a/tools/site_compare/drivers/win32/keyboard.py b/tools/site_compare/drivers/win32/keyboard.py
index a25df5e..246e14c 100644
--- a/tools/site_compare/drivers/win32/keyboard.py
+++ b/tools/site_compare/drivers/win32/keyboard.py
@@ -25,45 +25,45 @@ import win32con # Windows constants
def PressKey(down, key):
"""Presses or unpresses a key.
-
+
Uses keybd_event to simulate either depressing or releasing
a key
-
+
Args:
down: Whether the key is to be pressed or released
key: Virtual key code of key to press or release
"""
-
- # keybd_event injects key events at a very low level (it's the
+
+ # keybd_event injects key events at a very low level (it's the
# Windows API keyboard device drivers call) so this is a very
# reliable way of simulating user input
win32api.keybd_event(key, 0, (not down) * win32con.KEYEVENTF_KEYUP)
-
-
+
+
def TypeKey(key, keystroke_time=0):
"""Simulate a keypress of a virtual key.
-
+
Args:
key: which key to press
keystroke_time: length of time (in seconds) to "hold down" the key
Note that zero works just fine
-
+
Returns:
None
"""
-
+
# This just wraps a pair of PressKey calls with an intervening delay
PressKey(True, key)
time.sleep(keystroke_time)
PressKey(False, key)
-
+
def TypeString(string_to_type,
use_modifiers=False,
keystroke_time=0,
time_between_keystrokes=0):
"""Simulate typing a string on the keyboard.
-
+
Args:
string_to_type: the string to print
use_modifiers: specifies whether the following modifier characters
@@ -79,27 +79,27 @@ def TypeString(string_to_type,
nonprintable keys (F-keys, ESC, arrow keys, etc),
support for explicit control of left vs. right ALT or SHIFT,
support for Windows key
-
+
keystroke_time: length of time (in secondes) to "hold down" the key
time_between_keystrokes: length of time (seconds) to pause between keys
-
+
Returns:
None
"""
-
+
shift_held = win32api.GetAsyncKeyState(win32con.VK_SHIFT ) < 0
ctrl_held = win32api.GetAsyncKeyState(win32con.VK_CONTROL) < 0
alt_held = win32api.GetAsyncKeyState(win32con.VK_MENU ) < 0
-
+
next_escaped = False
escape_chars = {
'a': '\a', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t', 'v': '\v'}
-
+
for char in string_to_type:
vk = None
handled = False
-
- # Check to see if this is the start or end of a modified block (that is,
+
+ # Check to see if this is the start or end of a modified block (that is,
# {abc} for ALT-modified keys or [abc] for CTRL-modified keys
if use_modifiers and not next_escaped:
handled = True
@@ -117,17 +117,17 @@ def TypeString(string_to_type,
PressKey(False, win32con.VK_CONTROL)
else:
handled = False
-
+
# If this is an explicitly-escaped character, replace it with the
# appropriate code
if next_escaped and char in escape_chars: char = escape_chars[char]
-
+
# If this is \p, pause for one second.
if next_escaped and char == 'p':
time.sleep(1)
next_escaped = False
handled = True
-
+
# If this is \(d), press F key
if next_escaped and char.isdigit():
fkey = int(char)
@@ -139,28 +139,28 @@ def TypeString(string_to_type,
if not next_escaped and char == "\\":
next_escaped = True
handled = True
-
+
# If we make it here, it's not a special character, or it's an
# escaped special character which should be treated as a literal
if not handled:
next_escaped = False
if not vk: vk = win32api.VkKeyScan(char)
-
+
# VkKeyScan() returns the scan code in the low byte. The upper
# byte specifies modifiers necessary to produce the given character
# from the given scan code. The only one we're concerned with at the
- # moment is Shift. Determine the shift state and compare it to the
+ # moment is Shift. Determine the shift state and compare it to the
# current state... if it differs, press or release the shift key.
new_shift_held = bool(vk & (1<<8))
-
+
if new_shift_held != shift_held:
PressKey(new_shift_held, win32con.VK_SHIFT)
shift_held = new_shift_held
-
+
# Type the key with the specified length, then wait the specified delay
TypeKey(vk & 0xFF, keystroke_time)
time.sleep(time_between_keystrokes)
-
+
# Release the modifier keys, if held
if shift_held: PressKey(False, win32con.VK_SHIFT)
if ctrl_held: PressKey(False, win32con.VK_CONTROL)
@@ -168,18 +168,18 @@ def TypeString(string_to_type,
if __name__ == "__main__":
# We're being invoked rather than imported. Let's do some tests
-
+
# Press command-R to bring up the Run dialog
PressKey(True, win32con.VK_LWIN)
TypeKey(ord('R'))
PressKey(False, win32con.VK_LWIN)
-
+
# Wait a sec to make sure it comes up
time.sleep(1)
-
+
# Invoke Notepad through the Run dialog
TypeString("wordpad\n")
-
+
# Wait another sec, then start typing
time.sleep(1)
TypeString("This is a test of SiteCompare's Keyboard.py module.\n\n")
@@ -194,5 +194,5 @@ if __name__ == "__main__":
use_modifiers=True,
keystroke_time=0.05,
time_between_keystrokes=0.05)
-
-
+
+
diff --git a/tools/site_compare/drivers/win32/mouse.py b/tools/site_compare/drivers/win32/mouse.py
index afdb2ea..bd16272 100644
--- a/tools/site_compare/drivers/win32/mouse.py
+++ b/tools/site_compare/drivers/win32/mouse.py
@@ -19,25 +19,25 @@ import win32gui # for window functions
def ScreenToMouse(pt):
"""Convert a value in screen coordinates to mouse coordinates.
-
+
Mouse coordinates are specified as a percentage of screen dimensions,
normalized to 16 bits. 0 represents the far left/top of the screen,
65535 represents the far right/bottom. This function assumes that
the size of the screen is fixed at module load time and does not change
-
+
Args:
pt: the point of the coords to convert
-
+
Returns:
the converted point
"""
-
+
# Initialize the screen dimensions on first execution. Note that this
# function assumes that the screen dimensions do not change during run.
if not ScreenToMouse._SCREEN_DIMENSIONS:
desktop = win32gui.GetClientRect(win32gui.GetDesktopWindow())
ScreenToMouse._SCREEN_DIMENSIONS = (desktop[2], desktop[3])
-
+
return ((65535 * pt[0]) / ScreenToMouse._SCREEN_DIMENSIONS[0],
(65535 * pt[1]) / ScreenToMouse._SCREEN_DIMENSIONS[1])
@@ -46,11 +46,11 @@ ScreenToMouse._SCREEN_DIMENSIONS = None
def PressButton(down, button='left'):
"""Simulate a mouse button press or release at the current mouse location.
-
+
Args:
down: whether the button is pressed or released
button: which button is pressed
-
+
Returns:
None
"""
@@ -61,127 +61,127 @@ def PressButton(down, button='left'):
'middle': (win32con.MOUSEEVENTF_MIDDLEUP, win32con.MOUSEEVENTF_MIDDLEDOWN),
'right': (win32con.MOUSEEVENTF_RIGHTUP, win32con.MOUSEEVENTF_RIGHTDOWN)
}
-
+
# hit the button
win32api.mouse_event(flags[button][down], 0, 0)
-
+
def ClickButton(button='left', click_time=0):
"""Press and release a mouse button at the current mouse location.
-
+
Args:
button: which button to click
click_time: duration between press and release
-
+
Returns:
None
"""
PressButton(True, button)
time.sleep(click_time)
PressButton(False, button)
-
-
+
+
def DoubleClickButton(button='left', click_time=0, time_between_clicks=0):
"""Double-click a mouse button at the current mouse location.
-
+
Args:
button: which button to click
click_time: duration between press and release
time_between_clicks: time to pause between clicks
-
+
Returns:
None
"""
ClickButton(button, click_time)
time.sleep(time_between_clicks)
ClickButton(button, click_time)
-
+
def MoveToLocation(pos, duration=0, tick=0.01):
"""Move the mouse cursor to a specified location, taking the specified time.
-
+
Args:
pos: position (in screen coordinates) to move to
duration: amount of time the move should take
tick: amount of time between successive moves of the mouse
-
+
Returns:
None
"""
# calculate the number of moves to reach the destination
num_steps = (duration/tick)+1
-
+
# get the current and final mouse position in mouse coords
current_location = ScreenToMouse(win32gui.GetCursorPos())
end_location = ScreenToMouse(pos)
-
+
# Calculate the step size
step_size = ((end_location[0]-current_location[0])/num_steps,
(end_location[1]-current_location[1])/num_steps)
step = 0
-
+
while step < num_steps:
# Move the mouse one step
current_location = (current_location[0]+step_size[0],
current_location[1]+step_size[1])
-
+
# Coerce the coords to int to avoid a warning from pywin32
win32api.mouse_event(
win32con.MOUSEEVENTF_MOVE|win32con.MOUSEEVENTF_ABSOLUTE,
int(current_location[0]), int(current_location[1]))
-
+
step += 1
time.sleep(tick)
-
-
+
+
def ClickAtLocation(pos, button='left', click_time=0):
"""Simulate a mouse click in a particular location, in screen coordinates.
-
+
Args:
pos: position in screen coordinates (x,y)
button: which button to click
click_time: duration of the click
-
+
Returns:
None
"""
MoveToLocation(pos)
ClickButton(button, click_time)
-
+
def ClickInWindow(hwnd, offset=None, button='left', click_time=0):
"""Simulate a user mouse click in the center of a window.
-
+
Args:
hwnd: handle of the window to click in
offset: where to click, defaults to dead center
button: which button to click
click_time: duration of the click
-
+
Returns:
Nothing
"""
-
+
rect = win32gui.GetClientRect(hwnd)
if offset is None: offset = (rect[2]/2, rect[3]/2)
# get the screen coordinates of the window's center
pos = win32gui.ClientToScreen(hwnd, offset)
-
+
ClickAtLocation(pos, button, click_time)
-
+
def DoubleClickInWindow(
hwnd, offset=None, button='left', click_time=0, time_between_clicks=0.1):
"""Simulate a user mouse double click in the center of a window.
-
+
Args:
hwnd: handle of the window to click in
offset: where to click, defaults to dead center
button: which button to click
click_time: duration of the clicks
time_between_clicks: length of time to pause between clicks
-
+
Returns:
Nothing
"""
@@ -191,13 +191,13 @@ def DoubleClickInWindow(
if __name__ == "__main__":
# We're being invoked rather than imported. Let's do some tests
-
+
screen_size = win32gui.GetClientRect(win32gui.GetDesktopWindow())
screen_size = (screen_size[2], screen_size[3])
-
+
# move the mouse (instantly) to the upper right corner
MoveToLocation((screen_size[0], 0))
-
+
# move the mouse (over five seconds) to the lower left corner
MoveToLocation((0, screen_size[1]), 5)
@@ -209,10 +209,10 @@ if __name__ == "__main__":
# wait a bit, then click the right button to open the context menu
time.sleep(3)
ClickButton('right')
-
+
# move the mouse away and then click the left button to dismiss the
# context menu
MoveToLocation((screen_size[0]/2, screen_size[1]/2), 3)
MoveToLocation((0, 0), 3)
ClickButton()
-
+
diff --git a/tools/site_compare/drivers/win32/windowing.py b/tools/site_compare/drivers/win32/windowing.py
index 5bc37f8..fe77c56 100644
--- a/tools/site_compare/drivers/win32/windowing.py
+++ b/tools/site_compare/drivers/win32/windowing.py
@@ -24,7 +24,7 @@ import win32process
def FindChildWindows(hwnd, path):
"""Find a set of windows through a path specification.
-
+
Args:
hwnd: Handle of the parent window
path: Path to the window to find. Has the following form:
@@ -32,12 +32,12 @@ def FindChildWindows(hwnd, path):
The slashes specify the "path" to the child window.
The text is the window class, a pipe (if present) is a title.
* is a wildcard and will find all child windows at that level
-
+
Returns:
A list of the windows that were found
"""
windows_to_check = [hwnd]
-
+
# The strategy will be to take windows_to_check and use it
# to find a list of windows that match the next specification
# in the path, then repeat with the list of found windows as the
@@ -45,7 +45,7 @@ def FindChildWindows(hwnd, path):
for segment in path.split("/"):
windows_found = []
check_values = segment.split("|")
-
+
# check_values is now a list with the first element being
# the window class, the second being the window caption.
# If the class is absent (or wildcarded) set it to None
@@ -53,7 +53,7 @@ def FindChildWindows(hwnd, path):
# If the window caption is also absent, force it to None as well
if len(check_values) == 1: check_values.append(None)
-
+
# Loop through the list of windows to check
for window_check in windows_to_check:
window_found = None
@@ -70,26 +70,26 @@ def FindChildWindows(hwnd, path):
window_found = 0
else:
raise e
-
+
# If FindWindowEx struck gold, add to our list of windows found
if window_found: windows_found.append(window_found)
-
+
# The windows we found become the windows to check for the next segment
windows_to_check = windows_found
-
+
return windows_found
def FindChildWindow(hwnd, path):
"""Find a window through a path specification.
-
+
This method is a simple wrapper for FindChildWindows() for the
case (the majority case) where you expect to find a single window
-
+
Args:
hwnd: Handle of the parent window
path: Path to the window to find. See FindChildWindows()
-
+
Returns:
The window that was found
"""
@@ -98,36 +98,36 @@ def FindChildWindow(hwnd, path):
def ScrapeWindow(hwnd, rect=None):
"""Scrape a visible window and return its contents as a bitmap.
-
+
Args:
hwnd: handle of the window to scrape
rect: rectangle to scrape in client coords, defaults to the whole thing
If specified, it's a 4-tuple of (left, top, right, bottom)
-
+
Returns:
An Image containing the scraped data
"""
# Activate the window
SetForegroundWindow(hwnd)
-
+
# If no rectangle was specified, use the fill client rectangle
if not rect: rect = win32gui.GetClientRect(hwnd)
-
+
upper_left = win32gui.ClientToScreen(hwnd, (rect[0], rect[1]))
lower_right = win32gui.ClientToScreen(hwnd, (rect[2], rect[3]))
rect = upper_left+lower_right
-
+
return PIL.ImageGrab.grab(rect)
-
+
def SetForegroundWindow(hwnd):
"""Bring a window to the foreground."""
win32gui.SetForegroundWindow(hwnd)
-
-
+
+
def InvokeAndWait(path, cmdline="", timeout=10, tick=1.):
"""Invoke an application and wait for it to bring up a window.
-
+
Args:
path: full path to the executable to invoke
cmdline: command line to pass to executable
@@ -138,7 +138,7 @@ def InvokeAndWait(path, cmdline="", timeout=10, tick=1.):
A tuple of handles to the process and the application's window,
or (None, None) if it timed out waiting for the process
"""
-
+
def EnumWindowProc(hwnd, ret):
"""Internal enumeration func, checks for visibility and proper PID."""
if win32gui.IsWindowVisible(hwnd): # don't bother even checking hidden wnds
@@ -147,12 +147,12 @@ def InvokeAndWait(path, cmdline="", timeout=10, tick=1.):
ret[1] = hwnd
return 0 # 0 means stop enumeration
return 1 # 1 means continue enumeration
-
+
# We don't need to change anything about the startupinfo structure
# (the default is quite sufficient) but we need to create it just the
# same.
sinfo = win32process.STARTUPINFO()
-
+
proc = win32process.CreateProcess(
path, # path to new process's executable
cmdline, # application's command line
@@ -168,16 +168,16 @@ def InvokeAndWait(path, cmdline="", timeout=10, tick=1.):
# some point we may care about the other members, but for now, all
# we're after is the pid
pid = proc[2]
-
+
# Enumeration APIs can take an arbitrary integer, usually a pointer,
# to be passed to the enumeration function. We'll pass a pointer to
# a structure containing the PID we're looking for, and an empty out
# parameter to hold the found window ID
ret = [pid, None]
-
+
tries_until_timeout = timeout/tick
num_tries = 0
-
+
# Enumerate top-level windows, look for one with our PID
while num_tries < tries_until_timeout and ret[1] is None:
try:
@@ -186,7 +186,7 @@ def InvokeAndWait(path, cmdline="", timeout=10, tick=1.):
# error 0 isn't an error, it just meant the enumeration was
# terminated early
if e[0]: raise e
-
+
time.sleep(tick)
num_tries += 1
@@ -197,11 +197,11 @@ def InvokeAndWait(path, cmdline="", timeout=10, tick=1.):
def WaitForProcessExit(proc, timeout=None):
"""Waits for a given process to terminate.
-
+
Args:
proc: handle to process
timeout: timeout (in seconds). None = wait indefinitely
-
+
Returns:
True if process ended, False if timed out
"""
@@ -210,26 +210,26 @@ def WaitForProcessExit(proc, timeout=None):
else:
# convert sec to msec
timeout *= 1000
-
+
return (win32event.WaitForSingleObject(proc, timeout) ==
win32event.WAIT_OBJECT_0)
def WaitForThrobber(hwnd, rect=None, timeout=20, tick=0.1, done=10):
"""Wait for a browser's "throbber" (loading animation) to complete.
-
+
Args:
hwnd: window containing the throbber
rect: rectangle of the throbber, in client coords. If None, whole window
timeout: if the throbber is still throbbing after this long, give up
tick: how often to check the throbber
done: how long the throbber must be unmoving to be considered done
-
+
Returns:
Number of seconds waited, -1 if timed out
"""
if not rect: rect = win32gui.GetClientRect(hwnd)
-
+
# last_throbber will hold the results of the preceding scrape;
# we'll compare it against the current scrape to see if we're throbbing
last_throbber = ScrapeWindow(hwnd, rect)
@@ -239,7 +239,7 @@ def WaitForThrobber(hwnd, rect=None, timeout=20, tick=0.1, done=10):
while time.clock() < timeout_clock:
time.sleep(tick)
-
+
current_throbber = ScrapeWindow(hwnd, rect)
if current_throbber.tostring() != last_throbber.tostring():
last_throbber = current_throbber
@@ -247,27 +247,27 @@ def WaitForThrobber(hwnd, rect=None, timeout=20, tick=0.1, done=10):
else:
if time.clock() - last_changed_clock > done:
return last_changed_clock - start_clock
-
+
return -1
def MoveAndSizeWindow(wnd, position=None, size=None, child=None):
"""Moves and/or resizes a window.
-
+
Repositions and resizes a window. If a child window is provided,
the parent window is resized so the child window has the given size
-
+
Args:
wnd: handle of the frame window
position: new location for the frame window
size: new size for the frame window (or the child window)
child: handle of the child window
-
+
Returns:
None
"""
rect = win32gui.GetWindowRect(wnd)
-
+
if position is None: position = (rect[0], rect[1])
if size is None:
size = (rect[2]-rect[0], rect[3]-rect[1])
@@ -276,7 +276,7 @@ def MoveAndSizeWindow(wnd, position=None, size=None, child=None):
slop = (rect[2]-rect[0]-child_rect[2]+child_rect[0],
rect[3]-rect[1]-child_rect[3]+child_rect[1])
size = (size[0]+slop[0], size[1]+slop[1])
-
+
win32gui.MoveWindow(wnd, # window to move
position[0], # new x coord
position[1], # new y coord
@@ -287,46 +287,46 @@ def MoveAndSizeWindow(wnd, position=None, size=None, child=None):
def EndProcess(proc, code=0):
"""Ends a process.
-
+
Wraps the OS TerminateProcess call for platform-independence
-
+
Args:
proc: process ID
code: process exit code
-
+
Returns:
None
"""
win32process.TerminateProcess(proc, code)
-
-
+
+
def URLtoFilename(url, path=None, extension=None):
"""Converts a URL to a filename, given a path.
-
+
This in theory could cause collisions if two URLs differ only
in unprintable characters (eg. http://www.foo.com/?bar and
http://www.foo.com/:bar. In practice this shouldn't be a problem.
-
+
Args:
url: The URL to convert
path: path to the directory to store the file
extension: string to append to filename
-
+
Returns:
filename
"""
trans = string.maketrans(r'\/:*?"<>|', '_________')
-
+
if path is None: path = ""
if extension is None: extension = ""
if len(path) > 0 and path[-1] != '\\': path += '\\'
url = url.translate(trans)
return "%s%s%s" % (path, url, extension)
-
+
def PreparePath(path):
"""Ensures that a given path exists, making subdirectories if necessary.
-
+
Args:
path: fully-qualified path of directory to ensure exists
@@ -341,11 +341,11 @@ def PreparePath(path):
if __name__ == "__main__":
PreparePath(r"c:\sitecompare\scrapes\ie7")
# We're being invoked rather than imported. Let's do some tests
-
+
# Hardcode IE's location for the purpose of this test
(proc, wnd) = InvokeAndWait(
r"c:\program files\internet explorer\iexplore.exe")
-
+
# Find the browser pane in the IE window
browser = FindChildWindow(
wnd, "TabWindowClass/Shell DocObject View/Internet Explorer_Server")
@@ -355,8 +355,8 @@ if __name__ == "__main__":
# Take a screenshot
i = ScrapeWindow(browser)
-
+
i.show()
-
+
EndProcess(proc, 0)