Roll src/third_party/WebKit bf18a82:a9cee16 (svn 185297:185304)
[chromium-blink-merge.git] / chrome / test / chromedriver / keycode_text_conversion_win.cc
blob802eb3c7483246e9b67758539e32f982abc3ce0d
1 // Copyright (c) 2013 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.
5 #include "chrome/test/chromedriver/keycode_text_conversion.h"
7 #include <stdlib.h>
8 #include <windows.h>
10 #include "base/strings/utf_string_conversions.h"
11 #include "chrome/test/chromedriver/chrome/ui_events.h"
13 bool ConvertKeyCodeToText(
14 ui::KeyboardCode key_code, int modifiers, std::string* text,
15 std::string* error_msg) {
16 UINT scan_code = ::MapVirtualKeyW(key_code, MAPVK_VK_TO_VSC);
17 BYTE keyboard_state[256];
18 memset(keyboard_state, 0, 256);
19 *error_msg = std::string();
20 if (modifiers & kShiftKeyModifierMask)
21 keyboard_state[VK_SHIFT] |= 0x80;
22 if (modifiers & kControlKeyModifierMask)
23 keyboard_state[VK_CONTROL] |= 0x80;
24 if (modifiers & kAltKeyModifierMask)
25 keyboard_state[VK_MENU] |= 0x80;
26 wchar_t chars[5];
27 int code = ::ToUnicode(key_code, scan_code, keyboard_state, chars, 4, 0);
28 // |ToUnicode| converts some non-text key codes like F1 to various
29 // control chars. Filter those out.
30 if (code <= 0 || (code == 1 && iswcntrl(chars[0])))
31 *text = std::string();
32 else
33 base::WideToUTF8(chars, code, text);
34 return true;
37 bool ConvertCharToKeyCode(
38 base::char16 key, ui::KeyboardCode* key_code, int *necessary_modifiers,
39 std::string* error_msg) {
40 short vkey_and_modifiers = ::VkKeyScanW(key);
41 bool translated = vkey_and_modifiers != -1 &&
42 LOBYTE(vkey_and_modifiers) != 0xFF &&
43 HIBYTE(vkey_and_modifiers) != 0xFF;
44 *error_msg = std::string();
45 if (translated) {
46 *key_code = static_cast<ui::KeyboardCode>(LOBYTE(vkey_and_modifiers));
47 int win_modifiers = HIBYTE(vkey_and_modifiers);
48 int modifiers = 0;
49 if (win_modifiers & 0x01)
50 modifiers |= kShiftKeyModifierMask;
51 if (win_modifiers & 0x02)
52 modifiers |= kControlKeyModifierMask;
53 if (win_modifiers & 0x04)
54 modifiers |= kAltKeyModifierMask;
55 // Ignore bit 0x08: It is for Hankaku key.
56 *necessary_modifiers = modifiers;
58 return translated;