Add ICU message format support
[chromium-blink-merge.git] / ui / base / ime / input_method_chromeos.cc
blobc624a0fc20bd63dae859f4e05ad50bf2196f79b3
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"
7 #include <algorithm>
8 #include <cstring>
9 #include <set>
10 #include <vector>
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_chromeos.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"
27 namespace {
28 chromeos::IMEEngineHandlerInterface* GetEngine() {
29 return chromeos::IMEBridge::Get()->GetCurrentEngineHandler();
31 } // namespace
33 namespace ui {
35 // InputMethodChromeOS implementation -----------------------------------------
36 InputMethodChromeOS::InputMethodChromeOS(
37 internal::InputMethodDelegate* delegate)
38 : composing_text_(false),
39 composition_changed_(false),
40 handling_key_event_(false),
41 weak_ptr_factory_(this) {
42 SetDelegate(delegate);
43 chromeos::IMEBridge::Get()->SetInputContextHandler(this);
45 UpdateContextFocusState();
48 InputMethodChromeOS::~InputMethodChromeOS() {
49 ConfirmCompositionText();
50 // We are dead, so we need to ask the client to stop relying on us.
51 OnInputMethodChanged();
53 if (chromeos::IMEBridge::Get())
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) {
71 return false;
74 void InputMethodChromeOS::ProcessKeyEventDone(ui::KeyEvent* event,
75 bool is_handled) {
76 DCHECK(event);
77 if (event->type() == ET_KEY_PRESSED) {
78 if (is_handled) {
79 // IME event has a priority to be handled, so that character composer
80 // should be reset.
81 character_composer_.Reset();
82 } else {
83 // If IME does not handle key event, passes keyevent to character composer
84 // to be able to compose complex characters.
85 is_handled = ExecuteCharacterComposer(*event);
89 if (event->type() == ET_KEY_PRESSED || event->type() == ET_KEY_RELEASED)
90 ProcessKeyEventPostIME(event, is_handled);
92 handling_key_event_ = false;
95 void InputMethodChromeOS::DispatchKeyEvent(ui::KeyEvent* event) {
96 DCHECK(event->IsKeyEvent());
97 DCHECK(!(event->flags() & ui::EF_IS_SYNTHESIZED));
98 DCHECK(system_toplevel_window_focused());
100 // For linux_chromeos, the ime keyboard cannot track the caps lock state by
101 // itself, so need to call SetCapsLockEnabled() method to reflect the caps
102 // lock state by the key event.
103 if (!base::SysInfo::IsRunningOnChromeOS()) {
104 chromeos::input_method::InputMethodManager* manager =
105 chromeos::input_method::InputMethodManager::Get();
106 if (manager) {
107 chromeos::input_method::ImeKeyboard* keyboard = manager->GetImeKeyboard();
108 if (keyboard && event->type() == ui::ET_KEY_PRESSED) {
109 bool caps = (event->key_code() == ui::VKEY_CAPITAL)
110 ? !keyboard->CapsLockIsEnabled()
111 : (event->flags() & EF_CAPS_LOCK_DOWN);
112 keyboard->SetCapsLockEnabled(caps);
117 // If |context_| is not usable, then we can only dispatch the key event as is.
118 // We only dispatch the key event to input method when the |context_| is an
119 // normal input field (not a password field).
120 // Note: We need to send the key event to ibus even if the |context_| is not
121 // enabled, so that ibus can have a chance to enable the |context_|.
122 if (!IsNonPasswordInputFieldFocused() || !GetEngine()) {
123 if (event->type() == ET_KEY_PRESSED) {
124 if (ExecuteCharacterComposer(*event)) {
125 // Treating as PostIME event if character composer handles key event and
126 // generates some IME event,
127 ProcessKeyEventPostIME(event, true);
128 return;
130 ProcessUnfilteredKeyPressEvent(event);
131 } else {
132 ignore_result(DispatchKeyEventPostIME(event));
134 return;
137 handling_key_event_ = true;
138 if (GetEngine()->IsInterestedInKeyEvent()) {
139 GetEngine()->ProcessKeyEvent(
140 *event,
141 base::Bind(&InputMethodChromeOS::ProcessKeyEventDone,
142 weak_ptr_factory_.GetWeakPtr(),
143 // Pass the ownership of the new copied event.
144 base::Owned(new ui::KeyEvent(*event))));
145 } else {
146 ProcessKeyEventDone(event, false);
150 void InputMethodChromeOS::OnTextInputTypeChanged(
151 const TextInputClient* client) {
152 if (!IsTextInputClientFocused(client))
153 return;
155 UpdateContextFocusState();
157 chromeos::IMEEngineHandlerInterface* engine = GetEngine();
158 if (engine) {
159 // When focused input client is not changed, a text input type change should
160 // cause blur/focus events to engine.
161 // The focus in to or out from password field should also notify engine.
162 engine->FocusOut();
163 chromeos::IMEEngineHandlerInterface::InputContext context(
164 GetTextInputType(), GetTextInputMode(), GetTextInputFlags());
165 engine->FocusIn(context);
168 InputMethodBase::OnTextInputTypeChanged(client);
171 void InputMethodChromeOS::OnCaretBoundsChanged(const TextInputClient* client) {
172 if (!IsInputFieldFocused() || !IsTextInputClientFocused(client))
173 return;
175 NotifyTextInputCaretBoundsChanged(client);
177 if (!IsNonPasswordInputFieldFocused())
178 return;
180 // The current text input type should not be NONE if |context_| is focused.
181 DCHECK(client == GetTextInputClient());
182 DCHECK(!IsTextInputTypeNone());
183 const gfx::Rect caret_rect = client->GetCaretBounds();
185 gfx::Rect composition_head;
186 std::vector<gfx::Rect> rects;
187 if (client->HasCompositionText()) {
188 uint32 i = 0;
189 gfx::Rect rect;
190 while (client->GetCompositionCharacterBounds(i++, &rect))
191 rects.push_back(rect);
194 // Pepper don't support composition bounds, so fallback to caret bounds to
195 // avoid bad user experience (the IME window moved to upper left corner).
196 // For case of no composition at present, also use caret bounds which is
197 // required by the IME extension for certain features (e.g. physical keyboard
198 // autocorrect).
199 if (rects.empty())
200 rects.push_back(caret_rect);
202 composition_head = rects[0];
203 if (GetEngine())
204 GetEngine()->SetCompositionBounds(rects);
206 chromeos::IMECandidateWindowHandlerInterface* candidate_window =
207 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
208 if (!candidate_window)
209 return;
210 candidate_window->SetCursorBounds(caret_rect, composition_head);
212 gfx::Range text_range;
213 gfx::Range selection_range;
214 base::string16 surrounding_text;
215 if (!client->GetTextRange(&text_range) ||
216 !client->GetTextFromRange(text_range, &surrounding_text) ||
217 !client->GetSelectionRange(&selection_range)) {
218 previous_surrounding_text_.clear();
219 previous_selection_range_ = gfx::Range::InvalidRange();
220 return;
223 if (previous_selection_range_ == selection_range &&
224 previous_surrounding_text_ == surrounding_text)
225 return;
227 previous_selection_range_ = selection_range;
228 previous_surrounding_text_ = surrounding_text;
230 if (!selection_range.IsValid()) {
231 // TODO(nona): Ideally selection_range should not be invalid.
232 // TODO(nona): If javascript changes the focus on page loading, even (0,0)
233 // can not be obtained. Need investigation.
234 return;
237 // Here SetSurroundingText accepts relative position of |surrounding_text|, so
238 // we have to convert |selection_range| from node coordinates to
239 // |surrounding_text| coordinates.
240 if (!GetEngine())
241 return;
242 GetEngine()->SetSurroundingText(base::UTF16ToUTF8(surrounding_text),
243 selection_range.start() - text_range.start(),
244 selection_range.end() - text_range.start());
247 void InputMethodChromeOS::CancelComposition(const TextInputClient* client) {
248 if (IsNonPasswordInputFieldFocused() && IsTextInputClientFocused(client))
249 ResetContext();
252 void InputMethodChromeOS::OnInputLocaleChanged() {
253 // Not supported.
256 std::string InputMethodChromeOS::GetInputLocale() {
257 // Not supported.
258 return "";
261 bool InputMethodChromeOS::IsCandidatePopupOpen() const {
262 // TODO(yukishiino): Implement this method.
263 return false;
266 void InputMethodChromeOS::OnWillChangeFocusedClient(
267 TextInputClient* focused_before,
268 TextInputClient* focused) {
269 ConfirmCompositionText();
271 if (GetEngine())
272 GetEngine()->FocusOut();
275 void InputMethodChromeOS::OnDidChangeFocusedClient(
276 TextInputClient* focused_before,
277 TextInputClient* focused) {
278 // Force to update the input type since client's TextInputStateChanged()
279 // function might not be called if text input types before the client loses
280 // focus and after it acquires focus again are the same.
281 UpdateContextFocusState();
283 if (GetEngine()) {
284 chromeos::IMEEngineHandlerInterface::InputContext context(
285 GetTextInputType(), GetTextInputMode(), GetTextInputFlags());
286 GetEngine()->FocusIn(context);
290 void InputMethodChromeOS::ConfirmCompositionText() {
291 TextInputClient* client = GetTextInputClient();
292 if (client && client->HasCompositionText())
293 client->ConfirmCompositionText();
295 ResetContext();
298 void InputMethodChromeOS::ResetContext() {
299 if (!IsNonPasswordInputFieldFocused() || !GetTextInputClient())
300 return;
302 DCHECK(system_toplevel_window_focused());
304 composition_.Clear();
305 result_text_.clear();
306 composing_text_ = false;
307 composition_changed_ = false;
309 // This function runs asynchronously.
310 // Note: some input method engines may not support reset method, such as
311 // ibus-anthy. But as we control all input method engines by ourselves, we can
312 // make sure that all of the engines we are using support it correctly.
313 if (GetEngine())
314 GetEngine()->Reset();
316 character_composer_.Reset();
319 void InputMethodChromeOS::UpdateContextFocusState() {
320 ResetContext();
321 OnInputMethodChanged();
323 // Propagate the focus event to the candidate window handler which also
324 // manages the input method mode indicator.
325 chromeos::IMECandidateWindowHandlerInterface* candidate_window =
326 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
327 if (candidate_window)
328 candidate_window->FocusStateChanged(IsNonPasswordInputFieldFocused());
330 chromeos::IMEEngineHandlerInterface::InputContext context(
331 GetTextInputType(), GetTextInputMode(), GetTextInputFlags());
332 chromeos::IMEBridge::Get()->SetCurrentInputContext(context);
334 if (!IsTextInputTypeNone())
335 OnCaretBoundsChanged(GetTextInputClient());
338 void InputMethodChromeOS::ProcessKeyEventPostIME(ui::KeyEvent* event,
339 bool handled) {
340 TextInputClient* client = GetTextInputClient();
341 if (!client) {
342 // As ibus works asynchronously, there is a chance that the focused client
343 // loses focus before this method gets called.
344 ignore_result(DispatchKeyEventPostIME(event));
345 return;
348 if (event->type() == ET_KEY_PRESSED && handled) {
349 ProcessFilteredKeyPressEvent(event);
350 if (event->stopped_propagation()) {
351 ResetContext();
352 return;
356 // In case the focus was changed by the key event. The |context_| should have
357 // been reset when the focused window changed.
358 if (client != GetTextInputClient())
359 return;
361 if (HasInputMethodResult())
362 ProcessInputMethodResult(event, handled);
364 // In case the focus was changed when sending input method results to the
365 // focused window.
366 if (client != GetTextInputClient())
367 return;
369 if (handled)
370 return; // IME handled the key event. do not forward.
372 if (event->type() == ET_KEY_PRESSED)
373 ProcessUnfilteredKeyPressEvent(event);
374 else if (event->type() == ET_KEY_RELEASED)
375 ignore_result(DispatchKeyEventPostIME(event));
378 void InputMethodChromeOS::ProcessFilteredKeyPressEvent(ui::KeyEvent* event) {
379 if (NeedInsertChar()) {
380 ignore_result(DispatchKeyEventPostIME(event));
381 return;
383 ui::KeyEvent fabricated_event(ET_KEY_PRESSED,
384 VKEY_PROCESSKEY,
385 event->flags());
386 ignore_result(DispatchKeyEventPostIME(&fabricated_event));
387 if (fabricated_event.stopped_propagation())
388 event->StopPropagation();
391 void InputMethodChromeOS::ProcessUnfilteredKeyPressEvent(
392 ui::KeyEvent* event) {
393 const TextInputClient* prev_client = GetTextInputClient();
394 ignore_result(DispatchKeyEventPostIME(event));
395 if (event->stopped_propagation()) {
396 ResetContext();
397 return;
400 // We shouldn't dispatch the character anymore if the key event dispatch
401 // caused focus change. For example, in the following scenario,
402 // 1. visit a web page which has a <textarea>.
403 // 2. click Omnibox.
404 // 3. enable Korean IME, press A, then press Tab to move the focus to the web
405 // page.
406 // We should return here not to send the Tab key event to RWHV.
407 TextInputClient* client = GetTextInputClient();
408 if (!client || client != prev_client)
409 return;
411 // If a key event was not filtered by |context_| and |character_composer_|,
412 // then it means the key event didn't generate any result text. So we need
413 // to send corresponding character to the focused text input client.
414 uint16 ch = event->GetCharacter();
415 if (ch)
416 client->InsertChar(ch, event->flags());
419 void InputMethodChromeOS::ProcessInputMethodResult(ui::KeyEvent* event,
420 bool handled) {
421 TextInputClient* client = GetTextInputClient();
422 DCHECK(client);
424 if (result_text_.length()) {
425 if (handled && NeedInsertChar()) {
426 for (base::string16::const_iterator i = result_text_.begin();
427 i != result_text_.end(); ++i) {
428 client->InsertChar(*i, event->flags());
430 } else {
431 client->InsertText(result_text_);
432 composing_text_ = false;
436 if (composition_changed_ && !IsTextInputTypeNone()) {
437 if (composition_.text.length()) {
438 composing_text_ = true;
439 client->SetCompositionText(composition_);
440 } else if (result_text_.empty()) {
441 client->ClearCompositionText();
445 // We should not clear composition text here, as it may belong to the next
446 // composition session.
447 result_text_.clear();
448 composition_changed_ = false;
451 bool InputMethodChromeOS::NeedInsertChar() const {
452 return GetTextInputClient() &&
453 (IsTextInputTypeNone() ||
454 (!composing_text_ && result_text_.length() == 1));
457 bool InputMethodChromeOS::HasInputMethodResult() const {
458 return result_text_.length() || composition_changed_;
461 bool InputMethodChromeOS::SendFakeProcessKeyEvent(bool pressed) const {
462 KeyEvent evt(pressed ? ET_KEY_PRESSED : ET_KEY_RELEASED,
463 pressed ? VKEY_PROCESSKEY : VKEY_UNKNOWN,
464 EF_IME_FABRICATED_KEY);
465 ignore_result(DispatchKeyEventPostIME(&evt));
466 return evt.stopped_propagation();
469 void InputMethodChromeOS::CommitText(const std::string& text) {
470 if (text.empty())
471 return;
473 // We need to receive input method result even if the text input type is
474 // TEXT_INPUT_TYPE_NONE, to make sure we can always send correct
475 // character for each key event to the focused text input client.
476 if (!GetTextInputClient())
477 return;
479 const base::string16 utf16_text = base::UTF8ToUTF16(text);
480 if (utf16_text.empty())
481 return;
483 // Append the text to the buffer, because commit signal might be fired
484 // multiple times when processing a key event.
485 result_text_.append(utf16_text);
487 // If we are not handling key event, do not bother sending text result if the
488 // focused text input client does not support text input.
489 if (!handling_key_event_ && !IsTextInputTypeNone()) {
490 if (!SendFakeProcessKeyEvent(true))
491 GetTextInputClient()->InsertText(utf16_text);
492 SendFakeProcessKeyEvent(false);
493 result_text_.clear();
497 void InputMethodChromeOS::UpdateCompositionText(
498 const chromeos::CompositionText& text,
499 uint32 cursor_pos,
500 bool visible) {
501 if (IsTextInputTypeNone())
502 return;
504 if (!CanComposeInline()) {
505 chromeos::IMECandidateWindowHandlerInterface* candidate_window =
506 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
507 if (candidate_window)
508 candidate_window->UpdatePreeditText(text.text(), cursor_pos, visible);
511 // |visible| argument is very confusing. For example, what's the correct
512 // behavior when:
513 // 1. OnUpdatePreeditText() is called with a text and visible == false, then
514 // 2. OnShowPreeditText() is called afterwards.
516 // If it's only for clearing the current preedit text, then why not just use
517 // OnHidePreeditText()?
518 if (!visible) {
519 HidePreeditText();
520 return;
523 ExtractCompositionText(text, cursor_pos, &composition_);
525 composition_changed_ = true;
527 // In case OnShowPreeditText() is not called.
528 if (composition_.text.length())
529 composing_text_ = true;
531 if (!handling_key_event_) {
532 // If we receive a composition text without pending key event, then we need
533 // to send it to the focused text input client directly.
534 if (!SendFakeProcessKeyEvent(true))
535 GetTextInputClient()->SetCompositionText(composition_);
536 SendFakeProcessKeyEvent(false);
537 composition_changed_ = false;
538 composition_.Clear();
542 void InputMethodChromeOS::HidePreeditText() {
543 if (composition_.text.empty() || IsTextInputTypeNone())
544 return;
546 // Intentionally leaves |composing_text_| unchanged.
547 composition_changed_ = true;
548 composition_.Clear();
550 if (!handling_key_event_) {
551 TextInputClient* client = GetTextInputClient();
552 if (client && client->HasCompositionText()) {
553 if (!SendFakeProcessKeyEvent(true))
554 client->ClearCompositionText();
555 SendFakeProcessKeyEvent(false);
557 composition_changed_ = false;
561 void InputMethodChromeOS::DeleteSurroundingText(int32 offset, uint32 length) {
562 if (!composition_.text.empty())
563 return; // do nothing if there is ongoing composition.
565 if (GetTextInputClient()) {
566 uint32 before = offset >= 0 ? 0U : static_cast<uint32>(-1 * offset);
567 GetTextInputClient()->ExtendSelectionAndDelete(before, length - before);
571 bool InputMethodChromeOS::ExecuteCharacterComposer(const ui::KeyEvent& event) {
572 if (!character_composer_.FilterKeyPress(event))
573 return false;
575 // CharacterComposer consumed the key event. Update the composition text.
576 chromeos::CompositionText preedit;
577 preedit.set_text(character_composer_.preedit_string());
578 UpdateCompositionText(preedit, preedit.text().size(),
579 !preedit.text().empty());
580 std::string commit_text =
581 base::UTF16ToUTF8(character_composer_.composed_character());
582 if (!commit_text.empty()) {
583 CommitText(commit_text);
585 return true;
588 void InputMethodChromeOS::ExtractCompositionText(
589 const chromeos::CompositionText& text,
590 uint32 cursor_position,
591 CompositionText* out_composition) const {
592 out_composition->Clear();
593 out_composition->text = text.text();
595 if (out_composition->text.empty())
596 return;
598 // ibus uses character index for cursor position and attribute range, but we
599 // use char16 offset for them. So we need to do conversion here.
600 std::vector<size_t> char16_offsets;
601 size_t length = out_composition->text.length();
602 base::i18n::UTF16CharIterator char_iterator(&out_composition->text);
603 do {
604 char16_offsets.push_back(char_iterator.array_pos());
605 } while (char_iterator.Advance());
607 // The text length in Unicode characters.
608 uint32 char_length = static_cast<uint32>(char16_offsets.size());
609 // Make sure we can convert the value of |char_length| as well.
610 char16_offsets.push_back(length);
612 size_t cursor_offset =
613 char16_offsets[std::min(char_length, cursor_position)];
615 out_composition->selection = gfx::Range(cursor_offset);
617 const std::vector<chromeos::CompositionText::UnderlineAttribute>&
618 underline_attributes = text.underline_attributes();
619 if (!underline_attributes.empty()) {
620 for (size_t i = 0; i < underline_attributes.size(); ++i) {
621 const uint32 start = underline_attributes[i].start_index;
622 const uint32 end = underline_attributes[i].end_index;
623 if (start >= end)
624 continue;
625 CompositionUnderline underline(char16_offsets[start],
626 char16_offsets[end],
627 SK_ColorBLACK,
628 false /* thick */,
629 SK_ColorTRANSPARENT);
630 if (underline_attributes[i].type ==
631 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_DOUBLE)
632 underline.thick = true;
633 else if (underline_attributes[i].type ==
634 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_ERROR)
635 underline.color = SK_ColorRED;
636 else if (underline_attributes[i].type ==
637 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_NONE)
638 underline.color = SK_ColorTRANSPARENT;
639 out_composition->underlines.push_back(underline);
643 DCHECK(text.selection_start() <= text.selection_end());
644 if (text.selection_start() < text.selection_end()) {
645 const uint32 start = text.selection_start();
646 const uint32 end = text.selection_end();
647 CompositionUnderline underline(char16_offsets[start],
648 char16_offsets[end],
649 SK_ColorBLACK,
650 true /* thick */,
651 SK_ColorTRANSPARENT);
652 out_composition->underlines.push_back(underline);
654 // If the cursor is at start or end of this underline, then we treat
655 // it as the selection range as well, but make sure to set the cursor
656 // position to the selection end.
657 if (underline.start_offset == cursor_offset) {
658 out_composition->selection.set_start(underline.end_offset);
659 out_composition->selection.set_end(cursor_offset);
660 } else if (underline.end_offset == cursor_offset) {
661 out_composition->selection.set_start(underline.start_offset);
662 out_composition->selection.set_end(cursor_offset);
666 // Use a black thin underline by default.
667 if (out_composition->underlines.empty()) {
668 out_composition->underlines.push_back(CompositionUnderline(
669 0, length, SK_ColorBLACK, false /* thick */, SK_ColorTRANSPARENT));
673 bool InputMethodChromeOS::IsNonPasswordInputFieldFocused() {
674 TextInputType type = GetTextInputType();
675 return (type != TEXT_INPUT_TYPE_NONE) && (type != TEXT_INPUT_TYPE_PASSWORD);
678 bool InputMethodChromeOS::IsInputFieldFocused() {
679 return GetTextInputType() != TEXT_INPUT_TYPE_NONE;
682 } // namespace ui