Adding wrapper class WKBackForwardListItemHolder
[chromium-blink-merge.git] / ui / base / ime / input_method_chromeos.cc
blob47c9c1678e6d34ecd3380e9e43f12acc520565e9
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(const 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 bool InputMethodChromeOS::DispatchKeyEvent(const 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 true;
130 ProcessUnfilteredKeyPressEvent(event);
131 } else {
132 DispatchKeyEventPostIME(event);
134 return true;
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);
148 return true;
151 void InputMethodChromeOS::OnTextInputTypeChanged(
152 const TextInputClient* client) {
153 if (!IsTextInputClientFocused(client))
154 return;
156 UpdateContextFocusState();
158 chromeos::IMEEngineHandlerInterface* engine = GetEngine();
159 if (engine) {
160 // When focused input client is not changed, a text input type change should
161 // cause blur/focus events to engine.
162 // The focus in to or out from password field should also notify engine.
163 engine->FocusOut();
164 chromeos::IMEEngineHandlerInterface::InputContext context(
165 GetTextInputType(), GetTextInputMode(), GetTextInputFlags());
166 engine->FocusIn(context);
169 InputMethodBase::OnTextInputTypeChanged(client);
172 void InputMethodChromeOS::OnCaretBoundsChanged(const TextInputClient* client) {
173 if (!IsInputFieldFocused() || !IsTextInputClientFocused(client))
174 return;
176 NotifyTextInputCaretBoundsChanged(client);
178 if (!IsNonPasswordInputFieldFocused())
179 return;
181 // The current text input type should not be NONE if |context_| is focused.
182 DCHECK(client == GetTextInputClient());
183 DCHECK(!IsTextInputTypeNone());
184 const gfx::Rect caret_rect = client->GetCaretBounds();
186 gfx::Rect composition_head;
187 std::vector<gfx::Rect> rects;
188 if (client->HasCompositionText()) {
189 uint32 i = 0;
190 gfx::Rect rect;
191 while (client->GetCompositionCharacterBounds(i++, &rect))
192 rects.push_back(rect);
195 // Pepper don't support composition bounds, so fallback to caret bounds to
196 // avoid bad user experience (the IME window moved to upper left corner).
197 // For case of no composition at present, also use caret bounds which is
198 // required by the IME extension for certain features (e.g. physical keyboard
199 // autocorrect).
200 if (rects.empty())
201 rects.push_back(caret_rect);
203 composition_head = rects[0];
204 if (GetEngine())
205 GetEngine()->SetCompositionBounds(rects);
207 chromeos::IMECandidateWindowHandlerInterface* candidate_window =
208 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
209 if (!candidate_window)
210 return;
211 candidate_window->SetCursorBounds(caret_rect, composition_head);
213 gfx::Range text_range;
214 gfx::Range selection_range;
215 base::string16 surrounding_text;
216 if (!client->GetTextRange(&text_range) ||
217 !client->GetTextFromRange(text_range, &surrounding_text) ||
218 !client->GetSelectionRange(&selection_range)) {
219 previous_surrounding_text_.clear();
220 previous_selection_range_ = gfx::Range::InvalidRange();
221 return;
224 if (previous_selection_range_ == selection_range &&
225 previous_surrounding_text_ == surrounding_text)
226 return;
228 previous_selection_range_ = selection_range;
229 previous_surrounding_text_ = surrounding_text;
231 if (!selection_range.IsValid()) {
232 // TODO(nona): Ideally selection_range should not be invalid.
233 // TODO(nona): If javascript changes the focus on page loading, even (0,0)
234 // can not be obtained. Need investigation.
235 return;
238 // Here SetSurroundingText accepts relative position of |surrounding_text|, so
239 // we have to convert |selection_range| from node coordinates to
240 // |surrounding_text| coordinates.
241 if (!GetEngine())
242 return;
243 GetEngine()->SetSurroundingText(base::UTF16ToUTF8(surrounding_text),
244 selection_range.start() - text_range.start(),
245 selection_range.end() - text_range.start());
248 void InputMethodChromeOS::CancelComposition(const TextInputClient* client) {
249 if (IsNonPasswordInputFieldFocused() && IsTextInputClientFocused(client))
250 ResetContext();
253 void InputMethodChromeOS::OnInputLocaleChanged() {
254 // Not supported.
257 std::string InputMethodChromeOS::GetInputLocale() {
258 // Not supported.
259 return "";
262 bool InputMethodChromeOS::IsCandidatePopupOpen() const {
263 // TODO(yukishiino): Implement this method.
264 return false;
267 void InputMethodChromeOS::OnWillChangeFocusedClient(
268 TextInputClient* focused_before,
269 TextInputClient* focused) {
270 ConfirmCompositionText();
272 if (GetEngine())
273 GetEngine()->FocusOut();
276 void InputMethodChromeOS::OnDidChangeFocusedClient(
277 TextInputClient* focused_before,
278 TextInputClient* focused) {
279 // Force to update the input type since client's TextInputStateChanged()
280 // function might not be called if text input types before the client loses
281 // focus and after it acquires focus again are the same.
282 UpdateContextFocusState();
284 if (GetEngine()) {
285 chromeos::IMEEngineHandlerInterface::InputContext context(
286 GetTextInputType(), GetTextInputMode(), GetTextInputFlags());
287 GetEngine()->FocusIn(context);
291 void InputMethodChromeOS::ConfirmCompositionText() {
292 TextInputClient* client = GetTextInputClient();
293 if (client && client->HasCompositionText())
294 client->ConfirmCompositionText();
296 ResetContext();
299 void InputMethodChromeOS::ResetContext() {
300 if (!IsNonPasswordInputFieldFocused() || !GetTextInputClient())
301 return;
303 DCHECK(system_toplevel_window_focused());
305 composition_.Clear();
306 result_text_.clear();
307 composing_text_ = false;
308 composition_changed_ = false;
310 // This function runs asynchronously.
311 // Note: some input method engines may not support reset method, such as
312 // ibus-anthy. But as we control all input method engines by ourselves, we can
313 // make sure that all of the engines we are using support it correctly.
314 if (GetEngine())
315 GetEngine()->Reset();
317 character_composer_.Reset();
320 void InputMethodChromeOS::UpdateContextFocusState() {
321 ResetContext();
322 OnInputMethodChanged();
324 // Propagate the focus event to the candidate window handler which also
325 // manages the input method mode indicator.
326 chromeos::IMECandidateWindowHandlerInterface* candidate_window =
327 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
328 if (candidate_window)
329 candidate_window->FocusStateChanged(IsNonPasswordInputFieldFocused());
331 chromeos::IMEEngineHandlerInterface::InputContext context(
332 GetTextInputType(), GetTextInputMode(), GetTextInputFlags());
333 chromeos::IMEBridge::Get()->SetCurrentInputContext(context);
335 if (!IsTextInputTypeNone())
336 OnCaretBoundsChanged(GetTextInputClient());
339 void InputMethodChromeOS::ProcessKeyEventPostIME(const ui::KeyEvent& event,
340 bool handled) {
341 TextInputClient* client = GetTextInputClient();
342 if (!client) {
343 // As ibus works asynchronously, there is a chance that the focused client
344 // loses focus before this method gets called.
345 DispatchKeyEventPostIME(event);
346 return;
349 if (event.type() == ET_KEY_PRESSED && handled) {
350 if (ProcessFilteredKeyPressEvent(event)) {
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 DispatchKeyEventPostIME(event);
378 bool InputMethodChromeOS::ProcessFilteredKeyPressEvent(
379 const ui::KeyEvent& event) {
380 if (NeedInsertChar())
381 return DispatchKeyEventPostIME(event);
382 const ui::KeyEvent fabricated_event(ET_KEY_PRESSED,
383 VKEY_PROCESSKEY,
384 event.flags());
385 return DispatchKeyEventPostIME(fabricated_event);
388 void InputMethodChromeOS::ProcessUnfilteredKeyPressEvent(
389 const ui::KeyEvent& event) {
390 const TextInputClient* prev_client = GetTextInputClient();
391 if (DispatchKeyEventPostIME(event)) {
392 ResetContext();
393 return;
396 // We shouldn't dispatch the character anymore if the key event dispatch
397 // caused focus change. For example, in the following scenario,
398 // 1. visit a web page which has a <textarea>.
399 // 2. click Omnibox.
400 // 3. enable Korean IME, press A, then press Tab to move the focus to the web
401 // page.
402 // We should return here not to send the Tab key event to RWHV.
403 TextInputClient* client = GetTextInputClient();
404 if (!client || client != prev_client)
405 return;
407 // If a key event was not filtered by |context_| and |character_composer_|,
408 // then it means the key event didn't generate any result text. So we need
409 // to send corresponding character to the focused text input client.
410 uint16 ch = event.GetCharacter();
411 if (ch)
412 client->InsertChar(ch, event.flags());
415 void InputMethodChromeOS::ProcessInputMethodResult(const ui::KeyEvent& event,
416 bool handled) {
417 TextInputClient* client = GetTextInputClient();
418 DCHECK(client);
420 if (result_text_.length()) {
421 if (handled && NeedInsertChar()) {
422 for (base::string16::const_iterator i = result_text_.begin();
423 i != result_text_.end(); ++i) {
424 client->InsertChar(*i, event.flags());
426 } else {
427 client->InsertText(result_text_);
428 composing_text_ = false;
432 if (composition_changed_ && !IsTextInputTypeNone()) {
433 if (composition_.text.length()) {
434 composing_text_ = true;
435 client->SetCompositionText(composition_);
436 } else if (result_text_.empty()) {
437 client->ClearCompositionText();
441 // We should not clear composition text here, as it may belong to the next
442 // composition session.
443 result_text_.clear();
444 composition_changed_ = false;
447 bool InputMethodChromeOS::NeedInsertChar() const {
448 return GetTextInputClient() &&
449 (IsTextInputTypeNone() ||
450 (!composing_text_ && result_text_.length() == 1));
453 bool InputMethodChromeOS::HasInputMethodResult() const {
454 return result_text_.length() || composition_changed_;
457 void InputMethodChromeOS::SendFakeProcessKeyEvent(bool pressed) const {
458 if (!GetTextInputClient())
459 return;
460 KeyEvent evt(pressed ? ET_KEY_PRESSED : ET_KEY_RELEASED,
461 pressed ? VKEY_PROCESSKEY : VKEY_UNKNOWN,
462 EF_IME_FABRICATED_KEY);
463 DispatchKeyEventPostIME(evt);
466 void InputMethodChromeOS::CommitText(const std::string& text) {
467 if (text.empty())
468 return;
470 // We need to receive input method result even if the text input type is
471 // TEXT_INPUT_TYPE_NONE, to make sure we can always send correct
472 // character for each key event to the focused text input client.
473 if (!GetTextInputClient())
474 return;
476 const base::string16 utf16_text = base::UTF8ToUTF16(text);
477 if (utf16_text.empty())
478 return;
480 // Append the text to the buffer, because commit signal might be fired
481 // multiple times when processing a key event.
482 result_text_.append(utf16_text);
484 // If we are not handling key event, do not bother sending text result if the
485 // focused text input client does not support text input.
486 if (!handling_key_event_ && !IsTextInputTypeNone()) {
487 SendFakeProcessKeyEvent(true);
488 GetTextInputClient()->InsertText(utf16_text);
489 SendFakeProcessKeyEvent(false);
490 result_text_.clear();
494 void InputMethodChromeOS::UpdateCompositionText(
495 const chromeos::CompositionText& text,
496 uint32 cursor_pos,
497 bool visible) {
498 if (IsTextInputTypeNone())
499 return;
501 if (!CanComposeInline()) {
502 chromeos::IMECandidateWindowHandlerInterface* candidate_window =
503 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
504 if (candidate_window)
505 candidate_window->UpdatePreeditText(text.text(), cursor_pos, visible);
508 // |visible| argument is very confusing. For example, what's the correct
509 // behavior when:
510 // 1. OnUpdatePreeditText() is called with a text and visible == false, then
511 // 2. OnShowPreeditText() is called afterwards.
513 // If it's only for clearing the current preedit text, then why not just use
514 // OnHidePreeditText()?
515 if (!visible) {
516 HidePreeditText();
517 return;
520 ExtractCompositionText(text, cursor_pos, &composition_);
522 composition_changed_ = true;
524 // In case OnShowPreeditText() is not called.
525 if (composition_.text.length())
526 composing_text_ = true;
528 if (!handling_key_event_) {
529 // If we receive a composition text without pending key event, then we need
530 // to send it to the focused text input client directly.
531 SendFakeProcessKeyEvent(true);
532 GetTextInputClient()->SetCompositionText(composition_);
533 SendFakeProcessKeyEvent(false);
534 composition_changed_ = false;
535 composition_.Clear();
539 void InputMethodChromeOS::HidePreeditText() {
540 if (composition_.text.empty() || IsTextInputTypeNone())
541 return;
543 // Intentionally leaves |composing_text_| unchanged.
544 composition_changed_ = true;
545 composition_.Clear();
547 if (!handling_key_event_) {
548 TextInputClient* client = GetTextInputClient();
549 if (client && client->HasCompositionText()) {
550 SendFakeProcessKeyEvent(true);
551 client->ClearCompositionText();
552 SendFakeProcessKeyEvent(false);
554 composition_changed_ = false;
558 void InputMethodChromeOS::DeleteSurroundingText(int32 offset, uint32 length) {
559 if (!composition_.text.empty())
560 return; // do nothing if there is ongoing composition.
562 if (GetTextInputClient()) {
563 uint32 before = offset >= 0 ? 0U : static_cast<uint32>(-1 * offset);
564 GetTextInputClient()->ExtendSelectionAndDelete(before, length - before);
568 bool InputMethodChromeOS::ExecuteCharacterComposer(const ui::KeyEvent& event) {
569 if (!character_composer_.FilterKeyPress(event))
570 return false;
572 // CharacterComposer consumed the key event. Update the composition text.
573 chromeos::CompositionText preedit;
574 preedit.set_text(character_composer_.preedit_string());
575 UpdateCompositionText(preedit, preedit.text().size(),
576 !preedit.text().empty());
577 std::string commit_text =
578 base::UTF16ToUTF8(character_composer_.composed_character());
579 if (!commit_text.empty()) {
580 CommitText(commit_text);
582 return true;
585 void InputMethodChromeOS::ExtractCompositionText(
586 const chromeos::CompositionText& text,
587 uint32 cursor_position,
588 CompositionText* out_composition) const {
589 out_composition->Clear();
590 out_composition->text = text.text();
592 if (out_composition->text.empty())
593 return;
595 // ibus uses character index for cursor position and attribute range, but we
596 // use char16 offset for them. So we need to do conversion here.
597 std::vector<size_t> char16_offsets;
598 size_t length = out_composition->text.length();
599 base::i18n::UTF16CharIterator char_iterator(&out_composition->text);
600 do {
601 char16_offsets.push_back(char_iterator.array_pos());
602 } while (char_iterator.Advance());
604 // The text length in Unicode characters.
605 uint32 char_length = static_cast<uint32>(char16_offsets.size());
606 // Make sure we can convert the value of |char_length| as well.
607 char16_offsets.push_back(length);
609 size_t cursor_offset =
610 char16_offsets[std::min(char_length, cursor_position)];
612 out_composition->selection = gfx::Range(cursor_offset);
614 const std::vector<chromeos::CompositionText::UnderlineAttribute>&
615 underline_attributes = text.underline_attributes();
616 if (!underline_attributes.empty()) {
617 for (size_t i = 0; i < underline_attributes.size(); ++i) {
618 const uint32 start = underline_attributes[i].start_index;
619 const uint32 end = underline_attributes[i].end_index;
620 if (start >= end)
621 continue;
622 CompositionUnderline underline(char16_offsets[start],
623 char16_offsets[end],
624 SK_ColorBLACK,
625 false /* thick */,
626 SK_ColorTRANSPARENT);
627 if (underline_attributes[i].type ==
628 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_DOUBLE)
629 underline.thick = true;
630 else if (underline_attributes[i].type ==
631 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_ERROR)
632 underline.color = SK_ColorRED;
633 else if (underline_attributes[i].type ==
634 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_NONE)
635 underline.color = SK_ColorTRANSPARENT;
636 out_composition->underlines.push_back(underline);
640 DCHECK(text.selection_start() <= text.selection_end());
641 if (text.selection_start() < text.selection_end()) {
642 const uint32 start = text.selection_start();
643 const uint32 end = text.selection_end();
644 CompositionUnderline underline(char16_offsets[start],
645 char16_offsets[end],
646 SK_ColorBLACK,
647 true /* thick */,
648 SK_ColorTRANSPARENT);
649 out_composition->underlines.push_back(underline);
651 // If the cursor is at start or end of this underline, then we treat
652 // it as the selection range as well, but make sure to set the cursor
653 // position to the selection end.
654 if (underline.start_offset == cursor_offset) {
655 out_composition->selection.set_start(underline.end_offset);
656 out_composition->selection.set_end(cursor_offset);
657 } else if (underline.end_offset == cursor_offset) {
658 out_composition->selection.set_start(underline.start_offset);
659 out_composition->selection.set_end(cursor_offset);
663 // Use a black thin underline by default.
664 if (out_composition->underlines.empty()) {
665 out_composition->underlines.push_back(CompositionUnderline(
666 0, length, SK_ColorBLACK, false /* thick */, SK_ColorTRANSPARENT));
670 bool InputMethodChromeOS::IsNonPasswordInputFieldFocused() {
671 TextInputType type = GetTextInputType();
672 return (type != TEXT_INPUT_TYPE_NONE) && (type != TEXT_INPUT_TYPE_PASSWORD);
675 bool InputMethodChromeOS::IsInputFieldFocused() {
676 return GetTextInputType() != TEXT_INPUT_TYPE_NONE;
679 } // namespace ui