Home | History | Annotate | Download | only in win
      1 // Copyright 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 "ui/base/ime/win/imm32_manager.h"
      6 
      7 #include <msctf.h>
      8 
      9 #include "base/basictypes.h"
     10 #include "base/memory/scoped_ptr.h"
     11 #include "base/strings/string16.h"
     12 #include "base/strings/string_util.h"
     13 #include "base/strings/utf_string_conversions.h"
     14 #include "base/win/scoped_comptr.h"
     15 #include "third_party/skia/include/core/SkColor.h"
     16 #include "ui/base/ime/composition_text.h"
     17 
     18 // "imm32.lib" is required by IMM32 APIs used in this file.
     19 // NOTE(hbono): To comply with a comment from Darin, I have added
     20 // this #pragma directive instead of adding "imm32.lib" to a project file.
     21 #pragma comment(lib, "imm32.lib")
     22 
     23 // Following code requires wchar_t to be same as char16. It should always be
     24 // true on Windows.
     25 COMPILE_ASSERT(sizeof(wchar_t) == sizeof(base::char16), wchar_t__char16_diff);
     26 
     27 ///////////////////////////////////////////////////////////////////////////////
     28 // IMM32Manager
     29 
     30 namespace {
     31 
     32 // Determines whether or not the given attribute represents a target
     33 // (a.k.a. a selection).
     34 bool IsTargetAttribute(char attribute) {
     35   return (attribute == ATTR_TARGET_CONVERTED ||
     36           attribute == ATTR_TARGET_NOTCONVERTED);
     37 }
     38 
     39 // Helper function for IMM32Manager::GetCompositionInfo() method, to get the
     40 // target range that's selected by the user in the current composition string.
     41 void GetCompositionTargetRange(HIMC imm_context, int* target_start,
     42                                int* target_end) {
     43   int attribute_size = ::ImmGetCompositionString(imm_context, GCS_COMPATTR,
     44                                                  NULL, 0);
     45   if (attribute_size > 0) {
     46     int start = 0;
     47     int end = 0;
     48     scoped_ptr<char[]> attribute_data(new char[attribute_size]);
     49     if (attribute_data.get()) {
     50       ::ImmGetCompositionString(imm_context, GCS_COMPATTR,
     51                                 attribute_data.get(), attribute_size);
     52       for (start = 0; start < attribute_size; ++start) {
     53         if (IsTargetAttribute(attribute_data[start]))
     54           break;
     55       }
     56       for (end = start; end < attribute_size; ++end) {
     57         if (!IsTargetAttribute(attribute_data[end]))
     58           break;
     59       }
     60     }
     61     *target_start = start;
     62     *target_end = end;
     63   }
     64 }
     65 
     66 // Helper function for IMM32Manager::GetCompositionInfo() method, to get
     67 // underlines information of the current composition string.
     68 void GetCompositionUnderlines(HIMC imm_context,
     69                               int target_start,
     70                               int target_end,
     71                               ui::CompositionUnderlines* underlines) {
     72   int clause_size = ::ImmGetCompositionString(imm_context, GCS_COMPCLAUSE,
     73                                               NULL, 0);
     74   int clause_length = clause_size / sizeof(uint32);
     75   if (clause_length) {
     76     scoped_ptr<uint32[]> clause_data(new uint32[clause_length]);
     77     if (clause_data.get()) {
     78       ::ImmGetCompositionString(imm_context, GCS_COMPCLAUSE,
     79                                 clause_data.get(), clause_size);
     80       for (int i = 0; i < clause_length - 1; ++i) {
     81         ui::CompositionUnderline underline;
     82         underline.start_offset = clause_data[i];
     83         underline.end_offset = clause_data[i+1];
     84         underline.color = SK_ColorBLACK;
     85         underline.thick = false;
     86         underline.background_color = SK_ColorTRANSPARENT;
     87 
     88         // Use thick underline for the target clause.
     89         if (underline.start_offset >= static_cast<uint32>(target_start) &&
     90             underline.end_offset <= static_cast<uint32>(target_end)) {
     91           underline.thick = true;
     92         }
     93         underlines->push_back(underline);
     94       }
     95     }
     96   }
     97 }
     98 
     99 // Checks if a given primary language ID is a RTL language.
    100 bool IsRTLPrimaryLangID(LANGID lang) {
    101   switch (lang) {
    102     case LANG_ARABIC:
    103     case LANG_HEBREW:
    104     case LANG_PERSIAN:
    105     case LANG_SYRIAC:
    106     case LANG_UIGHUR:
    107     case LANG_URDU:
    108       return true;
    109     default:
    110       return false;
    111   }
    112 }
    113 
    114 }  // namespace
    115 
    116 namespace ui {
    117 
    118 IMM32Manager::IMM32Manager()
    119     : ime_status_(false),
    120       input_language_id_(LANG_USER_DEFAULT),
    121       is_composing_(false),
    122       system_caret_(false),
    123       caret_rect_(-1, -1, 0, 0),
    124       use_composition_window_(false) {
    125 }
    126 
    127 IMM32Manager::~IMM32Manager() {
    128 }
    129 
    130 bool IMM32Manager::SetInputLanguage() {
    131   // Retrieve the current keyboard layout from Windows and determine whether
    132   // or not the current input context has IMEs.
    133   // Also save its input language for language-specific operations required
    134   // while composing a text.
    135   HKL keyboard_layout = ::GetKeyboardLayout(0);
    136   input_language_id_ = reinterpret_cast<LANGID>(keyboard_layout);
    137 
    138   // Check TSF Input Processor first.
    139   // If the active profile is TSF INPUTPROCESSOR, this is IME.
    140   base::win::ScopedComPtr<ITfInputProcessorProfileMgr> prof_mgr;
    141   TF_INPUTPROCESSORPROFILE prof;
    142   if (SUCCEEDED(prof_mgr.CreateInstance(CLSID_TF_InputProcessorProfiles)) &&
    143       SUCCEEDED(prof_mgr->GetActiveProfile(GUID_TFCAT_TIP_KEYBOARD, &prof)) &&
    144       prof.hkl == NULL &&
    145       prof.dwProfileType == TF_PROFILETYPE_INPUTPROCESSOR) {
    146       ime_status_ = true;
    147   } else {
    148     // If the curent language is not using TSF, check IMM32 based IMEs.
    149     // As ImmIsIME always returns non-0 value on Vista+, use ImmGetIMEFileName
    150     // instead to check if this HKL has any associated IME file.
    151     ime_status_ = (ImmGetIMEFileName(keyboard_layout, NULL, 0) != 0);
    152   }
    153 
    154   return ime_status_;
    155 }
    156 
    157 void IMM32Manager::CreateImeWindow(HWND window_handle) {
    158   // When a user disables TSF (Text Service Framework) and CUAS (Cicero
    159   // Unaware Application Support), Chinese IMEs somehow ignore function calls
    160   // to ::ImmSetCandidateWindow(), i.e. they do not move their candidate
    161   // window to the position given as its parameters, and use the position
    162   // of the current system caret instead, i.e. it uses ::GetCaretPos() to
    163   // retrieve the position of their IME candidate window.
    164   // Therefore, we create a temporary system caret for Chinese IMEs and use
    165   // it during this input context.
    166   // Since some third-party Japanese IME also uses ::GetCaretPos() to determine
    167   // their window position, we also create a caret for Japanese IMEs.
    168   if (PRIMARYLANGID(input_language_id_) == LANG_CHINESE ||
    169       PRIMARYLANGID(input_language_id_) == LANG_JAPANESE) {
    170     if (!system_caret_) {
    171       if (::CreateCaret(window_handle, NULL, 1, 1)) {
    172         system_caret_ = true;
    173       }
    174     }
    175   }
    176   // Restore the positions of the IME windows.
    177   UpdateImeWindow(window_handle);
    178 }
    179 
    180 LRESULT IMM32Manager::SetImeWindowStyle(HWND window_handle, UINT message,
    181                                     WPARAM wparam, LPARAM lparam,
    182                                     BOOL* handled) {
    183   // To prevent the IMM (Input Method Manager) from displaying the IME
    184   // composition window, Update the styles of the IME windows and EXPLICITLY
    185   // call ::DefWindowProc() here.
    186   // NOTE(hbono): We can NEVER let WTL call ::DefWindowProc() when we update
    187   // the styles of IME windows because the 'lparam' variable is a local one
    188   // and all its updates disappear in returning from this function, i.e. WTL
    189   // does not call ::DefWindowProc() with our updated 'lparam' value but call
    190   // the function with its original value and over-writes our window styles.
    191   *handled = TRUE;
    192   lparam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
    193   return ::DefWindowProc(window_handle, message, wparam, lparam);
    194 }
    195 
    196 void IMM32Manager::DestroyImeWindow(HWND window_handle) {
    197   // Destroy the system caret if we have created for this IME input context.
    198   if (system_caret_) {
    199     ::DestroyCaret();
    200     system_caret_ = false;
    201   }
    202 }
    203 
    204 void IMM32Manager::MoveImeWindow(HWND window_handle, HIMC imm_context) {
    205   // Does nothing when the target window has no input focus. This is important
    206   // because the renderer may issue SelectionBoundsChanged event even when it
    207   // has no input focus. (e.g. the page update caused by incremental search.)
    208   // So this event should be ignored when the |window_handle| no longer has the
    209   // input focus.
    210   if (GetFocus() != window_handle)
    211     return;
    212 
    213   int x = caret_rect_.x();
    214   int y = caret_rect_.y();
    215 
    216   const int kCaretMargin = 1;
    217   if (!use_composition_window_ &&
    218       PRIMARYLANGID(input_language_id_) == LANG_CHINESE) {
    219     // As written in a comment in IMM32Manager::CreateImeWindow(),
    220     // Chinese IMEs ignore function calls to ::ImmSetCandidateWindow()
    221     // when a user disables TSF (Text Service Framework) and CUAS (Cicero
    222     // Unaware Application Support).
    223     // On the other hand, when a user enables TSF and CUAS, Chinese IMEs
    224     // ignore the position of the current system caret and uses the
    225     // parameters given to ::ImmSetCandidateWindow() with its 'dwStyle'
    226     // parameter CFS_CANDIDATEPOS.
    227     // Therefore, we do not only call ::ImmSetCandidateWindow() but also
    228     // set the positions of the temporary system caret if it exists.
    229     CANDIDATEFORM candidate_position = {0, CFS_CANDIDATEPOS, {x, y},
    230                                         {0, 0, 0, 0}};
    231     ::ImmSetCandidateWindow(imm_context, &candidate_position);
    232   }
    233   if (system_caret_) {
    234     switch (PRIMARYLANGID(input_language_id_)) {
    235       case LANG_JAPANESE:
    236         ::SetCaretPos(x, y + caret_rect_.height());
    237         break;
    238       default:
    239         ::SetCaretPos(x, y);
    240         break;
    241     }
    242   }
    243   if (use_composition_window_) {
    244     // Moves the composition text window.
    245     COMPOSITIONFORM cf = {CFS_POINT, {x, y}};
    246     ::ImmSetCompositionWindow(imm_context, &cf);
    247     // Don't need to set the position of candidate window.
    248     return;
    249   }
    250 
    251   if (PRIMARYLANGID(input_language_id_) == LANG_KOREAN) {
    252     // Chinese IMEs and Japanese IMEs require the upper-left corner of
    253     // the caret to move the position of their candidate windows.
    254     // On the other hand, Korean IMEs require the lower-left corner of the
    255     // caret to move their candidate windows.
    256     y += kCaretMargin;
    257   }
    258   // Japanese IMEs and Korean IMEs also use the rectangle given to
    259   // ::ImmSetCandidateWindow() with its 'dwStyle' parameter CFS_EXCLUDE
    260   // to move their candidate windows when a user disables TSF and CUAS.
    261   // Therefore, we also set this parameter here.
    262   CANDIDATEFORM exclude_rectangle = {0, CFS_EXCLUDE, {x, y},
    263       {x, y, x + caret_rect_.width(), y + caret_rect_.height()}};
    264   ::ImmSetCandidateWindow(imm_context, &exclude_rectangle);
    265 }
    266 
    267 void IMM32Manager::UpdateImeWindow(HWND window_handle) {
    268   // Just move the IME window attached to the given window.
    269   if (caret_rect_.x() >= 0 && caret_rect_.y() >= 0) {
    270     HIMC imm_context = ::ImmGetContext(window_handle);
    271     if (imm_context) {
    272       MoveImeWindow(window_handle, imm_context);
    273       ::ImmReleaseContext(window_handle, imm_context);
    274     }
    275   }
    276 }
    277 
    278 void IMM32Manager::CleanupComposition(HWND window_handle) {
    279   // Notify the IMM attached to the given window to complete the ongoing
    280   // composition, (this case happens when the given window is de-activated
    281   // while composing a text and re-activated), and reset the omposition status.
    282   if (is_composing_) {
    283     HIMC imm_context = ::ImmGetContext(window_handle);
    284     if (imm_context) {
    285       ::ImmNotifyIME(imm_context, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
    286       ::ImmReleaseContext(window_handle, imm_context);
    287     }
    288     ResetComposition(window_handle);
    289   }
    290 }
    291 
    292 void IMM32Manager::ResetComposition(HWND window_handle) {
    293   // Currently, just reset the composition status.
    294   is_composing_ = false;
    295 }
    296 
    297 void IMM32Manager::CompleteComposition(HWND window_handle, HIMC imm_context) {
    298   // We have to confirm there is an ongoing composition before completing it.
    299   // This is for preventing some IMEs from getting confused while completing an
    300   // ongoing composition even if they do not have any ongoing compositions.)
    301   if (is_composing_) {
    302     ::ImmNotifyIME(imm_context, NI_COMPOSITIONSTR, CPS_COMPLETE, 0);
    303     ResetComposition(window_handle);
    304   }
    305 }
    306 
    307 void IMM32Manager::GetCompositionInfo(HIMC imm_context, LPARAM lparam,
    308                                   CompositionText* composition) {
    309   // We only care about GCS_COMPATTR, GCS_COMPCLAUSE and GCS_CURSORPOS, and
    310   // convert them into underlines and selection range respectively.
    311   composition->underlines.clear();
    312 
    313   int length = static_cast<int>(composition->text.length());
    314 
    315   // Find out the range selected by the user.
    316   int target_start = length;
    317   int target_end = length;
    318   if (lparam & GCS_COMPATTR)
    319     GetCompositionTargetRange(imm_context, &target_start, &target_end);
    320 
    321   // Retrieve the selection range information. If CS_NOMOVECARET is specified,
    322   // that means the cursor should not be moved, then we just place the caret at
    323   // the beginning of the composition string. Otherwise we should honour the
    324   // GCS_CURSORPOS value if it's available.
    325   // TODO(suzhe): due to a bug of webkit, we currently can't use selection range
    326   // with composition string. See: https://bugs.webkit.org/show_bug.cgi?id=40805
    327   if (!(lparam & CS_NOMOVECARET) && (lparam & GCS_CURSORPOS)) {
    328     // IMM32 does not support non-zero-width selection in a composition. So
    329     // always use the caret position as selection range.
    330     int cursor = ::ImmGetCompositionString(imm_context, GCS_CURSORPOS, NULL, 0);
    331     composition->selection = gfx::Range(cursor);
    332   } else {
    333     composition->selection = gfx::Range(0);
    334   }
    335 
    336   // Retrieve the clause segmentations and convert them to underlines.
    337   if (lparam & GCS_COMPCLAUSE) {
    338     GetCompositionUnderlines(imm_context, target_start, target_end,
    339                              &composition->underlines);
    340   }
    341 
    342   // Set default underlines in case there is no clause information.
    343   if (!composition->underlines.size()) {
    344     CompositionUnderline underline;
    345     underline.color = SK_ColorBLACK;
    346     underline.background_color = SK_ColorTRANSPARENT;
    347     if (target_start > 0) {
    348       underline.start_offset = 0U;
    349       underline.end_offset = static_cast<uint32>(target_start);
    350       underline.thick = false;
    351       composition->underlines.push_back(underline);
    352     }
    353     if (target_end > target_start) {
    354       underline.start_offset = static_cast<uint32>(target_start);
    355       underline.end_offset = static_cast<uint32>(target_end);
    356       underline.thick = true;
    357       composition->underlines.push_back(underline);
    358     }
    359     if (target_end < length) {
    360       underline.start_offset = static_cast<uint32>(target_end);
    361       underline.end_offset = static_cast<uint32>(length);
    362       underline.thick = false;
    363       composition->underlines.push_back(underline);
    364     }
    365   }
    366 }
    367 
    368 bool IMM32Manager::GetString(HIMC imm_context,
    369                          WPARAM lparam,
    370                          int type,
    371                          base::string16* result) {
    372   if (!(lparam & type))
    373     return false;
    374   LONG string_size = ::ImmGetCompositionString(imm_context, type, NULL, 0);
    375   if (string_size <= 0)
    376     return false;
    377   DCHECK_EQ(0u, string_size % sizeof(wchar_t));
    378   ::ImmGetCompositionString(imm_context, type,
    379       WriteInto(result, (string_size / sizeof(wchar_t)) + 1), string_size);
    380   return true;
    381 }
    382 
    383 bool IMM32Manager::GetResult(
    384     HWND window_handle, LPARAM lparam, base::string16* result) {
    385   bool ret = false;
    386   HIMC imm_context = ::ImmGetContext(window_handle);
    387   if (imm_context) {
    388     ret = GetString(imm_context, lparam, GCS_RESULTSTR, result);
    389     ::ImmReleaseContext(window_handle, imm_context);
    390   }
    391   return ret;
    392 }
    393 
    394 bool IMM32Manager::GetComposition(HWND window_handle, LPARAM lparam,
    395                               CompositionText* composition) {
    396   bool ret = false;
    397   HIMC imm_context = ::ImmGetContext(window_handle);
    398   if (imm_context) {
    399     // Copy the composition string to the CompositionText object.
    400     ret = GetString(imm_context, lparam, GCS_COMPSTR, &composition->text);
    401 
    402     if (ret) {
    403       // This is a dirty workaround for facebook. Facebook deletes the
    404       // placeholder character (U+3000) used by Traditional-Chinese IMEs at the
    405       // beginning of composition text. This prevents WebKit from replacing this
    406       // placeholder character with a Traditional-Chinese character, i.e. we
    407       // cannot input any characters in a comment box of facebook with
    408       // Traditional-Chinese IMEs. As a workaround, we replace U+3000 at the
    409       // beginning of composition text with U+FF3F, a placeholder character used
    410       // by Japanese IMEs.
    411       if (input_language_id_ == MAKELANGID(LANG_CHINESE,
    412                                            SUBLANG_CHINESE_TRADITIONAL) &&
    413           composition->text[0] == 0x3000) {
    414         composition->text[0] = 0xFF3F;
    415       }
    416 
    417       // Retrieve the composition underlines and selection range information.
    418       GetCompositionInfo(imm_context, lparam, composition);
    419 
    420       // Mark that there is an ongoing composition.
    421       is_composing_ = true;
    422     }
    423 
    424     ::ImmReleaseContext(window_handle, imm_context);
    425   }
    426   return ret;
    427 }
    428 
    429 void IMM32Manager::DisableIME(HWND window_handle) {
    430   // A renderer process have moved its input focus to a password input
    431   // when there is an ongoing composition, e.g. a user has clicked a
    432   // mouse button and selected a password input while composing a text.
    433   // For this case, we have to complete the ongoing composition and
    434   // clean up the resources attached to this object BEFORE DISABLING THE IME.
    435   CleanupComposition(window_handle);
    436   ::ImmAssociateContextEx(window_handle, NULL, 0);
    437 }
    438 
    439 void IMM32Manager::CancelIME(HWND window_handle) {
    440   if (is_composing_) {
    441     HIMC imm_context = ::ImmGetContext(window_handle);
    442     if (imm_context) {
    443       ::ImmNotifyIME(imm_context, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
    444       ::ImmReleaseContext(window_handle, imm_context);
    445     }
    446     ResetComposition(window_handle);
    447   }
    448 }
    449 
    450 void IMM32Manager::EnableIME(HWND window_handle) {
    451   // Load the default IME context.
    452   // NOTE(hbono)
    453   //   IMM ignores this call if the IME context is loaded. Therefore, we do
    454   //   not have to check whether or not the IME context is loaded.
    455   ::ImmAssociateContextEx(window_handle, NULL, IACE_DEFAULT);
    456 }
    457 
    458 void IMM32Manager::UpdateCaretRect(HWND window_handle,
    459                                const gfx::Rect& caret_rect) {
    460   // Save the caret position, and Update the position of the IME window.
    461   // This update is used for moving an IME window when a renderer process
    462   // resize/moves the input caret.
    463   if (caret_rect_ != caret_rect) {
    464     caret_rect_ = caret_rect;
    465     // Move the IME windows.
    466     HIMC imm_context = ::ImmGetContext(window_handle);
    467     if (imm_context) {
    468       MoveImeWindow(window_handle, imm_context);
    469       ::ImmReleaseContext(window_handle, imm_context);
    470     }
    471   }
    472 }
    473 
    474 void IMM32Manager::SetUseCompositionWindow(bool use_composition_window) {
    475   use_composition_window_ = use_composition_window;
    476 }
    477 
    478 std::string IMM32Manager::GetInputLanguageName() const {
    479   const LCID locale_id = MAKELCID(input_language_id_, SORT_DEFAULT);
    480   // max size for LOCALE_SISO639LANGNAME and LOCALE_SISO3166CTRYNAME is 9.
    481   wchar_t buffer[9];
    482 
    483   // Get language id.
    484   int length = ::GetLocaleInfo(locale_id, LOCALE_SISO639LANGNAME, &buffer[0],
    485                                arraysize(buffer));
    486   if (length <= 1)
    487     return std::string();
    488 
    489   std::string language;
    490   base::WideToUTF8(buffer, length - 1, &language);
    491   if (SUBLANGID(input_language_id_) == SUBLANG_NEUTRAL)
    492     return language;
    493 
    494   // Get region id.
    495   length = ::GetLocaleInfo(locale_id, LOCALE_SISO3166CTRYNAME, &buffer[0],
    496                            arraysize(buffer));
    497   if (length <= 1)
    498     return language;
    499 
    500   std::string region;
    501   base::WideToUTF8(buffer, length - 1, &region);
    502   return language.append(1, '-').append(region);
    503 }
    504 
    505 void IMM32Manager::SetTextInputMode(HWND window_handle,
    506                                     TextInputMode input_mode) {
    507   if (input_mode == ui::TEXT_INPUT_MODE_DEFAULT)
    508     return;
    509 
    510   const HIMC imm_context = ::ImmGetContext(window_handle);
    511   if (!imm_context)
    512     return;
    513 
    514   DWORD conversion_mode = 0;
    515   DWORD sentence_mode = 0;
    516   if (::ImmGetConversionStatus(imm_context, &conversion_mode, &sentence_mode)
    517       == FALSE) {
    518     return;
    519   }
    520 
    521   BOOL open = FALSE;
    522   ConvertInputModeToImmFlags(input_mode, conversion_mode, &open,
    523                              &conversion_mode),
    524 
    525   ::ImmSetOpenStatus(imm_context, open);
    526   if (open)
    527     ::ImmSetConversionStatus(imm_context, conversion_mode, sentence_mode);
    528   ::ImmReleaseContext(window_handle, imm_context);
    529 }
    530 
    531 // static
    532 bool IMM32Manager::IsRTLKeyboardLayoutInstalled() {
    533   static enum {
    534     RTL_KEYBOARD_LAYOUT_NOT_INITIALIZED,
    535     RTL_KEYBOARD_LAYOUT_INSTALLED,
    536     RTL_KEYBOARD_LAYOUT_NOT_INSTALLED,
    537     RTL_KEYBOARD_LAYOUT_ERROR,
    538   } layout = RTL_KEYBOARD_LAYOUT_NOT_INITIALIZED;
    539 
    540   // Cache the result value.
    541   if (layout != RTL_KEYBOARD_LAYOUT_NOT_INITIALIZED)
    542     return layout == RTL_KEYBOARD_LAYOUT_INSTALLED;
    543 
    544   // Retrieve the number of layouts installed in this system.
    545   int size = GetKeyboardLayoutList(0, NULL);
    546   if (size <= 0) {
    547     layout = RTL_KEYBOARD_LAYOUT_ERROR;
    548     return false;
    549   }
    550 
    551   // Retrieve the keyboard layouts in an array and check if there is an RTL
    552   // layout in it.
    553   scoped_ptr<HKL[]> layouts(new HKL[size]);
    554   ::GetKeyboardLayoutList(size, layouts.get());
    555   for (int i = 0; i < size; ++i) {
    556     if (IsRTLPrimaryLangID(PRIMARYLANGID(layouts[i]))) {
    557       layout = RTL_KEYBOARD_LAYOUT_INSTALLED;
    558       return true;
    559     }
    560   }
    561 
    562   layout = RTL_KEYBOARD_LAYOUT_NOT_INSTALLED;
    563   return false;
    564 }
    565 
    566 bool IMM32Manager::IsCtrlShiftPressed(base::i18n::TextDirection* direction) {
    567   uint8_t keystate[256];
    568   if (!::GetKeyboardState(&keystate[0]))
    569     return false;
    570 
    571   // To check if a user is pressing only a control key and a right-shift key
    572   // (or a left-shift key), we use the steps below:
    573   // 1. Check if a user is pressing a control key and a right-shift key (or
    574   //    a left-shift key).
    575   // 2. If the condition 1 is true, we should check if there are any other
    576   //    keys pressed at the same time.
    577   //    To ignore the keys checked in 1, we set their status to 0 before
    578   //    checking the key status.
    579   const int kKeyDownMask = 0x80;
    580   if ((keystate[VK_CONTROL] & kKeyDownMask) == 0)
    581     return false;
    582 
    583   if (keystate[VK_RSHIFT] & kKeyDownMask) {
    584     keystate[VK_RSHIFT] = 0;
    585     *direction = base::i18n::RIGHT_TO_LEFT;
    586   } else if (keystate[VK_LSHIFT] & kKeyDownMask) {
    587     keystate[VK_LSHIFT] = 0;
    588     *direction = base::i18n::LEFT_TO_RIGHT;
    589   } else {
    590     return false;
    591   }
    592 
    593   // Scan the key status to find pressed keys. We should abandon changing the
    594   // text direction when there are other pressed keys.
    595   // This code is executed only when a user is pressing a control key and a
    596   // right-shift key (or a left-shift key), i.e. we should ignore the status of
    597   // the keys: VK_SHIFT, VK_CONTROL, VK_RCONTROL, and VK_LCONTROL.
    598   // So, we reset their status to 0 and ignore them.
    599   keystate[VK_SHIFT] = 0;
    600   keystate[VK_CONTROL] = 0;
    601   keystate[VK_RCONTROL] = 0;
    602   keystate[VK_LCONTROL] = 0;
    603   // Oddly, pressing F10 in another application seemingly breaks all subsequent
    604   // calls to GetKeyboardState regarding the state of the F22 key. Perhaps this
    605   // defect is limited to my keyboard driver, but ignoring F22 should be okay.
    606   keystate[VK_F22] = 0;
    607   for (int i = 0; i <= VK_PACKET; ++i) {
    608     if (keystate[i] & kKeyDownMask)
    609       return false;
    610   }
    611   return true;
    612 }
    613 
    614 void IMM32Manager::ConvertInputModeToImmFlags(TextInputMode input_mode,
    615                                               DWORD initial_conversion_mode,
    616                                               BOOL* open,
    617                                               DWORD* new_conversion_mode) {
    618   *open = TRUE;
    619   *new_conversion_mode = initial_conversion_mode;
    620   switch (input_mode) {
    621     case ui::TEXT_INPUT_MODE_FULL_WIDTH_LATIN:
    622       *new_conversion_mode |= IME_CMODE_FULLSHAPE;
    623       *new_conversion_mode &= ~(IME_CMODE_NATIVE
    624                               | IME_CMODE_KATAKANA);
    625       break;
    626     case ui::TEXT_INPUT_MODE_KANA:
    627       *new_conversion_mode |= (IME_CMODE_NATIVE
    628                              | IME_CMODE_FULLSHAPE);
    629       *new_conversion_mode &= ~IME_CMODE_KATAKANA;
    630       break;
    631     case ui::TEXT_INPUT_MODE_KATAKANA:
    632       *new_conversion_mode |= (IME_CMODE_NATIVE
    633                              | IME_CMODE_KATAKANA
    634                              | IME_CMODE_FULLSHAPE);
    635       break;
    636     default:
    637       *open = FALSE;
    638       break;
    639   }
    640 }
    641 
    642 }  // namespace ui
    643