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"
7 #include "base/basictypes.h"
8 #include "base/memory/scoped_ptr.h"
9 #include "base/strings/string16.h"
10 #include "base/strings/string_util.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/win/scoped_comptr.h"
13 #include "third_party/skia/include/core/SkColor.h"
14 #include "ui/base/ime/composition_text.h"
16 // "imm32.lib" is required by IMM32 APIs used in this file.
17 // NOTE(hbono): To comply with a comment from Darin, I have added
18 // this #pragma directive instead of adding "imm32.lib" to a project file.
19 #pragma comment(lib, "imm32.lib")
21 // Following code requires wchar_t to be same as char16. It should always be
23 static_assert(sizeof(wchar_t) == sizeof(base::char16
),
24 "wchar_t should be the same size as char16");
26 ///////////////////////////////////////////////////////////////////////////////
31 // Determines whether or not the given attribute represents a target
32 // (a.k.a. a selection).
33 bool IsTargetAttribute(char attribute
) {
34 return (attribute
== ATTR_TARGET_CONVERTED
||
35 attribute
== ATTR_TARGET_NOTCONVERTED
);
38 // Helper function for IMM32Manager::GetCompositionInfo() method, to get the
39 // target range that's selected by the user in the current composition string.
40 void GetCompositionTargetRange(HIMC imm_context
, int* target_start
,
42 int attribute_size
= ::ImmGetCompositionString(imm_context
, GCS_COMPATTR
,
44 if (attribute_size
> 0) {
47 scoped_ptr
<char[]> attribute_data(new char[attribute_size
]);
48 if (attribute_data
.get()) {
49 ::ImmGetCompositionString(imm_context
, GCS_COMPATTR
,
50 attribute_data
.get(), attribute_size
);
51 for (start
= 0; start
< attribute_size
; ++start
) {
52 if (IsTargetAttribute(attribute_data
[start
]))
55 for (end
= start
; end
< attribute_size
; ++end
) {
56 if (!IsTargetAttribute(attribute_data
[end
]))
60 *target_start
= start
;
65 // Helper function for IMM32Manager::GetCompositionInfo() method, to get
66 // underlines information of the current composition string.
67 void GetCompositionUnderlines(HIMC imm_context
,
70 ui::CompositionUnderlines
* underlines
) {
71 int clause_size
= ::ImmGetCompositionString(imm_context
, GCS_COMPCLAUSE
,
73 int clause_length
= clause_size
/ sizeof(uint32
);
75 scoped_ptr
<uint32
[]> clause_data(new uint32
[clause_length
]);
76 if (clause_data
.get()) {
77 ::ImmGetCompositionString(imm_context
, GCS_COMPCLAUSE
,
78 clause_data
.get(), clause_size
);
79 for (int i
= 0; i
< clause_length
- 1; ++i
) {
80 ui::CompositionUnderline underline
;
81 underline
.start_offset
= clause_data
[i
];
82 underline
.end_offset
= clause_data
[i
+1];
83 underline
.color
= SK_ColorBLACK
;
84 underline
.thick
= false;
85 underline
.background_color
= SK_ColorTRANSPARENT
;
87 // Use thick underline for the target clause.
88 if (underline
.start_offset
>= static_cast<uint32
>(target_start
) &&
89 underline
.end_offset
<= static_cast<uint32
>(target_end
)) {
90 underline
.thick
= true;
92 underlines
->push_back(underline
);
98 // Checks if a given primary language ID is a RTL language.
99 bool IsRTLPrimaryLangID(LANGID lang
) {
117 IMM32Manager::IMM32Manager()
118 : is_composing_(false),
119 input_language_id_(LANG_USER_DEFAULT
),
120 system_caret_(false),
121 caret_rect_(-1, -1, 0, 0),
122 use_composition_window_(false) {
125 IMM32Manager::~IMM32Manager() {
128 void IMM32Manager::SetInputLanguage() {
129 // Retrieve the current keyboard layout from Windows and determine whether
130 // or not the current input context has IMEs.
131 // Also save its input language for language-specific operations required
132 // while composing a text.
133 HKL keyboard_layout
= ::GetKeyboardLayout(0);
135 static_cast<LANGID
>(reinterpret_cast<uintptr_t>(keyboard_layout
));
138 void IMM32Manager::CreateImeWindow(HWND window_handle
) {
139 // When a user disables TSF (Text Service Framework) and CUAS (Cicero
140 // Unaware Application Support), Chinese IMEs somehow ignore function calls
141 // to ::ImmSetCandidateWindow(), i.e. they do not move their candidate
142 // window to the position given as its parameters, and use the position
143 // of the current system caret instead, i.e. it uses ::GetCaretPos() to
144 // retrieve the position of their IME candidate window.
145 // Therefore, we create a temporary system caret for Chinese IMEs and use
146 // it during this input context.
147 // Since some third-party Japanese IME also uses ::GetCaretPos() to determine
148 // their window position, we also create a caret for Japanese IMEs.
149 if (PRIMARYLANGID(input_language_id_
) == LANG_CHINESE
||
150 PRIMARYLANGID(input_language_id_
) == LANG_JAPANESE
) {
151 if (!system_caret_
) {
152 if (::CreateCaret(window_handle
, NULL
, 1, 1)) {
153 system_caret_
= true;
157 // Restore the positions of the IME windows.
158 UpdateImeWindow(window_handle
);
161 LRESULT
IMM32Manager::SetImeWindowStyle(HWND window_handle
, UINT message
,
162 WPARAM wparam
, LPARAM lparam
,
164 // To prevent the IMM (Input Method Manager) from displaying the IME
165 // composition window, Update the styles of the IME windows and EXPLICITLY
166 // call ::DefWindowProc() here.
167 // NOTE(hbono): We can NEVER let WTL call ::DefWindowProc() when we update
168 // the styles of IME windows because the 'lparam' variable is a local one
169 // and all its updates disappear in returning from this function, i.e. WTL
170 // does not call ::DefWindowProc() with our updated 'lparam' value but call
171 // the function with its original value and over-writes our window styles.
173 lparam
&= ~ISC_SHOWUICOMPOSITIONWINDOW
;
174 return ::DefWindowProc(window_handle
, message
, wparam
, lparam
);
177 void IMM32Manager::DestroyImeWindow(HWND window_handle
) {
178 // Destroy the system caret if we have created for this IME input context.
181 system_caret_
= false;
185 void IMM32Manager::MoveImeWindow(HWND window_handle
, HIMC imm_context
) {
186 // Does nothing when the target window has no input focus. This is important
187 // because the renderer may issue SelectionBoundsChanged event even when it
188 // has no input focus. (e.g. the page update caused by incremental search.)
189 // So this event should be ignored when the |window_handle| no longer has the
191 if (GetFocus() != window_handle
)
194 int x
= caret_rect_
.x();
195 int y
= caret_rect_
.y();
197 const int kCaretMargin
= 1;
198 if (!use_composition_window_
&&
199 PRIMARYLANGID(input_language_id_
) == LANG_CHINESE
) {
200 // As written in a comment in IMM32Manager::CreateImeWindow(),
201 // Chinese IMEs ignore function calls to ::ImmSetCandidateWindow()
202 // when a user disables TSF (Text Service Framework) and CUAS (Cicero
203 // Unaware Application Support).
204 // On the other hand, when a user enables TSF and CUAS, Chinese IMEs
205 // ignore the position of the current system caret and uses the
206 // parameters given to ::ImmSetCandidateWindow() with its 'dwStyle'
207 // parameter CFS_CANDIDATEPOS.
208 // Therefore, we do not only call ::ImmSetCandidateWindow() but also
209 // set the positions of the temporary system caret if it exists.
210 CANDIDATEFORM candidate_position
= {0, CFS_CANDIDATEPOS
, {x
, y
},
212 ::ImmSetCandidateWindow(imm_context
, &candidate_position
);
215 switch (PRIMARYLANGID(input_language_id_
)) {
217 ::SetCaretPos(x
, y
+ caret_rect_
.height());
224 if (use_composition_window_
) {
225 // Moves the composition text window.
226 COMPOSITIONFORM cf
= {CFS_POINT
, {x
, y
}};
227 ::ImmSetCompositionWindow(imm_context
, &cf
);
228 // Don't need to set the position of candidate window.
232 if (PRIMARYLANGID(input_language_id_
) == LANG_KOREAN
) {
233 // Chinese IMEs and Japanese IMEs require the upper-left corner of
234 // the caret to move the position of their candidate windows.
235 // On the other hand, Korean IMEs require the lower-left corner of the
236 // caret to move their candidate windows.
239 // Japanese IMEs and Korean IMEs also use the rectangle given to
240 // ::ImmSetCandidateWindow() with its 'dwStyle' parameter CFS_EXCLUDE
241 // to move their candidate windows when a user disables TSF and CUAS.
242 // Therefore, we also set this parameter here.
243 CANDIDATEFORM exclude_rectangle
= {0, CFS_EXCLUDE
, {x
, y
},
244 {x
, y
, x
+ caret_rect_
.width(), y
+ caret_rect_
.height()}};
245 ::ImmSetCandidateWindow(imm_context
, &exclude_rectangle
);
248 void IMM32Manager::UpdateImeWindow(HWND window_handle
) {
249 // Just move the IME window attached to the given window.
250 if (caret_rect_
.x() >= 0 && caret_rect_
.y() >= 0) {
251 HIMC imm_context
= ::ImmGetContext(window_handle
);
253 MoveImeWindow(window_handle
, imm_context
);
254 ::ImmReleaseContext(window_handle
, imm_context
);
259 void IMM32Manager::CleanupComposition(HWND window_handle
) {
260 // Notify the IMM attached to the given window to complete the ongoing
261 // composition, (this case happens when the given window is de-activated
262 // while composing a text and re-activated), and reset the omposition status.
264 HIMC imm_context
= ::ImmGetContext(window_handle
);
266 ::ImmNotifyIME(imm_context
, NI_COMPOSITIONSTR
, CPS_COMPLETE
, 0);
267 ::ImmReleaseContext(window_handle
, imm_context
);
269 ResetComposition(window_handle
);
273 void IMM32Manager::ResetComposition(HWND window_handle
) {
274 // Currently, just reset the composition status.
275 is_composing_
= false;
278 void IMM32Manager::CompleteComposition(HWND window_handle
, HIMC imm_context
) {
279 // We have to confirm there is an ongoing composition before completing it.
280 // This is for preventing some IMEs from getting confused while completing an
281 // ongoing composition even if they do not have any ongoing compositions.)
283 ::ImmNotifyIME(imm_context
, NI_COMPOSITIONSTR
, CPS_COMPLETE
, 0);
284 ResetComposition(window_handle
);
288 void IMM32Manager::GetCompositionInfo(HIMC imm_context
, LPARAM lparam
,
289 CompositionText
* composition
) {
290 // We only care about GCS_COMPATTR, GCS_COMPCLAUSE and GCS_CURSORPOS, and
291 // convert them into underlines and selection range respectively.
292 composition
->underlines
.clear();
294 int length
= static_cast<int>(composition
->text
.length());
296 // Find out the range selected by the user.
297 int target_start
= length
;
298 int target_end
= length
;
299 if (lparam
& GCS_COMPATTR
)
300 GetCompositionTargetRange(imm_context
, &target_start
, &target_end
);
302 // Retrieve the selection range information. If CS_NOMOVECARET is specified,
303 // that means the cursor should not be moved, then we just place the caret at
304 // the beginning of the composition string. Otherwise we should honour the
305 // GCS_CURSORPOS value if it's available.
306 // TODO(suzhe): due to a bug of webkit, we currently can't use selection range
307 // with composition string. See: https://bugs.webkit.org/show_bug.cgi?id=40805
308 if (!(lparam
& CS_NOMOVECARET
) && (lparam
& GCS_CURSORPOS
)) {
309 // IMM32 does not support non-zero-width selection in a composition. So
310 // always use the caret position as selection range.
311 int cursor
= ::ImmGetCompositionString(imm_context
, GCS_CURSORPOS
, NULL
, 0);
312 composition
->selection
= gfx::Range(cursor
);
314 composition
->selection
= gfx::Range(0);
317 // Retrieve the clause segmentations and convert them to underlines.
318 if (lparam
& GCS_COMPCLAUSE
) {
319 GetCompositionUnderlines(imm_context
, target_start
, target_end
,
320 &composition
->underlines
);
323 // Set default underlines in case there is no clause information.
324 if (!composition
->underlines
.size()) {
325 CompositionUnderline underline
;
326 underline
.color
= SK_ColorBLACK
;
327 underline
.background_color
= SK_ColorTRANSPARENT
;
328 if (target_start
> 0) {
329 underline
.start_offset
= 0U;
330 underline
.end_offset
= static_cast<uint32
>(target_start
);
331 underline
.thick
= false;
332 composition
->underlines
.push_back(underline
);
334 if (target_end
> target_start
) {
335 underline
.start_offset
= static_cast<uint32
>(target_start
);
336 underline
.end_offset
= static_cast<uint32
>(target_end
);
337 underline
.thick
= true;
338 composition
->underlines
.push_back(underline
);
340 if (target_end
< length
) {
341 underline
.start_offset
= static_cast<uint32
>(target_end
);
342 underline
.end_offset
= static_cast<uint32
>(length
);
343 underline
.thick
= false;
344 composition
->underlines
.push_back(underline
);
349 bool IMM32Manager::GetString(HIMC imm_context
,
352 base::string16
* result
) {
353 if (!(lparam
& type
))
355 LONG string_size
= ::ImmGetCompositionString(imm_context
, type
, NULL
, 0);
356 if (string_size
<= 0)
358 DCHECK_EQ(0u, string_size
% sizeof(wchar_t));
359 ::ImmGetCompositionString(imm_context
, type
,
360 base::WriteInto(result
, (string_size
/ sizeof(wchar_t)) + 1),
365 bool IMM32Manager::GetResult(
366 HWND window_handle
, LPARAM lparam
, base::string16
* result
) {
368 HIMC imm_context
= ::ImmGetContext(window_handle
);
370 ret
= GetString(imm_context
, lparam
, GCS_RESULTSTR
, result
);
371 ::ImmReleaseContext(window_handle
, imm_context
);
376 bool IMM32Manager::GetComposition(HWND window_handle
, LPARAM lparam
,
377 CompositionText
* composition
) {
379 HIMC imm_context
= ::ImmGetContext(window_handle
);
381 // Copy the composition string to the CompositionText object.
382 ret
= GetString(imm_context
, lparam
, GCS_COMPSTR
, &composition
->text
);
385 // This is a dirty workaround for facebook. Facebook deletes the
386 // placeholder character (U+3000) used by Traditional-Chinese IMEs at the
387 // beginning of composition text. This prevents WebKit from replacing this
388 // placeholder character with a Traditional-Chinese character, i.e. we
389 // cannot input any characters in a comment box of facebook with
390 // Traditional-Chinese IMEs. As a workaround, we replace U+3000 at the
391 // beginning of composition text with U+FF3F, a placeholder character used
393 if (input_language_id_
== MAKELANGID(LANG_CHINESE
,
394 SUBLANG_CHINESE_TRADITIONAL
) &&
395 composition
->text
[0] == 0x3000) {
396 composition
->text
[0] = 0xFF3F;
399 // Retrieve the composition underlines and selection range information.
400 GetCompositionInfo(imm_context
, lparam
, composition
);
402 // Mark that there is an ongoing composition.
403 is_composing_
= true;
406 ::ImmReleaseContext(window_handle
, imm_context
);
411 void IMM32Manager::DisableIME(HWND window_handle
) {
412 // A renderer process have moved its input focus to a password input
413 // when there is an ongoing composition, e.g. a user has clicked a
414 // mouse button and selected a password input while composing a text.
415 // For this case, we have to complete the ongoing composition and
416 // clean up the resources attached to this object BEFORE DISABLING THE IME.
417 CleanupComposition(window_handle
);
418 ::ImmAssociateContextEx(window_handle
, NULL
, 0);
421 void IMM32Manager::CancelIME(HWND window_handle
) {
423 HIMC imm_context
= ::ImmGetContext(window_handle
);
425 ::ImmNotifyIME(imm_context
, NI_COMPOSITIONSTR
, CPS_CANCEL
, 0);
426 ::ImmReleaseContext(window_handle
, imm_context
);
428 ResetComposition(window_handle
);
432 void IMM32Manager::EnableIME(HWND window_handle
) {
433 // Load the default IME context.
435 // IMM ignores this call if the IME context is loaded. Therefore, we do
436 // not have to check whether or not the IME context is loaded.
437 ::ImmAssociateContextEx(window_handle
, NULL
, IACE_DEFAULT
);
440 void IMM32Manager::UpdateCaretRect(HWND window_handle
,
441 const gfx::Rect
& caret_rect
) {
442 // Save the caret position, and Update the position of the IME window.
443 // This update is used for moving an IME window when a renderer process
444 // resize/moves the input caret.
445 if (caret_rect_
!= caret_rect
) {
446 caret_rect_
= caret_rect
;
447 // Move the IME windows.
448 HIMC imm_context
= ::ImmGetContext(window_handle
);
450 MoveImeWindow(window_handle
, imm_context
);
451 ::ImmReleaseContext(window_handle
, imm_context
);
456 void IMM32Manager::SetUseCompositionWindow(bool use_composition_window
) {
457 use_composition_window_
= use_composition_window
;
460 std::string
IMM32Manager::GetInputLanguageName() const {
461 const LCID locale_id
= MAKELCID(input_language_id_
, SORT_DEFAULT
);
462 // max size for LOCALE_SISO639LANGNAME and LOCALE_SISO3166CTRYNAME is 9.
466 int length
= ::GetLocaleInfo(locale_id
, LOCALE_SISO639LANGNAME
, &buffer
[0],
469 return std::string();
471 std::string language
;
472 base::WideToUTF8(buffer
, length
- 1, &language
);
473 if (SUBLANGID(input_language_id_
) == SUBLANG_NEUTRAL
)
477 length
= ::GetLocaleInfo(locale_id
, LOCALE_SISO3166CTRYNAME
, &buffer
[0],
483 base::WideToUTF8(buffer
, length
- 1, ®ion
);
484 return language
.append(1, '-').append(region
);
487 void IMM32Manager::SetTextInputMode(HWND window_handle
,
488 TextInputMode input_mode
) {
489 if (input_mode
== ui::TEXT_INPUT_MODE_DEFAULT
)
492 const HIMC imm_context
= ::ImmGetContext(window_handle
);
496 DWORD conversion_mode
= 0;
497 DWORD sentence_mode
= 0;
498 if (::ImmGetConversionStatus(imm_context
, &conversion_mode
, &sentence_mode
)
504 ConvertInputModeToImmFlags(input_mode
, conversion_mode
, &open
,
507 ::ImmSetOpenStatus(imm_context
, open
);
509 ::ImmSetConversionStatus(imm_context
, conversion_mode
, sentence_mode
);
510 ::ImmReleaseContext(window_handle
, imm_context
);
514 bool IMM32Manager::IsRTLKeyboardLayoutInstalled() {
516 RTL_KEYBOARD_LAYOUT_NOT_INITIALIZED
,
517 RTL_KEYBOARD_LAYOUT_INSTALLED
,
518 RTL_KEYBOARD_LAYOUT_NOT_INSTALLED
,
519 RTL_KEYBOARD_LAYOUT_ERROR
,
520 } layout
= RTL_KEYBOARD_LAYOUT_NOT_INITIALIZED
;
522 // Cache the result value.
523 if (layout
!= RTL_KEYBOARD_LAYOUT_NOT_INITIALIZED
)
524 return layout
== RTL_KEYBOARD_LAYOUT_INSTALLED
;
526 // Retrieve the number of layouts installed in this system.
527 int size
= GetKeyboardLayoutList(0, NULL
);
529 layout
= RTL_KEYBOARD_LAYOUT_ERROR
;
533 // Retrieve the keyboard layouts in an array and check if there is an RTL
535 scoped_ptr
<HKL
[]> layouts(new HKL
[size
]);
536 ::GetKeyboardLayoutList(size
, layouts
.get());
537 for (int i
= 0; i
< size
; ++i
) {
538 if (IsRTLPrimaryLangID(
539 PRIMARYLANGID(reinterpret_cast<uintptr_t>(layouts
[i
])))) {
540 layout
= RTL_KEYBOARD_LAYOUT_INSTALLED
;
545 layout
= RTL_KEYBOARD_LAYOUT_NOT_INSTALLED
;
549 bool IMM32Manager::IsCtrlShiftPressed(base::i18n::TextDirection
* direction
) {
550 uint8_t keystate
[256];
551 if (!::GetKeyboardState(&keystate
[0]))
554 // To check if a user is pressing only a control key and a right-shift key
555 // (or a left-shift key), we use the steps below:
556 // 1. Check if a user is pressing a control key and a right-shift key (or
557 // a left-shift key).
558 // 2. If the condition 1 is true, we should check if there are any other
559 // keys pressed at the same time.
560 // To ignore the keys checked in 1, we set their status to 0 before
561 // checking the key status.
562 const int kKeyDownMask
= 0x80;
563 if ((keystate
[VK_CONTROL
] & kKeyDownMask
) == 0)
566 if (keystate
[VK_RSHIFT
] & kKeyDownMask
) {
567 keystate
[VK_RSHIFT
] = 0;
568 *direction
= base::i18n::RIGHT_TO_LEFT
;
569 } else if (keystate
[VK_LSHIFT
] & kKeyDownMask
) {
570 keystate
[VK_LSHIFT
] = 0;
571 *direction
= base::i18n::LEFT_TO_RIGHT
;
576 // Scan the key status to find pressed keys. We should abandon changing the
577 // text direction when there are other pressed keys.
578 // This code is executed only when a user is pressing a control key and a
579 // right-shift key (or a left-shift key), i.e. we should ignore the status of
580 // the keys: VK_SHIFT, VK_CONTROL, VK_RCONTROL, and VK_LCONTROL.
581 // So, we reset their status to 0 and ignore them.
582 keystate
[VK_SHIFT
] = 0;
583 keystate
[VK_CONTROL
] = 0;
584 keystate
[VK_RCONTROL
] = 0;
585 keystate
[VK_LCONTROL
] = 0;
586 // Oddly, pressing F10 in another application seemingly breaks all subsequent
587 // calls to GetKeyboardState regarding the state of the F22 key. Perhaps this
588 // defect is limited to my keyboard driver, but ignoring F22 should be okay.
589 keystate
[VK_F22
] = 0;
590 for (int i
= 0; i
<= VK_PACKET
; ++i
) {
591 if (keystate
[i
] & kKeyDownMask
)
597 void IMM32Manager::ConvertInputModeToImmFlags(TextInputMode input_mode
,
598 DWORD initial_conversion_mode
,
600 DWORD
* new_conversion_mode
) {
602 *new_conversion_mode
= initial_conversion_mode
;
603 switch (input_mode
) {
604 case ui::TEXT_INPUT_MODE_FULL_WIDTH_LATIN
:
605 *new_conversion_mode
|= IME_CMODE_FULLSHAPE
;
606 *new_conversion_mode
&= ~(IME_CMODE_NATIVE
607 | IME_CMODE_KATAKANA
);
609 case ui::TEXT_INPUT_MODE_KANA
:
610 *new_conversion_mode
|= (IME_CMODE_NATIVE
611 | IME_CMODE_FULLSHAPE
);
612 *new_conversion_mode
&= ~IME_CMODE_KATAKANA
;
614 case ui::TEXT_INPUT_MODE_KATAKANA
:
615 *new_conversion_mode
|= (IME_CMODE_NATIVE
617 | IME_CMODE_FULLSHAPE
);