Home | History | Annotate | Download | only in chromedriver
      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.
      4 
      5 #include "chrome/test/chromedriver/keycode_text_conversion.h"
      6 
      7 #include <windows.h>
      8 
      9 #include <cctype>
     10 
     11 #include "base/strings/utf_string_conversions.h"
     12 #include "chrome/test/chromedriver/chrome/ui_events.h"
     13 
     14 bool ConvertKeyCodeToText(
     15     ui::KeyboardCode key_code, int modifiers, std::string* text,
     16     std::string* error_msg) {
     17   UINT scan_code = ::MapVirtualKeyW(key_code, MAPVK_VK_TO_VSC);
     18   BYTE keyboard_state[256];
     19   memset(keyboard_state, 0, 256);
     20   *error_msg = std::string();
     21   if (modifiers & kShiftKeyModifierMask)
     22     keyboard_state[VK_SHIFT] |= 0x80;
     23   if (modifiers & kControlKeyModifierMask)
     24     keyboard_state[VK_CONTROL] |= 0x80;
     25   if (modifiers & kAltKeyModifierMask)
     26     keyboard_state[VK_MENU] |= 0x80;
     27   wchar_t chars[5];
     28   int code = ::ToUnicode(key_code, scan_code, keyboard_state, chars, 4, 0);
     29   // |ToUnicode| converts some non-text key codes like F1 to various ASCII
     30   // control chars. Filter those out.
     31   if (code <= 0 || (code == 1 && std::iscntrl(chars[0])))
     32     *text = std::string();
     33   else
     34     WideToUTF8(chars, code, text);
     35   return true;
     36 }
     37 
     38 bool ConvertCharToKeyCode(
     39     char16 key, ui::KeyboardCode* key_code, int *necessary_modifiers,
     40     std::string* error_msg) {
     41   short vkey_and_modifiers = ::VkKeyScanW(key);
     42   bool translated = vkey_and_modifiers != -1 &&
     43                     LOBYTE(vkey_and_modifiers) != -1 &&
     44                     HIBYTE(vkey_and_modifiers) != -1;
     45   *error_msg = std::string();
     46   if (translated) {
     47     *key_code = static_cast<ui::KeyboardCode>(LOBYTE(vkey_and_modifiers));
     48     int win_modifiers = HIBYTE(vkey_and_modifiers);
     49     int modifiers = 0;
     50     if (win_modifiers & 0x01)
     51       modifiers |= kShiftKeyModifierMask;
     52     if (win_modifiers & 0x02)
     53       modifiers |= kControlKeyModifierMask;
     54     if (win_modifiers & 0x04)
     55       modifiers |= kAltKeyModifierMask;
     56     // Ignore bit 0x08: It is for Hankaku key.
     57     *necessary_modifiers = modifiers;
     58   }
     59   return translated;
     60 }
     61