1# Copyright 2016 The Chromium Authors. All rights reserved. 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4 5import string 6 7from telemetry.internal.actions import page_action 8 9 10# Map from DOM key values 11# (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) to 12# Windows virtual key codes 13# (https://cs.chromium.org/chromium/src/third_party/WebKit/Source/platform/WindowsKeyboardCodes.h) 14# and their printed representations (if available). 15_KEY_MAP = {} 16 17def _AddSpecialKey(key, windows_virtual_key_code, text=None): 18 assert key not in _KEY_MAP, 'Duplicate key: %s' % key 19 _KEY_MAP[key] = (windows_virtual_key_code, text) 20 21def _AddRegularKey(keys, windows_virtual_key_code): 22 for k in keys: 23 assert k not in _KEY_MAP, 'Duplicate key: %s' % k 24 _KEY_MAP[k] = (windows_virtual_key_code, k) 25 26_AddSpecialKey('PageUp', 0x21) 27_AddSpecialKey('PageDown', 0x22) 28_AddSpecialKey('End', 0x23) 29_AddSpecialKey('Home', 0x24) 30_AddSpecialKey('ArrowLeft', 0x25) 31_AddSpecialKey('ArrowUp', 0x26) 32_AddSpecialKey('ArrowRight', 0x27) 33_AddSpecialKey('ArrowDown', 0x28) 34 35_AddSpecialKey('Return', 0x0D, text='\x0D') 36_AddSpecialKey('Delete', 0x2E, text='\x7F') 37_AddSpecialKey('Backspace', 0x08, text='\x08') 38 39# Letter keys. 40for c in string.ascii_uppercase: 41 _AddRegularKey([c, c.lower()], ord(c)) 42 43# Symbol keys. 44_AddRegularKey(';:', 0xBA) 45_AddRegularKey('=+', 0xBB) 46_AddRegularKey(',<', 0xBC) 47_AddRegularKey('-_', 0xBD) 48_AddRegularKey('.>', 0xBE) 49_AddRegularKey('/?', 0xBF) 50_AddRegularKey('`~', 0xC0) 51_AddRegularKey('[{', 0xDB) 52_AddRegularKey('\\|', 0xDC) 53_AddRegularKey(']}', 0xDD) 54_AddRegularKey('\'"', 0xDE) 55 56# Numeric keys. 57_AddRegularKey('0)', 0x30) 58_AddRegularKey('1!', 0x31) 59_AddRegularKey('2@', 0x32) 60_AddRegularKey('3#', 0x33) 61_AddRegularKey('4$', 0x34) 62_AddRegularKey('5%', 0x35) 63_AddRegularKey('6^', 0x36) 64_AddRegularKey('7&', 0x37) 65_AddRegularKey('8*', 0x38) 66_AddRegularKey('9(', 0x39) 67 68# Space. 69_AddRegularKey(' ', 0x20) 70 71 72class KeyPressAction(page_action.PageAction): 73 74 def __init__(self, dom_key, timeout=60): 75 super(KeyPressAction, self).__init__() 76 self._dom_key = dom_key 77 if dom_key not in _KEY_MAP: 78 raise ValueError('No mapping for key: %s' % dom_key) 79 self._windows_virtual_key_code, self._text = _KEY_MAP[dom_key] 80 self._timeout = timeout 81 82 def RunAction(self, tab): 83 tab.DispatchKeyEvent(keyEventType='rawKeyDown', 84 domKey=self._dom_key, 85 windowsVirtualKeyCode=self._windows_virtual_key_code, 86 timeout=self._timeout) 87 if self._text: 88 tab.DispatchKeyEvent(keyEventType='char', 89 text=self._text, 90 domKey=self._dom_key, 91 windowsVirtualKeyCode=ord(self._text), 92 timeout=self._timeout) 93 tab.DispatchKeyEvent(keyEventType='keyUp', 94 domKey=self._dom_key, 95 windowsVirtualKeyCode=self._windows_virtual_key_code, 96 timeout=self._timeout) 97