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.
5 #include "ui/base/ime/win/imm32_manager.h"
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"
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")
23 // Following code requires wchar_t to be same as char16. It should always be
25 static_assert(sizeof(wchar_t) == sizeof(base::char16
),
26 "wchar_t should be the same size as char16");
28 ///////////////////////////////////////////////////////////////////////////////
33 // Determines whether or not the given attribute represents a target
34 // (a.k.a. a selection).
35 bool IsTargetAttribute(char attribute
) {
36 return (attribute
== ATTR_TARGET_CONVERTED
||
37 attribute
== ATTR_TARGET_NOTCONVERTED
);
40 // Helper function for IMM32Manager::GetCompositionInfo() method, to get the
41 // target range that's selected by the user in the current composition string.
42 void GetCompositionTargetRange(HIMC imm_context
, int* target_start
,
44 int attribute_size
= ::ImmGetCompositionString(imm_context
, GCS_COMPATTR
,
46 if (attribute_size
> 0) {
49 scoped_ptr
<char[]> attribute_data(new char[attribute_size
]);
50 if (attribute_data
.get()) {
51 ::ImmGetCompositionString(imm_context
, GCS_COMPATTR
,
52 attribute_data
.get(), attribute_size
);
53 for (start
= 0; start
< attribute_size
; ++start
) {
54 if (IsTargetAttribute(attribute_data
[start
]))
57 for (end
= start
; end
< attribute_size
; ++end
) {
58 if (!IsTargetAttribute(attribute_data
[end
]))
62 *target_start
= start
;
67 // Helper function for IMM32Manager::GetCompositionInfo() method, to get
68 // underlines information of the current composition string.
69 void GetCompositionUnderlines(HIMC imm_context
,
72 ui::CompositionUnderlines
* underlines
) {
73 int clause_size
= ::ImmGetCompositionString(imm_context
, GCS_COMPCLAUSE
,
75 int clause_length
= clause_size
/ sizeof(uint32
);
77 scoped_ptr
<uint32
[]> clause_data(new uint32
[clause_length
]);
78 if (clause_data
.get()) {
79 ::ImmGetCompositionString(imm_context
, GCS_COMPCLAUSE
,
80 clause_data
.get(), clause_size
);
81 for (int i
= 0; i
< clause_length
- 1; ++i
) {
82 ui::CompositionUnderline underline
;
83 underline
.start_offset
= clause_data
[i
];
84 underline
.end_offset
= clause_data
[i
+1];
85 underline
.color
= SK_ColorBLACK
;
86 underline
.thick
= false;
87 underline
.background_color
= SK_ColorTRANSPARENT
;
89 // Use thick underline for the target clause.
90 if (underline
.start_offset
>= static_cast<uint32
>(target_start
) &&
91 underline
.end_offset
<= static_cast<uint32
>(target_end
)) {
92 underline
.thick
= true;
94 underlines
->push_back(underline
);
100 // Checks if a given primary language ID is a RTL language.
101 bool IsRTLPrimaryLangID(LANGID lang
) {
119 IMM32Manager::IMM32Manager()
120 : ime_status_(false),
121 input_language_id_(LANG_USER_DEFAULT
),
122 is_composing_(false),
123 system_caret_(false),
124 caret_rect_(-1, -1, 0, 0),
125 use_composition_window_(false) {
128 IMM32Manager::~IMM32Manager() {
131 bool IMM32Manager::SetInputLanguage() {
132 // Retrieve the current keyboard layout from Windows and determine whether
133 // or not the current input context has IMEs.
134 // Also save its input language for language-specific operations required
135 // while composing a text.
136 HKL keyboard_layout
= ::GetKeyboardLayout(0);
137 input_language_id_
= reinterpret_cast<LANGID
>(keyboard_layout
);
139 // Check TSF Input Processor first.
140 // If the active profile is TSF INPUTPROCESSOR, this is IME.
141 base::win::ScopedComPtr
<ITfInputProcessorProfileMgr
> prof_mgr
;
142 TF_INPUTPROCESSORPROFILE prof
;
143 if (SUCCEEDED(prof_mgr
.CreateInstance(CLSID_TF_InputProcessorProfiles
)) &&
144 SUCCEEDED(prof_mgr
->GetActiveProfile(GUID_TFCAT_TIP_KEYBOARD
, &prof
)) &&
146 prof
.dwProfileType
== TF_PROFILETYPE_INPUTPROCESSOR
) {
149 // If the curent language is not using TSF, check IMM32 based IMEs.
150 // As ImmIsIME always returns non-0 value on Vista+, use ImmGetIMEFileName
151 // instead to check if this HKL has any associated IME file.
152 ime_status_
= (ImmGetIMEFileName(keyboard_layout
, NULL
, 0) != 0);
158 void IMM32Manager::CreateImeWindow(HWND window_handle
) {
159 // When a user disables TSF (Text Service Framework) and CUAS (Cicero
160 // Unaware Application Support), Chinese IMEs somehow ignore function calls
161 // to ::ImmSetCandidateWindow(), i.e. they do not move their candidate
162 // window to the position given as its parameters, and use the position
163 // of the current system caret instead, i.e. it uses ::GetCaretPos() to
164 // retrieve the position of their IME candidate window.
165 // Therefore, we create a temporary system caret for Chinese IMEs and use
166 // it during this input context.
167 // Since some third-party Japanese IME also uses ::GetCaretPos() to determine
168 // their window position, we also create a caret for Japanese IMEs.
169 if (PRIMARYLANGID(input_language_id_
) == LANG_CHINESE
||
170 PRIMARYLANGID(input_language_id_
) == LANG_JAPANESE
) {
171 if (!system_caret_
) {
172 if (::CreateCaret(window_handle
, NULL
, 1, 1)) {
173 system_caret_
= true;
177 // Restore the positions of the IME windows.
178 UpdateImeWindow(window_handle
);
181 LRESULT
IMM32Manager::SetImeWindowStyle(HWND window_handle
, UINT message
,
182 WPARAM wparam
, LPARAM lparam
,
184 // To prevent the IMM (Input Method Manager) from displaying the IME
185 // composition window, Update the styles of the IME windows and EXPLICITLY
186 // call ::DefWindowProc() here.
187 // NOTE(hbono): We can NEVER let WTL call ::DefWindowProc() when we update
188 // the styles of IME windows because the 'lparam' variable is a local one
189 // and all its updates disappear in returning from this function, i.e. WTL
190 // does not call ::DefWindowProc() with our updated 'lparam' value but call
191 // the function with its original value and over-writes our window styles.
193 lparam
&= ~ISC_SHOWUICOMPOSITIONWINDOW
;
194 return ::DefWindowProc(window_handle
, message
, wparam
, lparam
);
197 void IMM32Manager::DestroyImeWindow(HWND window_handle
) {
198 // Destroy the system caret if we have created for this IME input context.
201 system_caret_
= false;
205 void IMM32Manager::MoveImeWindow(HWND window_handle
, HIMC imm_context
) {
206 // Does nothing when the target window has no input focus. This is important
207 // because the renderer may issue SelectionBoundsChanged event even when it
208 // has no input focus. (e.g. the page update caused by incremental search.)
209 // So this event should be ignored when the |window_handle| no longer has the
211 if (GetFocus() != window_handle
)
214 int x
= caret_rect_
.x();
215 int y
= caret_rect_
.y();
217 const int kCaretMargin
= 1;
218 if (!use_composition_window_
&&
219 PRIMARYLANGID(input_language_id_
) == LANG_CHINESE
) {
220 // As written in a comment in IMM32Manager::CreateImeWindow(),
221 // Chinese IMEs ignore function calls to ::ImmSetCandidateWindow()
222 // when a user disables TSF (Text Service Framework) and CUAS (Cicero
223 // Unaware Application Support).
224 // On the other hand, when a user enables TSF and CUAS, Chinese IMEs
225 // ignore the position of the current system caret and uses the
226 // parameters given to ::ImmSetCandidateWindow() with its 'dwStyle'
227 // parameter CFS_CANDIDATEPOS.
228 // Therefore, we do not only call ::ImmSetCandidateWindow() but also
229 // set the positions of the temporary system caret if it exists.
230 CANDIDATEFORM candidate_position
= {0, CFS_CANDIDATEPOS
, {x
, y
},
232 ::ImmSetCandidateWindow(imm_context
, &candidate_position
);
235 switch (PRIMARYLANGID(input_language_id_
)) {
237 ::SetCaretPos(x
, y
+ caret_rect_
.height());
244 if (use_composition_window_
) {
245 // Moves the composition text window.
246 COMPOSITIONFORM cf
= {CFS_POINT
, {x
, y
}};
247 ::ImmSetCompositionWindow(imm_context
, &cf
);
248 // Don't need to set the position of candidate window.
252 if (PRIMARYLANGID(input_language_id_
) == LANG_KOREAN
) {
253 // Chinese IMEs and Japanese IMEs require the upper-left corner of
254 // the caret to move the position of their candidate windows.
255 // On the other hand, Korean IMEs require the lower-left corner of the
256 // caret to move their candidate windows.
259 // Japanese IMEs and Korean IMEs also use the rectangle given to
260 // ::ImmSetCandidateWindow() with its 'dwStyle' parameter CFS_EXCLUDE
261 // to move their candidate windows when a user disables TSF and CUAS.
262 // Therefore, we also set this parameter here.
263 CANDIDATEFORM exclude_rectangle
= {0, CFS_EXCLUDE
, {x
, y
},
264 {x
, y
, x
+ caret_rect_
.width(), y
+ caret_rect_
.height()}};
265 ::ImmSetCandidateWindow(imm_context
, &exclude_rectangle
);
268 void IMM32Manager::UpdateImeWindow(HWND window_handle
) {
269 // Just move the IME window attached to the given window.
270 if (caret_rect_
.x() >= 0 && caret_rect_
.y() >= 0) {
271 HIMC imm_context
= ::ImmGetContext(window_handle
);
273 MoveImeWindow(window_handle
, imm_context
);
274 ::ImmReleaseContext(window_handle
, imm_context
);
279 void IMM32Manager::CleanupComposition(HWND window_handle
) {
280 // Notify the IMM attached to the given window to complete the ongoing
281 // composition, (this case happens when the given window is de-activated
282 // while composing a text and re-activated), and reset the omposition status.
284 HIMC imm_context
= ::ImmGetContext(window_handle
);
286 ::ImmNotifyIME(imm_context
, NI_COMPOSITIONSTR
, CPS_COMPLETE
, 0);
287 ::ImmReleaseContext(window_handle
, imm_context
);
289 ResetComposition(window_handle
);
293 void IMM32Manager::ResetComposition(HWND window_handle
) {
294 // Currently, just reset the composition status.
295 is_composing_
= false;
298 void IMM32Manager::CompleteComposition(HWND window_handle
, HIMC imm_context
) {
299 // We have to confirm there is an ongoing composition before completing it.
300 // This is for preventing some IMEs from getting confused while completing an
301 // ongoing composition even if they do not have any ongoing compositions.)
303 ::ImmNotifyIME(imm_context
, NI_COMPOSITIONSTR
, CPS_COMPLETE
, 0);
304 ResetComposition(window_handle
);
308 void IMM32Manager::GetCompositionInfo(HIMC imm_context
, LPARAM lparam
,
309 CompositionText
* composition
) {
310 // We only care about GCS_COMPATTR, GCS_COMPCLAUSE and GCS_CURSORPOS, and
311 // convert them into underlines and selection range respectively.
312 composition
->underlines
.clear();
314 int length
= static_cast<int>(composition
->text
.length());
316 // Find out the range selected by the user.
317 int target_start
= length
;
318 int target_end
= length
;
319 if (lparam
& GCS_COMPATTR
)
320 GetCompositionTargetRange(imm_context
, &target_start
, &target_end
);
322 // Retrieve the selection range information. If CS_NOMOVECARET is specified,
323 // that means the cursor should not be moved, then we just place the caret at
324 // the beginning of the composition string. Otherwise we should honour the
325 // GCS_CURSORPOS value if it's available.
326 // TODO(suzhe): due to a bug of webkit, we currently can't use selection range
327 // with composition string. See: https://bugs.webkit.org/show_bug.cgi?id=40805
328 if (!(lparam
& CS_NOMOVECARET
) && (lparam
& GCS_CURSORPOS
)) {
329 // IMM32 does not support non-zero-width selection in a composition. So
330 // always use the caret position as selection range.
331 int cursor
= ::ImmGetCompositionString(imm_context
, GCS_CURSORPOS
, NULL
, 0);
332 composition
->selection
= gfx::Range(cursor
);
334 composition
->selection
= gfx::Range(0);
337 // Retrieve the clause segmentations and convert them to underlines.
338 if (lparam
& GCS_COMPCLAUSE
) {
339 GetCompositionUnderlines(imm_context
, target_start
, target_end
,
340 &composition
->underlines
);
343 // Set default underlines in case there is no clause information.
344 if (!composition
->underlines
.size()) {
345 CompositionUnderline underline
;
346 underline
.color
= SK_ColorBLACK
;
347 underline
.background_color
= SK_ColorTRANSPARENT
;
348 if (target_start
> 0) {
349 underline
.start_offset
= 0U;
350 underline
.end_offset
= static_cast<uint32
>(target_start
);
351 underline
.thick
= false;
352 composition
->underlines
.push_back(underline
);
354 if (target_end
> target_start
) {
355 underline
.start_offset
= static_cast<uint32
>(target_start
);
356 underline
.end_offset
= static_cast<uint32
>(target_end
);
357 underline
.thick
= true;
358 composition
->underlines
.push_back(underline
);
360 if (target_end
< length
) {
361 underline
.start_offset
= static_cast<uint32
>(target_end
);
362 underline
.end_offset
= static_cast<uint32
>(length
);
363 underline
.thick
= false;
364 composition
->underlines
.push_back(underline
);
369 bool IMM32Manager::GetString(HIMC imm_context
,
372 base::string16
* result
) {
373 if (!(lparam
& type
))
375 LONG string_size
= ::ImmGetCompositionString(imm_context
, type
, NULL
, 0);
376 if (string_size
<= 0)
378 DCHECK_EQ(0u, string_size
% sizeof(wchar_t));
379 ::ImmGetCompositionString(imm_context
, type
,
380 WriteInto(result
, (string_size
/ sizeof(wchar_t)) + 1), string_size
);
384 bool IMM32Manager::GetResult(
385 HWND window_handle
, LPARAM lparam
, base::string16
* result
) {
387 HIMC imm_context
= ::ImmGetContext(window_handle
);
389 ret
= GetString(imm_context
, lparam
, GCS_RESULTSTR
, result
);
390 ::ImmReleaseContext(window_handle
, imm_context
);
395 bool IMM32Manager::GetComposition(HWND window_handle
, LPARAM lparam
,
396 CompositionText
* composition
) {
398 HIMC imm_context
= ::ImmGetContext(window_handle
);
400 // Copy the composition string to the CompositionText object.
401 ret
= GetString(imm_context
, lparam
, GCS_COMPSTR
, &composition
->text
);
404 // This is a dirty workaround for facebook. Facebook deletes the
405 // placeholder character (U+3000) used by Traditional-Chinese IMEs at the
406 // beginning of composition text. This prevents WebKit from replacing this
407 // placeholder character with a Traditional-Chinese character, i.e. we
408 // cannot input any characters in a comment box of facebook with
409 // Traditional-Chinese IMEs. As a workaround, we replace U+3000 at the
410 // beginning of composition text with U+FF3F, a placeholder character used
412 if (input_language_id_
== MAKELANGID(LANG_CHINESE
,
413 SUBLANG_CHINESE_TRADITIONAL
) &&
414 composition
->text
[0] == 0x3000) {
415 composition
->text
[0] = 0xFF3F;
418 // Retrieve the composition underlines and selection range information.
419 GetCompositionInfo(imm_context
, lparam
, composition
);
421 // Mark that there is an ongoing composition.
422 is_composing_
= true;
425 ::ImmReleaseContext(window_handle
, imm_context
);
430 void IMM32Manager::DisableIME(HWND window_handle
) {
431 // A renderer process have moved its input focus to a password input
432 // when there is an ongoing composition, e.g. a user has clicked a
433 // mouse button and selected a password input while composing a text.
434 // For this case, we have to complete the ongoing composition and
435 // clean up the resources attached to this object BEFORE DISABLING THE IME.
436 CleanupComposition(window_handle
);
437 ::ImmAssociateContextEx(window_handle
, NULL
, 0);
440 void IMM32Manager::CancelIME(HWND window_handle
) {
442 HIMC imm_context
= ::ImmGetContext(window_handle
);
444 ::ImmNotifyIME(imm_context
, NI_COMPOSITIONSTR
, CPS_CANCEL
, 0);
445 ::ImmReleaseContext(window_handle
, imm_context
);
447 ResetComposition(window_handle
);
451 void IMM32Manager::EnableIME(HWND window_handle
) {
452 // Load the default IME context.
454 // IMM ignores this call if the IME context is loaded. Therefore, we do
455 // not have to check whether or not the IME context is loaded.
456 ::ImmAssociateContextEx(window_handle
, NULL
, IACE_DEFAULT
);
459 void IMM32Manager::UpdateCaretRect(HWND window_handle
,
460 const gfx::Rect
& caret_rect
) {
461 // Save the caret position, and Update the position of the IME window.
462 // This update is used for moving an IME window when a renderer process
463 // resize/moves the input caret.
464 if (caret_rect_
!= caret_rect
) {
465 caret_rect_
= caret_rect
;
466 // Move the IME windows.
467 HIMC imm_context
= ::ImmGetContext(window_handle
);
469 MoveImeWindow(window_handle
, imm_context
);
470 ::ImmReleaseContext(window_handle
, imm_context
);
475 void IMM32Manager::SetUseCompositionWindow(bool use_composition_window
) {
476 use_composition_window_
= use_composition_window
;
479 std::string
IMM32Manager::GetInputLanguageName() const {
480 const LCID locale_id
= MAKELCID(input_language_id_
, SORT_DEFAULT
);
481 // max size for LOCALE_SISO639LANGNAME and LOCALE_SISO3166CTRYNAME is 9.
485 int length
= ::GetLocaleInfo(locale_id
, LOCALE_SISO639LANGNAME
, &buffer
[0],
488 return std::string();
490 std::string language
;
491 base::WideToUTF8(buffer
, length
- 1, &language
);
492 if (SUBLANGID(input_language_id_
) == SUBLANG_NEUTRAL
)
496 length
= ::GetLocaleInfo(locale_id
, LOCALE_SISO3166CTRYNAME
, &buffer
[0],
502 base::WideToUTF8(buffer
, length
- 1, ®ion
);
503 return language
.append(1, '-').append(region
);
506 void IMM32Manager::SetTextInputMode(HWND window_handle
,
507 TextInputMode input_mode
) {
508 if (input_mode
== ui::TEXT_INPUT_MODE_DEFAULT
)
511 const HIMC imm_context
= ::ImmGetContext(window_handle
);
515 DWORD conversion_mode
= 0;
516 DWORD sentence_mode
= 0;
517 if (::ImmGetConversionStatus(imm_context
, &conversion_mode
, &sentence_mode
)
523 ConvertInputModeToImmFlags(input_mode
, conversion_mode
, &open
,
526 ::ImmSetOpenStatus(imm_context
, open
);
528 ::ImmSetConversionStatus(imm_context
, conversion_mode
, sentence_mode
);
529 ::ImmReleaseContext(window_handle
, imm_context
);
533 bool IMM32Manager::IsRTLKeyboardLayoutInstalled() {
535 RTL_KEYBOARD_LAYOUT_NOT_INITIALIZED
,
536 RTL_KEYBOARD_LAYOUT_INSTALLED
,
537 RTL_KEYBOARD_LAYOUT_NOT_INSTALLED
,
538 RTL_KEYBOARD_LAYOUT_ERROR
,
539 } layout
= RTL_KEYBOARD_LAYOUT_NOT_INITIALIZED
;
541 // Cache the result value.
542 if (layout
!= RTL_KEYBOARD_LAYOUT_NOT_INITIALIZED
)
543 return layout
== RTL_KEYBOARD_LAYOUT_INSTALLED
;
545 // Retrieve the number of layouts installed in this system.
546 int size
= GetKeyboardLayoutList(0, NULL
);
548 layout
= RTL_KEYBOARD_LAYOUT_ERROR
;
552 // Retrieve the keyboard layouts in an array and check if there is an RTL
554 scoped_ptr
<HKL
[]> layouts(new HKL
[size
]);
555 ::GetKeyboardLayoutList(size
, layouts
.get());
556 for (int i
= 0; i
< size
; ++i
) {
557 if (IsRTLPrimaryLangID(PRIMARYLANGID(layouts
[i
]))) {
558 layout
= RTL_KEYBOARD_LAYOUT_INSTALLED
;
563 layout
= RTL_KEYBOARD_LAYOUT_NOT_INSTALLED
;
567 bool IMM32Manager::IsCtrlShiftPressed(base::i18n::TextDirection
* direction
) {
568 uint8_t keystate
[256];
569 if (!::GetKeyboardState(&keystate
[0]))
572 // To check if a user is pressing only a control key and a right-shift key
573 // (or a left-shift key), we use the steps below:
574 // 1. Check if a user is pressing a control key and a right-shift key (or
575 // a left-shift key).
576 // 2. If the condition 1 is true, we should check if there are any other
577 // keys pressed at the same time.
578 // To ignore the keys checked in 1, we set their status to 0 before
579 // checking the key status.
580 const int kKeyDownMask
= 0x80;
581 if ((keystate
[VK_CONTROL
] & kKeyDownMask
) == 0)
584 if (keystate
[VK_RSHIFT
] & kKeyDownMask
) {
585 keystate
[VK_RSHIFT
] = 0;
586 *direction
= base::i18n::RIGHT_TO_LEFT
;
587 } else if (keystate
[VK_LSHIFT
] & kKeyDownMask
) {
588 keystate
[VK_LSHIFT
] = 0;
589 *direction
= base::i18n::LEFT_TO_RIGHT
;
594 // Scan the key status to find pressed keys. We should abandon changing the
595 // text direction when there are other pressed keys.
596 // This code is executed only when a user is pressing a control key and a
597 // right-shift key (or a left-shift key), i.e. we should ignore the status of
598 // the keys: VK_SHIFT, VK_CONTROL, VK_RCONTROL, and VK_LCONTROL.
599 // So, we reset their status to 0 and ignore them.
600 keystate
[VK_SHIFT
] = 0;
601 keystate
[VK_CONTROL
] = 0;
602 keystate
[VK_RCONTROL
] = 0;
603 keystate
[VK_LCONTROL
] = 0;
604 // Oddly, pressing F10 in another application seemingly breaks all subsequent
605 // calls to GetKeyboardState regarding the state of the F22 key. Perhaps this
606 // defect is limited to my keyboard driver, but ignoring F22 should be okay.
607 keystate
[VK_F22
] = 0;
608 for (int i
= 0; i
<= VK_PACKET
; ++i
) {
609 if (keystate
[i
] & kKeyDownMask
)
615 void IMM32Manager::ConvertInputModeToImmFlags(TextInputMode input_mode
,
616 DWORD initial_conversion_mode
,
618 DWORD
* new_conversion_mode
) {
620 *new_conversion_mode
= initial_conversion_mode
;
621 switch (input_mode
) {
622 case ui::TEXT_INPUT_MODE_FULL_WIDTH_LATIN
:
623 *new_conversion_mode
|= IME_CMODE_FULLSHAPE
;
624 *new_conversion_mode
&= ~(IME_CMODE_NATIVE
625 | IME_CMODE_KATAKANA
);
627 case ui::TEXT_INPUT_MODE_KANA
:
628 *new_conversion_mode
|= (IME_CMODE_NATIVE
629 | IME_CMODE_FULLSHAPE
);
630 *new_conversion_mode
&= ~IME_CMODE_KATAKANA
;
632 case ui::TEXT_INPUT_MODE_KATAKANA
:
633 *new_conversion_mode
|= (IME_CMODE_NATIVE
635 | IME_CMODE_FULLSHAPE
);