1 // Copyright 2014 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/input_method_chromeos.h"
12 #include "base/basictypes.h"
13 #include "base/bind.h"
14 #include "base/i18n/char_iterator.h"
15 #include "base/logging.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/sys_info.h"
19 #include "base/third_party/icu/icu_utf.h"
20 #include "ui/base/ime/chromeos/composition_text.h"
21 #include "ui/base/ime/chromeos/ime_keyboard.h"
22 #include "ui/base/ime/chromeos/input_method_manager.h"
23 #include "ui/base/ime/text_input_client.h"
24 #include "ui/events/event.h"
25 #include "ui/gfx/geometry/rect.h"
28 chromeos::IMEEngineHandlerInterface
* GetEngine() {
29 return chromeos::IMEBridge::Get()->GetCurrentEngineHandler();
35 // InputMethodChromeOS implementation -----------------------------------------
36 InputMethodChromeOS::InputMethodChromeOS(
37 internal::InputMethodDelegate
* delegate
)
38 : composing_text_(false),
39 composition_changed_(false),
40 weak_ptr_factory_(this) {
41 SetDelegate(delegate
);
42 chromeos::IMEBridge::Get()->SetInputContextHandler(this);
44 UpdateContextFocusState();
47 InputMethodChromeOS::~InputMethodChromeOS() {
48 ConfirmCompositionText();
49 // We are dead, so we need to ask the client to stop relying on us.
50 OnInputMethodChanged();
52 chromeos::IMEBridge::Get()->SetInputContextHandler(NULL
);
55 void InputMethodChromeOS::OnFocus() {
56 InputMethodBase::OnFocus();
57 OnTextInputTypeChanged(GetTextInputClient());
60 void InputMethodChromeOS::OnBlur() {
61 ConfirmCompositionText();
62 InputMethodBase::OnBlur();
63 OnTextInputTypeChanged(GetTextInputClient());
66 bool InputMethodChromeOS::OnUntranslatedIMEMessage(
67 const base::NativeEvent
& event
,
68 NativeEventResult
* result
) {
72 void InputMethodChromeOS::ProcessKeyEventDone(const ui::KeyEvent
* event
,
75 if (event
->type() == ET_KEY_PRESSED
) {
77 // IME event has a priority to be handled, so that character composer
79 character_composer_
.Reset();
81 // If IME does not handle key event, passes keyevent to character composer
82 // to be able to compose complex characters.
83 is_handled
= ExecuteCharacterComposer(*event
);
87 if (event
->type() == ET_KEY_PRESSED
|| event
->type() == ET_KEY_RELEASED
)
88 ProcessKeyEventPostIME(*event
, is_handled
);
91 bool InputMethodChromeOS::DispatchKeyEvent(const ui::KeyEvent
& event
) {
92 DCHECK(event
.type() == ET_KEY_PRESSED
|| event
.type() == ET_KEY_RELEASED
);
93 DCHECK(system_toplevel_window_focused());
95 // For linux_chromeos, the ime keyboard cannot track the caps lock state by
96 // itself, so need to call SetCapsLockEnabled() method to reflect the caps
97 // lock state by the key event.
98 if (!base::SysInfo::IsRunningOnChromeOS()) {
99 chromeos::input_method::InputMethodManager
* manager
=
100 chromeos::input_method::InputMethodManager::Get();
102 chromeos::input_method::ImeKeyboard
* keyboard
= manager
->GetImeKeyboard();
103 if (keyboard
&& event
.type() == ui::ET_KEY_PRESSED
) {
104 bool caps
= (event
.key_code() == ui::VKEY_CAPITAL
)
105 ? !keyboard
->CapsLockIsEnabled()
106 : (event
.flags() & EF_CAPS_LOCK_DOWN
);
107 keyboard
->SetCapsLockEnabled(caps
);
112 // If |context_| is not usable, then we can only dispatch the key event as is.
113 // We only dispatch the key event to input method when the |context_| is an
114 // normal input field (not a password field).
115 // Note: We need to send the key event to ibus even if the |context_| is not
116 // enabled, so that ibus can have a chance to enable the |context_|.
117 if (!IsNonPasswordInputFieldFocused() || !GetEngine()) {
118 if (event
.type() == ET_KEY_PRESSED
) {
119 if (ExecuteCharacterComposer(event
)) {
120 // Treating as PostIME event if character composer handles key event and
121 // generates some IME event,
122 ProcessKeyEventPostIME(event
, true);
125 ProcessUnfilteredKeyPressEvent(event
);
127 DispatchKeyEventPostIME(event
);
132 if (GetEngine()->IsInterestedInKeyEvent()) {
133 GetEngine()->ProcessKeyEvent(
135 base::Bind(&InputMethodChromeOS::ProcessKeyEventDone
,
136 weak_ptr_factory_
.GetWeakPtr(),
137 // Pass the ownership of the new copied event.
138 base::Owned(new ui::KeyEvent(event
))));
140 ProcessKeyEventDone(&event
, false);
145 void InputMethodChromeOS::OnTextInputTypeChanged(
146 const TextInputClient
* client
) {
147 if (!IsTextInputClientFocused(client
))
150 UpdateContextFocusState();
152 chromeos::IMEEngineHandlerInterface
* engine
= GetEngine();
154 // When focused input client is not changed, a text input type change should
155 // cause blur/focus events to engine.
156 // The focus in to or out from password field should also notify engine.
158 chromeos::IMEEngineHandlerInterface::InputContext
context(
159 GetTextInputType(), GetTextInputMode(), GetTextInputFlags());
160 engine
->FocusIn(context
);
163 InputMethodBase::OnTextInputTypeChanged(client
);
166 void InputMethodChromeOS::OnCaretBoundsChanged(const TextInputClient
* client
) {
167 if (!IsInputFieldFocused() || !IsTextInputClientFocused(client
))
170 NotifyTextInputCaretBoundsChanged(client
);
172 if (!IsNonPasswordInputFieldFocused())
175 // The current text input type should not be NONE if |context_| is focused.
176 DCHECK(client
== GetTextInputClient());
177 DCHECK(!IsTextInputTypeNone());
178 const gfx::Rect caret_rect
= client
->GetCaretBounds();
180 gfx::Rect composition_head
;
181 std::vector
<gfx::Rect
> rects
;
182 if (client
->HasCompositionText()) {
185 while (client
->GetCompositionCharacterBounds(i
++, &rect
))
186 rects
.push_back(rect
);
188 rects
.push_back(caret_rect
);
191 if (rects
.size() > 0) {
192 composition_head
= rects
[0];
194 GetEngine()->SetCompositionBounds(rects
);
197 chromeos::IMECandidateWindowHandlerInterface
* candidate_window
=
198 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
199 if (!candidate_window
)
201 candidate_window
->SetCursorBounds(caret_rect
, composition_head
);
203 gfx::Range text_range
;
204 gfx::Range selection_range
;
205 base::string16 surrounding_text
;
206 if (!client
->GetTextRange(&text_range
) ||
207 !client
->GetTextFromRange(text_range
, &surrounding_text
) ||
208 !client
->GetSelectionRange(&selection_range
)) {
209 previous_surrounding_text_
.clear();
210 previous_selection_range_
= gfx::Range::InvalidRange();
214 if (previous_selection_range_
== selection_range
&&
215 previous_surrounding_text_
== surrounding_text
)
218 previous_selection_range_
= selection_range
;
219 previous_surrounding_text_
= surrounding_text
;
221 if (!selection_range
.IsValid()) {
222 // TODO(nona): Ideally selection_range should not be invalid.
223 // TODO(nona): If javascript changes the focus on page loading, even (0,0)
224 // can not be obtained. Need investigation.
228 // Here SetSurroundingText accepts relative position of |surrounding_text|, so
229 // we have to convert |selection_range| from node coordinates to
230 // |surrounding_text| coordinates.
233 GetEngine()->SetSurroundingText(base::UTF16ToUTF8(surrounding_text
),
234 selection_range
.start() - text_range
.start(),
235 selection_range
.end() - text_range
.start());
238 void InputMethodChromeOS::CancelComposition(const TextInputClient
* client
) {
239 if (IsNonPasswordInputFieldFocused() && IsTextInputClientFocused(client
))
243 void InputMethodChromeOS::OnInputLocaleChanged() {
247 std::string
InputMethodChromeOS::GetInputLocale() {
252 bool InputMethodChromeOS::IsActive() {
256 bool InputMethodChromeOS::IsCandidatePopupOpen() const {
257 // TODO(yukishiino): Implement this method.
261 void InputMethodChromeOS::OnWillChangeFocusedClient(
262 TextInputClient
* focused_before
,
263 TextInputClient
* focused
) {
264 ConfirmCompositionText();
267 GetEngine()->FocusOut();
270 void InputMethodChromeOS::OnDidChangeFocusedClient(
271 TextInputClient
* focused_before
,
272 TextInputClient
* focused
) {
273 // Force to update the input type since client's TextInputStateChanged()
274 // function might not be called if text input types before the client loses
275 // focus and after it acquires focus again are the same.
276 UpdateContextFocusState();
279 chromeos::IMEEngineHandlerInterface::InputContext
context(
280 GetTextInputType(), GetTextInputMode(), GetTextInputFlags());
281 GetEngine()->FocusIn(context
);
285 void InputMethodChromeOS::ConfirmCompositionText() {
286 TextInputClient
* client
= GetTextInputClient();
287 if (client
&& client
->HasCompositionText())
288 client
->ConfirmCompositionText();
293 void InputMethodChromeOS::ResetContext() {
294 if (!IsNonPasswordInputFieldFocused() || !GetTextInputClient())
297 DCHECK(system_toplevel_window_focused());
299 composition_
.Clear();
300 result_text_
.clear();
301 composing_text_
= false;
302 composition_changed_
= false;
304 // This function runs asynchronously.
305 // Note: some input method engines may not support reset method, such as
306 // ibus-anthy. But as we control all input method engines by ourselves, we can
307 // make sure that all of the engines we are using support it correctly.
309 GetEngine()->Reset();
311 character_composer_
.Reset();
314 void InputMethodChromeOS::UpdateContextFocusState() {
316 OnInputMethodChanged();
318 // Propagate the focus event to the candidate window handler which also
319 // manages the input method mode indicator.
320 chromeos::IMECandidateWindowHandlerInterface
* candidate_window
=
321 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
322 if (candidate_window
)
323 candidate_window
->FocusStateChanged(IsNonPasswordInputFieldFocused());
325 chromeos::IMEEngineHandlerInterface::InputContext
context(
326 GetTextInputType(), GetTextInputMode(), GetTextInputFlags());
327 chromeos::IMEBridge::Get()->SetCurrentInputContext(context
);
329 if (!IsTextInputTypeNone())
330 OnCaretBoundsChanged(GetTextInputClient());
333 void InputMethodChromeOS::ProcessKeyEventPostIME(
334 const ui::KeyEvent
& event
,
336 TextInputClient
* client
= GetTextInputClient();
338 // As ibus works asynchronously, there is a chance that the focused client
339 // loses focus before this method gets called.
340 DispatchKeyEventPostIME(event
);
344 if (event
.type() == ET_KEY_PRESSED
&& handled
)
345 ProcessFilteredKeyPressEvent(event
);
347 // In case the focus was changed by the key event. The |context_| should have
348 // been reset when the focused window changed.
349 if (client
!= GetTextInputClient())
352 if (HasInputMethodResult())
353 ProcessInputMethodResult(event
, handled
);
355 // In case the focus was changed when sending input method results to the
357 if (client
!= GetTextInputClient())
361 return; // IME handled the key event. do not forward.
363 if (event
.type() == ET_KEY_PRESSED
)
364 ProcessUnfilteredKeyPressEvent(event
);
365 else if (event
.type() == ET_KEY_RELEASED
)
366 DispatchKeyEventPostIME(event
);
369 void InputMethodChromeOS::ProcessFilteredKeyPressEvent(
370 const ui::KeyEvent
& event
) {
371 if (NeedInsertChar()) {
372 DispatchKeyEventPostIME(event
);
374 const ui::KeyEvent
fabricated_event(ET_KEY_PRESSED
,
377 DispatchKeyEventPostIME(fabricated_event
);
381 void InputMethodChromeOS::ProcessUnfilteredKeyPressEvent(
382 const ui::KeyEvent
& event
) {
383 const TextInputClient
* prev_client
= GetTextInputClient();
384 DispatchKeyEventPostIME(event
);
386 // We shouldn't dispatch the character anymore if the key event dispatch
387 // caused focus change. For example, in the following scenario,
388 // 1. visit a web page which has a <textarea>.
390 // 3. enable Korean IME, press A, then press Tab to move the focus to the web
392 // We should return here not to send the Tab key event to RWHV.
393 TextInputClient
* client
= GetTextInputClient();
394 if (!client
|| client
!= prev_client
)
397 // If a key event was not filtered by |context_| and |character_composer_|,
398 // then it means the key event didn't generate any result text. So we need
399 // to send corresponding character to the focused text input client.
400 uint16 ch
= event
.GetCharacter();
402 client
->InsertChar(ch
, event
.flags());
405 void InputMethodChromeOS::ProcessInputMethodResult(const ui::KeyEvent
& event
,
407 TextInputClient
* client
= GetTextInputClient();
410 if (result_text_
.length()) {
411 if (handled
&& NeedInsertChar()) {
412 for (base::string16::const_iterator i
= result_text_
.begin();
413 i
!= result_text_
.end(); ++i
) {
414 client
->InsertChar(*i
, event
.flags());
417 client
->InsertText(result_text_
);
418 composing_text_
= false;
422 if (composition_changed_
&& !IsTextInputTypeNone()) {
423 if (composition_
.text
.length()) {
424 composing_text_
= true;
425 client
->SetCompositionText(composition_
);
426 } else if (result_text_
.empty()) {
427 client
->ClearCompositionText();
431 // We should not clear composition text here, as it may belong to the next
432 // composition session.
433 result_text_
.clear();
434 composition_changed_
= false;
437 bool InputMethodChromeOS::NeedInsertChar() const {
438 return GetTextInputClient() &&
439 (IsTextInputTypeNone() ||
440 (!composing_text_
&& result_text_
.length() == 1));
443 bool InputMethodChromeOS::HasInputMethodResult() const {
444 return result_text_
.length() || composition_changed_
;
447 void InputMethodChromeOS::SendFakeProcessKeyEvent(bool pressed
) const {
448 if (!GetTextInputClient())
450 KeyEvent
evt(pressed
? ET_KEY_PRESSED
: ET_KEY_RELEASED
,
451 pressed
? VKEY_PROCESSKEY
: VKEY_UNKNOWN
,
452 EF_IME_FABRICATED_KEY
);
453 DispatchKeyEventPostIME(evt
);
456 void InputMethodChromeOS::CommitText(const std::string
& text
) {
460 // We need to receive input method result even if the text input type is
461 // TEXT_INPUT_TYPE_NONE, to make sure we can always send correct
462 // character for each key event to the focused text input client.
463 if (!GetTextInputClient())
466 const base::string16 utf16_text
= base::UTF8ToUTF16(text
);
467 if (utf16_text
.empty())
470 // Append the text to the buffer, because commit signal might be fired
471 // multiple times when processing a key event.
472 result_text_
.append(utf16_text
);
474 // If we are not handling key event, do not bother sending text result if the
475 // focused text input client does not support text input.
476 if (!IsTextInputTypeNone()) {
477 SendFakeProcessKeyEvent(true);
478 GetTextInputClient()->InsertText(utf16_text
);
479 SendFakeProcessKeyEvent(false);
480 result_text_
.clear();
484 void InputMethodChromeOS::UpdateCompositionText(
485 const chromeos::CompositionText
& text
,
488 if (IsTextInputTypeNone())
491 if (!CanComposeInline()) {
492 chromeos::IMECandidateWindowHandlerInterface
* candidate_window
=
493 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
494 if (candidate_window
)
495 candidate_window
->UpdatePreeditText(text
.text(), cursor_pos
, visible
);
498 // |visible| argument is very confusing. For example, what's the correct
500 // 1. OnUpdatePreeditText() is called with a text and visible == false, then
501 // 2. OnShowPreeditText() is called afterwards.
503 // If it's only for clearing the current preedit text, then why not just use
504 // OnHidePreeditText()?
510 ExtractCompositionText(text
, cursor_pos
, &composition_
);
512 composition_changed_
= true;
514 // In case OnShowPreeditText() is not called.
515 if (composition_
.text
.length())
516 composing_text_
= true;
518 // If we receive a composition text without pending key event, then we need to
519 // send it to the focused text input client directly.
520 SendFakeProcessKeyEvent(true);
521 GetTextInputClient()->SetCompositionText(composition_
);
522 SendFakeProcessKeyEvent(false);
523 composition_changed_
= false;
524 composition_
.Clear();
527 void InputMethodChromeOS::HidePreeditText() {
528 if (composition_
.text
.empty() || IsTextInputTypeNone())
531 // Intentionally leaves |composing_text_| unchanged.
532 composition_changed_
= true;
533 composition_
.Clear();
535 TextInputClient
* client
= GetTextInputClient();
536 if (client
&& client
->HasCompositionText()) {
537 SendFakeProcessKeyEvent(true);
538 client
->ClearCompositionText();
539 SendFakeProcessKeyEvent(false);
541 composition_changed_
= false;
544 void InputMethodChromeOS::DeleteSurroundingText(int32 offset
, uint32 length
) {
545 if (!composition_
.text
.empty())
546 return; // do nothing if there is ongoing composition.
548 if (GetTextInputClient()) {
549 uint32 before
= offset
>= 0 ? 0U : static_cast<uint32
>(-1 * offset
);
550 GetTextInputClient()->ExtendSelectionAndDelete(before
, length
- before
);
554 bool InputMethodChromeOS::ExecuteCharacterComposer(const ui::KeyEvent
& event
) {
555 if (!character_composer_
.FilterKeyPress(event
))
558 // CharacterComposer consumed the key event. Update the composition text.
559 chromeos::CompositionText preedit
;
560 preedit
.set_text(character_composer_
.preedit_string());
561 UpdateCompositionText(preedit
, preedit
.text().size(),
562 !preedit
.text().empty());
563 std::string commit_text
=
564 base::UTF16ToUTF8(character_composer_
.composed_character());
565 if (!commit_text
.empty()) {
566 CommitText(commit_text
);
571 void InputMethodChromeOS::ExtractCompositionText(
572 const chromeos::CompositionText
& text
,
573 uint32 cursor_position
,
574 CompositionText
* out_composition
) const {
575 out_composition
->Clear();
576 out_composition
->text
= text
.text();
578 if (out_composition
->text
.empty())
581 // ibus uses character index for cursor position and attribute range, but we
582 // use char16 offset for them. So we need to do conversion here.
583 std::vector
<size_t> char16_offsets
;
584 size_t length
= out_composition
->text
.length();
585 base::i18n::UTF16CharIterator
char_iterator(&out_composition
->text
);
587 char16_offsets
.push_back(char_iterator
.array_pos());
588 } while (char_iterator
.Advance());
590 // The text length in Unicode characters.
591 uint32 char_length
= static_cast<uint32
>(char16_offsets
.size());
592 // Make sure we can convert the value of |char_length| as well.
593 char16_offsets
.push_back(length
);
595 size_t cursor_offset
=
596 char16_offsets
[std::min(char_length
, cursor_position
)];
598 out_composition
->selection
= gfx::Range(cursor_offset
);
600 const std::vector
<chromeos::CompositionText::UnderlineAttribute
>&
601 underline_attributes
= text
.underline_attributes();
602 if (!underline_attributes
.empty()) {
603 for (size_t i
= 0; i
< underline_attributes
.size(); ++i
) {
604 const uint32 start
= underline_attributes
[i
].start_index
;
605 const uint32 end
= underline_attributes
[i
].end_index
;
608 CompositionUnderline
underline(char16_offsets
[start
],
612 SK_ColorTRANSPARENT
);
613 if (underline_attributes
[i
].type
==
614 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_DOUBLE
)
615 underline
.thick
= true;
616 else if (underline_attributes
[i
].type
==
617 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_ERROR
)
618 underline
.color
= SK_ColorRED
;
619 else if (underline_attributes
[i
].type
==
620 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_NONE
)
621 underline
.color
= SK_ColorTRANSPARENT
;
622 out_composition
->underlines
.push_back(underline
);
626 DCHECK(text
.selection_start() <= text
.selection_end());
627 if (text
.selection_start() < text
.selection_end()) {
628 const uint32 start
= text
.selection_start();
629 const uint32 end
= text
.selection_end();
630 CompositionUnderline
underline(char16_offsets
[start
],
634 SK_ColorTRANSPARENT
);
635 out_composition
->underlines
.push_back(underline
);
637 // If the cursor is at start or end of this underline, then we treat
638 // it as the selection range as well, but make sure to set the cursor
639 // position to the selection end.
640 if (underline
.start_offset
== cursor_offset
) {
641 out_composition
->selection
.set_start(underline
.end_offset
);
642 out_composition
->selection
.set_end(cursor_offset
);
643 } else if (underline
.end_offset
== cursor_offset
) {
644 out_composition
->selection
.set_start(underline
.start_offset
);
645 out_composition
->selection
.set_end(cursor_offset
);
649 // Use a black thin underline by default.
650 if (out_composition
->underlines
.empty()) {
651 out_composition
->underlines
.push_back(CompositionUnderline(
652 0, length
, SK_ColorBLACK
, false /* thick */, SK_ColorTRANSPARENT
));
656 bool InputMethodChromeOS::IsNonPasswordInputFieldFocused() {
657 TextInputType type
= GetTextInputType();
658 return (type
!= TEXT_INPUT_TYPE_NONE
) && (type
!= TEXT_INPUT_TYPE_PASSWORD
);
661 bool InputMethodChromeOS::IsInputFieldFocused() {
662 return GetTextInputType() != TEXT_INPUT_TYPE_NONE
;