Home | History | Annotate | Download | only in webdriver
      1 // Copyright (c) 2011 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/webdriver/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/common/automation_constants.h"
     13 
     14 namespace webdriver {
     15 
     16 std::string ConvertKeyCodeToText(ui::KeyboardCode key_code, int modifiers) {
     17   UINT scan_code = ::MapVirtualKeyW(key_code, MAPVK_VK_TO_VSC);
     18   BYTE keyboard_state[256];
     19   memset(keyboard_state, 0, 256);
     20   if (modifiers & automation::kShiftKeyMask)
     21     keyboard_state[VK_SHIFT] |= 0x80;
     22   if (modifiers & automation::kControlKeyMask)
     23     keyboard_state[VK_CONTROL] |= 0x80;
     24   if (modifiers & automation::kAltKeyMask)
     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 ASCII
     29   // control chars. Filter those out.
     30   if (code <= 0 || (code == 1 && std::iscntrl(chars[0]))) {
     31     return "";
     32   } else {
     33     std::string text;
     34     WideToUTF8(chars, code, &text);
     35     return text;
     36   }
     37 }
     38 
     39 bool ConvertCharToKeyCode(
     40     char16 key, ui::KeyboardCode* key_code, int *necessary_modifiers) {
     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   if (translated) {
     46     *key_code = static_cast<ui::KeyboardCode>(LOBYTE(vkey_and_modifiers));
     47     *necessary_modifiers = HIBYTE(vkey_and_modifiers);
     48   }
     49   return translated;
     50 }
     51 
     52 }  // namespace webdriver
     53