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 current_keyevent_id_(0),
41 weak_ptr_factory_(this) {
42 SetDelegate(delegate
);
43 chromeos::IMEBridge::Get()->SetInputContextHandler(this);
45 UpdateContextFocusState();
48 InputMethodChromeOS::~InputMethodChromeOS() {
49 AbandonAllPendingKeyEvents();
50 ConfirmCompositionText();
51 // We are dead, so we need to ask the client to stop relying on us.
52 OnInputMethodChanged();
54 chromeos::IMEBridge::Get()->SetInputContextHandler(NULL
);
57 void InputMethodChromeOS::OnFocus() {
58 InputMethodBase::OnFocus();
59 OnTextInputTypeChanged(GetTextInputClient());
62 void InputMethodChromeOS::OnBlur() {
63 ConfirmCompositionText();
64 InputMethodBase::OnBlur();
65 OnTextInputTypeChanged(GetTextInputClient());
68 bool InputMethodChromeOS::OnUntranslatedIMEMessage(
69 const base::NativeEvent
& event
,
70 NativeEventResult
* result
) {
74 void InputMethodChromeOS::ProcessKeyEventDone(uint32 id
,
77 if (pending_key_events_
.find(id
) == pending_key_events_
.end())
78 return; // Abandoned key event.
81 if (event
->type() == ET_KEY_PRESSED
) {
83 // IME event has a priority to be handled, so that character composer
85 character_composer_
.Reset();
87 // If IME does not handle key event, passes keyevent to character composer
88 // to be able to compose complex characters.
89 is_handled
= ExecuteCharacterComposer(*event
);
93 if (event
->type() == ET_KEY_PRESSED
|| event
->type() == ET_KEY_RELEASED
)
94 ProcessKeyEventPostIME(*event
, is_handled
);
96 // ProcessKeyEventPostIME may change the |pending_key_events_|.
97 pending_key_events_
.erase(id
);
100 bool InputMethodChromeOS::DispatchKeyEvent(const ui::KeyEvent
& event
) {
101 DCHECK(event
.type() == ET_KEY_PRESSED
|| event
.type() == ET_KEY_RELEASED
);
102 DCHECK(system_toplevel_window_focused());
104 // For linux_chromeos, the ime keyboard cannot track the caps lock state by
105 // itself, so need to call SetCapsLockEnabled() method to reflect the caps
106 // lock state by the key event.
107 if (!base::SysInfo::IsRunningOnChromeOS()) {
108 chromeos::input_method::InputMethodManager
* manager
=
109 chromeos::input_method::InputMethodManager::Get();
111 chromeos::input_method::ImeKeyboard
* keyboard
= manager
->GetImeKeyboard();
112 if (keyboard
&& event
.type() == ui::ET_KEY_PRESSED
) {
113 bool caps
= (event
.key_code() == ui::VKEY_CAPITAL
)
114 ? !keyboard
->CapsLockIsEnabled()
115 : (event
.flags() & EF_CAPS_LOCK_DOWN
);
116 keyboard
->SetCapsLockEnabled(caps
);
121 // If |context_| is not usable, then we can only dispatch the key event as is.
122 // We only dispatch the key event to input method when the |context_| is an
123 // normal input field (not a password field).
124 // Note: We need to send the key event to ibus even if the |context_| is not
125 // enabled, so that ibus can have a chance to enable the |context_|.
126 if (!IsNonPasswordInputFieldFocused() || !GetEngine()) {
127 if (event
.type() == ET_KEY_PRESSED
) {
128 if (ExecuteCharacterComposer(event
)) {
129 // Treating as PostIME event if character composer handles key event and
130 // generates some IME event,
131 ProcessKeyEventPostIME(event
, true);
134 ProcessUnfilteredKeyPressEvent(event
);
136 DispatchKeyEventPostIME(event
);
141 pending_key_events_
.insert(current_keyevent_id_
);
143 ui::KeyEvent
* copied_event
= new ui::KeyEvent(event
);
144 GetEngine()->ProcessKeyEvent(
146 base::Bind(&InputMethodChromeOS::ProcessKeyEventDone
,
147 weak_ptr_factory_
.GetWeakPtr(),
148 current_keyevent_id_
,
149 // Pass the ownership of |copied_event|.
150 base::Owned(copied_event
)));
152 ++current_keyevent_id_
;
156 void InputMethodChromeOS::OnTextInputTypeChanged(
157 const TextInputClient
* client
) {
158 if (!IsTextInputClientFocused(client
))
161 UpdateContextFocusState();
163 chromeos::IMEEngineHandlerInterface
* engine
= GetEngine();
165 // When focused input client is not changed, a text input type change should
166 // cause blur/focus events to engine.
167 // The focus in to or out from password field should also notify engine.
169 chromeos::IMEEngineHandlerInterface::InputContext
context(
170 GetTextInputType(), GetTextInputMode(), GetTextInputFlags());
171 engine
->FocusIn(context
);
174 InputMethodBase::OnTextInputTypeChanged(client
);
177 void InputMethodChromeOS::OnCaretBoundsChanged(const TextInputClient
* client
) {
178 if (!IsInputFieldFocused() || !IsTextInputClientFocused(client
))
181 NotifyTextInputCaretBoundsChanged(client
);
183 if (!IsNonPasswordInputFieldFocused())
186 // The current text input type should not be NONE if |context_| is focused.
187 DCHECK(client
== GetTextInputClient());
188 DCHECK(!IsTextInputTypeNone());
189 const gfx::Rect caret_rect
= client
->GetCaretBounds();
191 gfx::Rect composition_head
;
192 std::vector
<gfx::Rect
> rects
;
193 if (client
->HasCompositionText()) {
196 while (client
->GetCompositionCharacterBounds(i
++, &rect
))
197 rects
.push_back(rect
);
199 rects
.push_back(caret_rect
);
202 if (rects
.size() > 0) {
203 composition_head
= rects
[0];
205 GetEngine()->SetCompositionBounds(rects
);
208 chromeos::IMECandidateWindowHandlerInterface
* candidate_window
=
209 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
210 if (!candidate_window
)
212 candidate_window
->SetCursorBounds(caret_rect
, composition_head
);
214 gfx::Range text_range
;
215 gfx::Range selection_range
;
216 base::string16 surrounding_text
;
217 if (!client
->GetTextRange(&text_range
) ||
218 !client
->GetTextFromRange(text_range
, &surrounding_text
) ||
219 !client
->GetSelectionRange(&selection_range
)) {
220 previous_surrounding_text_
.clear();
221 previous_selection_range_
= gfx::Range::InvalidRange();
225 if (previous_selection_range_
== selection_range
&&
226 previous_surrounding_text_
== surrounding_text
)
229 previous_selection_range_
= selection_range
;
230 previous_surrounding_text_
= surrounding_text
;
232 if (!selection_range
.IsValid()) {
233 // TODO(nona): Ideally selection_range should not be invalid.
234 // TODO(nona): If javascript changes the focus on page loading, even (0,0)
235 // can not be obtained. Need investigation.
239 // Here SetSurroundingText accepts relative position of |surrounding_text|, so
240 // we have to convert |selection_range| from node coordinates to
241 // |surrounding_text| coordinates.
244 GetEngine()->SetSurroundingText(base::UTF16ToUTF8(surrounding_text
),
245 selection_range
.start() - text_range
.start(),
246 selection_range
.end() - text_range
.start());
249 void InputMethodChromeOS::CancelComposition(const TextInputClient
* client
) {
250 if (IsNonPasswordInputFieldFocused() && IsTextInputClientFocused(client
))
254 void InputMethodChromeOS::OnInputLocaleChanged() {
258 std::string
InputMethodChromeOS::GetInputLocale() {
263 bool InputMethodChromeOS::IsActive() {
267 bool InputMethodChromeOS::IsCandidatePopupOpen() const {
268 // TODO(yukishiino): Implement this method.
272 void InputMethodChromeOS::OnWillChangeFocusedClient(
273 TextInputClient
* focused_before
,
274 TextInputClient
* focused
) {
275 ConfirmCompositionText();
278 GetEngine()->FocusOut();
281 void InputMethodChromeOS::OnDidChangeFocusedClient(
282 TextInputClient
* focused_before
,
283 TextInputClient
* focused
) {
284 // Force to update the input type since client's TextInputStateChanged()
285 // function might not be called if text input types before the client loses
286 // focus and after it acquires focus again are the same.
287 UpdateContextFocusState();
290 chromeos::IMEEngineHandlerInterface::InputContext
context(
291 GetTextInputType(), GetTextInputMode(), GetTextInputFlags());
292 GetEngine()->FocusIn(context
);
296 void InputMethodChromeOS::ConfirmCompositionText() {
297 TextInputClient
* client
= GetTextInputClient();
298 if (client
&& client
->HasCompositionText())
299 client
->ConfirmCompositionText();
304 void InputMethodChromeOS::ResetContext() {
305 if (!IsNonPasswordInputFieldFocused() || !GetTextInputClient())
308 DCHECK(system_toplevel_window_focused());
310 composition_
.Clear();
311 result_text_
.clear();
312 composing_text_
= false;
313 composition_changed_
= false;
315 // We need to abandon all pending key events, but as above comment says, there
316 // is no reliable way to abandon all results generated by these abandoned key
318 AbandonAllPendingKeyEvents();
320 // This function runs asynchronously.
321 // Note: some input method engines may not support reset method, such as
322 // ibus-anthy. But as we control all input method engines by ourselves, we can
323 // make sure that all of the engines we are using support it correctly.
325 GetEngine()->Reset();
327 character_composer_
.Reset();
330 void InputMethodChromeOS::UpdateContextFocusState() {
332 OnInputMethodChanged();
334 // Propagate the focus event to the candidate window handler which also
335 // manages the input method mode indicator.
336 chromeos::IMECandidateWindowHandlerInterface
* candidate_window
=
337 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
338 if (candidate_window
)
339 candidate_window
->FocusStateChanged(IsNonPasswordInputFieldFocused());
341 chromeos::IMEBridge::Get()->SetCurrentTextInputType(GetTextInputType());
343 if (!IsTextInputTypeNone())
344 OnCaretBoundsChanged(GetTextInputClient());
347 void InputMethodChromeOS::ProcessKeyEventPostIME(
348 const ui::KeyEvent
& event
,
350 TextInputClient
* client
= GetTextInputClient();
352 // As ibus works asynchronously, there is a chance that the focused client
353 // loses focus before this method gets called.
354 DispatchKeyEventPostIME(event
);
358 if (event
.type() == ET_KEY_PRESSED
&& handled
)
359 ProcessFilteredKeyPressEvent(event
);
361 // In case the focus was changed by the key event. The |context_| should have
362 // been reset when the focused window changed.
363 if (client
!= GetTextInputClient())
366 if (HasInputMethodResult())
367 ProcessInputMethodResult(event
, handled
);
369 // In case the focus was changed when sending input method results to the
371 if (client
!= GetTextInputClient())
374 if (event
.type() == ET_KEY_PRESSED
&& !handled
)
375 ProcessUnfilteredKeyPressEvent(event
);
376 else if (event
.type() == ET_KEY_RELEASED
)
377 DispatchKeyEventPostIME(event
);
380 void InputMethodChromeOS::ProcessFilteredKeyPressEvent(
381 const ui::KeyEvent
& event
) {
382 if (NeedInsertChar()) {
383 DispatchKeyEventPostIME(event
);
385 const ui::KeyEvent
fabricated_event(ET_KEY_PRESSED
,
388 DispatchKeyEventPostIME(fabricated_event
);
392 void InputMethodChromeOS::ProcessUnfilteredKeyPressEvent(
393 const ui::KeyEvent
& event
) {
394 const TextInputClient
* prev_client
= GetTextInputClient();
395 DispatchKeyEventPostIME(event
);
397 // We shouldn't dispatch the character anymore if the key event dispatch
398 // caused focus change. For example, in the following scenario,
399 // 1. visit a web page which has a <textarea>.
401 // 3. enable Korean IME, press A, then press Tab to move the focus to the web
403 // We should return here not to send the Tab key event to RWHV.
404 TextInputClient
* client
= GetTextInputClient();
405 if (!client
|| client
!= prev_client
)
408 // If a key event was not filtered by |context_| and |character_composer_|,
409 // then it means the key event didn't generate any result text. So we need
410 // to send corresponding character to the focused text input client.
411 uint16 ch
= event
.GetCharacter();
413 client
->InsertChar(ch
, event
.flags());
416 void InputMethodChromeOS::ProcessInputMethodResult(const ui::KeyEvent
& event
,
418 TextInputClient
* client
= GetTextInputClient();
421 if (result_text_
.length()) {
422 if (handled
&& NeedInsertChar()) {
423 for (base::string16::const_iterator i
= result_text_
.begin();
424 i
!= result_text_
.end(); ++i
) {
425 client
->InsertChar(*i
, event
.flags());
428 client
->InsertText(result_text_
);
429 composing_text_
= false;
433 if (composition_changed_
&& !IsTextInputTypeNone()) {
434 if (composition_
.text
.length()) {
435 composing_text_
= true;
436 client
->SetCompositionText(composition_
);
437 } else if (result_text_
.empty()) {
438 client
->ClearCompositionText();
442 // We should not clear composition text here, as it may belong to the next
443 // composition session.
444 result_text_
.clear();
445 composition_changed_
= false;
448 bool InputMethodChromeOS::NeedInsertChar() const {
449 return GetTextInputClient() &&
450 (IsTextInputTypeNone() ||
451 (!composing_text_
&& result_text_
.length() == 1));
454 bool InputMethodChromeOS::HasInputMethodResult() const {
455 return result_text_
.length() || composition_changed_
;
458 void InputMethodChromeOS::SendFakeProcessKeyEvent(bool pressed
) const {
459 if (!GetTextInputClient())
461 KeyEvent
evt(pressed
? ET_KEY_PRESSED
: ET_KEY_RELEASED
,
462 pressed
? VKEY_PROCESSKEY
: VKEY_UNKNOWN
,
463 EF_IME_FABRICATED_KEY
);
464 DispatchKeyEventPostIME(evt
);
467 void InputMethodChromeOS::AbandonAllPendingKeyEvents() {
468 pending_key_events_
.clear();
471 void InputMethodChromeOS::CommitText(const std::string
& text
) {
475 // We need to receive input method result even if the text input type is
476 // TEXT_INPUT_TYPE_NONE, to make sure we can always send correct
477 // character for each key event to the focused text input client.
478 if (!GetTextInputClient())
481 const base::string16 utf16_text
= base::UTF8ToUTF16(text
);
482 if (utf16_text
.empty())
485 // Append the text to the buffer, because commit signal might be fired
486 // multiple times when processing a key event.
487 result_text_
.append(utf16_text
);
489 // If we are not handling key event, do not bother sending text result if the
490 // focused text input client does not support text input.
491 if (pending_key_events_
.empty() && !IsTextInputTypeNone()) {
492 SendFakeProcessKeyEvent(true);
493 GetTextInputClient()->InsertText(utf16_text
);
494 SendFakeProcessKeyEvent(false);
495 result_text_
.clear();
499 void InputMethodChromeOS::UpdateCompositionText(
500 const chromeos::CompositionText
& text
,
503 if (IsTextInputTypeNone())
506 if (!CanComposeInline()) {
507 chromeos::IMECandidateWindowHandlerInterface
* candidate_window
=
508 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
509 if (candidate_window
)
510 candidate_window
->UpdatePreeditText(text
.text(), cursor_pos
, visible
);
513 // |visible| argument is very confusing. For example, what's the correct
515 // 1. OnUpdatePreeditText() is called with a text and visible == false, then
516 // 2. OnShowPreeditText() is called afterwards.
518 // If it's only for clearing the current preedit text, then why not just use
519 // OnHidePreeditText()?
525 ExtractCompositionText(text
, cursor_pos
, &composition_
);
527 composition_changed_
= true;
529 // In case OnShowPreeditText() is not called.
530 if (composition_
.text
.length())
531 composing_text_
= true;
533 // If we receive a composition text without pending key event, then we need to
534 // send it to the focused text input client directly.
535 if (pending_key_events_
.empty()) {
536 SendFakeProcessKeyEvent(true);
537 GetTextInputClient()->SetCompositionText(composition_
);
538 SendFakeProcessKeyEvent(false);
539 composition_changed_
= false;
540 composition_
.Clear();
544 void InputMethodChromeOS::HidePreeditText() {
545 if (composition_
.text
.empty() || IsTextInputTypeNone())
548 // Intentionally leaves |composing_text_| unchanged.
549 composition_changed_
= true;
550 composition_
.Clear();
552 if (pending_key_events_
.empty()) {
553 TextInputClient
* client
= GetTextInputClient();
554 if (client
&& client
->HasCompositionText()) {
555 SendFakeProcessKeyEvent(true);
556 client
->ClearCompositionText();
557 SendFakeProcessKeyEvent(false);
559 composition_changed_
= false;
563 void InputMethodChromeOS::DeleteSurroundingText(int32 offset
, uint32 length
) {
564 if (!composition_
.text
.empty())
565 return; // do nothing if there is ongoing composition.
567 if (GetTextInputClient()) {
568 uint32 before
= offset
>= 0 ? 0U : static_cast<uint32
>(-1 * offset
);
569 GetTextInputClient()->ExtendSelectionAndDelete(before
, length
- before
);
573 bool InputMethodChromeOS::ExecuteCharacterComposer(const ui::KeyEvent
& event
) {
574 if (!character_composer_
.FilterKeyPress(event
))
577 // CharacterComposer consumed the key event. Update the composition text.
578 chromeos::CompositionText preedit
;
579 preedit
.set_text(character_composer_
.preedit_string());
580 UpdateCompositionText(preedit
, preedit
.text().size(),
581 !preedit
.text().empty());
582 std::string commit_text
=
583 base::UTF16ToUTF8(character_composer_
.composed_character());
584 if (!commit_text
.empty()) {
585 CommitText(commit_text
);
590 void InputMethodChromeOS::ExtractCompositionText(
591 const chromeos::CompositionText
& text
,
592 uint32 cursor_position
,
593 CompositionText
* out_composition
) const {
594 out_composition
->Clear();
595 out_composition
->text
= text
.text();
597 if (out_composition
->text
.empty())
600 // ibus uses character index for cursor position and attribute range, but we
601 // use char16 offset for them. So we need to do conversion here.
602 std::vector
<size_t> char16_offsets
;
603 size_t length
= out_composition
->text
.length();
604 base::i18n::UTF16CharIterator
char_iterator(&out_composition
->text
);
606 char16_offsets
.push_back(char_iterator
.array_pos());
607 } while (char_iterator
.Advance());
609 // The text length in Unicode characters.
610 uint32 char_length
= static_cast<uint32
>(char16_offsets
.size());
611 // Make sure we can convert the value of |char_length| as well.
612 char16_offsets
.push_back(length
);
614 size_t cursor_offset
=
615 char16_offsets
[std::min(char_length
, cursor_position
)];
617 out_composition
->selection
= gfx::Range(cursor_offset
);
619 const std::vector
<chromeos::CompositionText::UnderlineAttribute
>&
620 underline_attributes
= text
.underline_attributes();
621 if (!underline_attributes
.empty()) {
622 for (size_t i
= 0; i
< underline_attributes
.size(); ++i
) {
623 const uint32 start
= underline_attributes
[i
].start_index
;
624 const uint32 end
= underline_attributes
[i
].end_index
;
627 CompositionUnderline
underline(char16_offsets
[start
],
631 SK_ColorTRANSPARENT
);
632 if (underline_attributes
[i
].type
==
633 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_DOUBLE
)
634 underline
.thick
= true;
635 else if (underline_attributes
[i
].type
==
636 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_ERROR
)
637 underline
.color
= SK_ColorRED
;
638 else if (underline_attributes
[i
].type
==
639 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_NONE
)
640 underline
.color
= SK_ColorTRANSPARENT
;
641 out_composition
->underlines
.push_back(underline
);
645 DCHECK(text
.selection_start() <= text
.selection_end());
646 if (text
.selection_start() < text
.selection_end()) {
647 const uint32 start
= text
.selection_start();
648 const uint32 end
= text
.selection_end();
649 CompositionUnderline
underline(char16_offsets
[start
],
653 SK_ColorTRANSPARENT
);
654 out_composition
->underlines
.push_back(underline
);
656 // If the cursor is at start or end of this underline, then we treat
657 // it as the selection range as well, but make sure to set the cursor
658 // position to the selection end.
659 if (underline
.start_offset
== cursor_offset
) {
660 out_composition
->selection
.set_start(underline
.end_offset
);
661 out_composition
->selection
.set_end(cursor_offset
);
662 } else if (underline
.end_offset
== cursor_offset
) {
663 out_composition
->selection
.set_start(underline
.start_offset
);
664 out_composition
->selection
.set_end(cursor_offset
);
668 // Use a black thin underline by default.
669 if (out_composition
->underlines
.empty()) {
670 out_composition
->underlines
.push_back(CompositionUnderline(
671 0, length
, SK_ColorBLACK
, false /* thick */, SK_ColorTRANSPARENT
));
675 bool InputMethodChromeOS::IsNonPasswordInputFieldFocused() {
676 TextInputType type
= GetTextInputType();
677 return (type
!= TEXT_INPUT_TYPE_NONE
) && (type
!= TEXT_INPUT_TYPE_PASSWORD
);
680 bool InputMethodChromeOS::IsInputFieldFocused() {
681 return GetTextInputType() != TEXT_INPUT_TYPE_NONE
;