Revert of Fix missing GN dependencies. (patchset #4 id:60001 of https://codereview...
[chromium-blink-merge.git] / ui / base / ime / input_method_chromeos.cc
blob1a4b7e60a66d8d7e79fe9a776f7d8ab392d23772
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.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 chromeos::IMEBridge::Get()->SetInputContextHandler(NULL);
56 void InputMethodChromeOS::OnFocus() {
57 InputMethodBase::OnFocus();
58 OnTextInputTypeChanged(GetTextInputClient());
61 void InputMethodChromeOS::OnBlur() {
62 ConfirmCompositionText();
63 InputMethodBase::OnBlur();
64 OnTextInputTypeChanged(GetTextInputClient());
67 bool InputMethodChromeOS::OnUntranslatedIMEMessage(
68 const base::NativeEvent& event,
69 NativeEventResult* result) {
70 return false;
73 void InputMethodChromeOS::ProcessKeyEventDone(const ui::KeyEvent* event,
74 bool is_handled) {
75 DCHECK(event);
76 if (event->type() == ET_KEY_PRESSED) {
77 if (is_handled) {
78 // IME event has a priority to be handled, so that character composer
79 // should be reset.
80 character_composer_.Reset();
81 } else {
82 // If IME does not handle key event, passes keyevent to character composer
83 // to be able to compose complex characters.
84 is_handled = ExecuteCharacterComposer(*event);
88 if (event->type() == ET_KEY_PRESSED || event->type() == ET_KEY_RELEASED)
89 ProcessKeyEventPostIME(*event, is_handled);
91 handling_key_event_ = false;
94 bool InputMethodChromeOS::DispatchKeyEvent(const ui::KeyEvent& event) {
95 DCHECK(event.type() == ET_KEY_PRESSED || event.type() == ET_KEY_RELEASED);
96 DCHECK(system_toplevel_window_focused());
98 // For linux_chromeos, the ime keyboard cannot track the caps lock state by
99 // itself, so need to call SetCapsLockEnabled() method to reflect the caps
100 // lock state by the key event.
101 if (!base::SysInfo::IsRunningOnChromeOS()) {
102 chromeos::input_method::InputMethodManager* manager =
103 chromeos::input_method::InputMethodManager::Get();
104 if (manager) {
105 chromeos::input_method::ImeKeyboard* keyboard = manager->GetImeKeyboard();
106 if (keyboard && event.type() == ui::ET_KEY_PRESSED) {
107 bool caps = (event.key_code() == ui::VKEY_CAPITAL)
108 ? !keyboard->CapsLockIsEnabled()
109 : (event.flags() & EF_CAPS_LOCK_DOWN);
110 keyboard->SetCapsLockEnabled(caps);
115 handling_key_event_ = true;
116 // If |context_| is not usable, then we can only dispatch the key event as is.
117 // We only dispatch the key event to input method when the |context_| is an
118 // normal input field (not a password field).
119 // Note: We need to send the key event to ibus even if the |context_| is not
120 // enabled, so that ibus can have a chance to enable the |context_|.
121 if (!IsNonPasswordInputFieldFocused() || !GetEngine()) {
122 if (event.type() == ET_KEY_PRESSED) {
123 if (ExecuteCharacterComposer(event)) {
124 // Treating as PostIME event if character composer handles key event and
125 // generates some IME event,
126 ProcessKeyEventPostIME(event, true);
127 return true;
129 ProcessUnfilteredKeyPressEvent(event);
130 } else {
131 DispatchKeyEventPostIME(event);
133 return true;
136 if (GetEngine()->IsInterestedInKeyEvent()) {
137 GetEngine()->ProcessKeyEvent(
138 event,
139 base::Bind(&InputMethodChromeOS::ProcessKeyEventDone,
140 weak_ptr_factory_.GetWeakPtr(),
141 // Pass the ownership of the new copied event.
142 base::Owned(new ui::KeyEvent(event))));
143 } else {
144 ProcessKeyEventDone(&event, false);
146 return true;
149 void InputMethodChromeOS::OnTextInputTypeChanged(
150 const TextInputClient* client) {
151 if (!IsTextInputClientFocused(client))
152 return;
154 UpdateContextFocusState();
156 chromeos::IMEEngineHandlerInterface* engine = GetEngine();
157 if (engine) {
158 // When focused input client is not changed, a text input type change should
159 // cause blur/focus events to engine.
160 // The focus in to or out from password field should also notify engine.
161 engine->FocusOut();
162 chromeos::IMEEngineHandlerInterface::InputContext context(
163 GetTextInputType(), GetTextInputMode(), GetTextInputFlags());
164 engine->FocusIn(context);
167 InputMethodBase::OnTextInputTypeChanged(client);
170 void InputMethodChromeOS::OnCaretBoundsChanged(const TextInputClient* client) {
171 if (!IsInputFieldFocused() || !IsTextInputClientFocused(client))
172 return;
174 NotifyTextInputCaretBoundsChanged(client);
176 if (!IsNonPasswordInputFieldFocused())
177 return;
179 // The current text input type should not be NONE if |context_| is focused.
180 DCHECK(client == GetTextInputClient());
181 DCHECK(!IsTextInputTypeNone());
182 const gfx::Rect caret_rect = client->GetCaretBounds();
184 gfx::Rect composition_head;
185 std::vector<gfx::Rect> rects;
186 if (client->HasCompositionText()) {
187 uint32 i = 0;
188 gfx::Rect rect;
189 while (client->GetCompositionCharacterBounds(i++, &rect))
190 rects.push_back(rect);
191 } else {
192 rects.push_back(caret_rect);
195 if (rects.size() > 0) {
196 composition_head = rects[0];
197 if (GetEngine())
198 GetEngine()->SetCompositionBounds(rects);
201 chromeos::IMECandidateWindowHandlerInterface* candidate_window =
202 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
203 if (!candidate_window)
204 return;
205 candidate_window->SetCursorBounds(caret_rect, composition_head);
207 gfx::Range text_range;
208 gfx::Range selection_range;
209 base::string16 surrounding_text;
210 if (!client->GetTextRange(&text_range) ||
211 !client->GetTextFromRange(text_range, &surrounding_text) ||
212 !client->GetSelectionRange(&selection_range)) {
213 previous_surrounding_text_.clear();
214 previous_selection_range_ = gfx::Range::InvalidRange();
215 return;
218 if (previous_selection_range_ == selection_range &&
219 previous_surrounding_text_ == surrounding_text)
220 return;
222 previous_selection_range_ = selection_range;
223 previous_surrounding_text_ = surrounding_text;
225 if (!selection_range.IsValid()) {
226 // TODO(nona): Ideally selection_range should not be invalid.
227 // TODO(nona): If javascript changes the focus on page loading, even (0,0)
228 // can not be obtained. Need investigation.
229 return;
232 // Here SetSurroundingText accepts relative position of |surrounding_text|, so
233 // we have to convert |selection_range| from node coordinates to
234 // |surrounding_text| coordinates.
235 if (!GetEngine())
236 return;
237 GetEngine()->SetSurroundingText(base::UTF16ToUTF8(surrounding_text),
238 selection_range.start() - text_range.start(),
239 selection_range.end() - text_range.start());
242 void InputMethodChromeOS::CancelComposition(const TextInputClient* client) {
243 if (IsNonPasswordInputFieldFocused() && IsTextInputClientFocused(client))
244 ResetContext();
247 void InputMethodChromeOS::OnInputLocaleChanged() {
248 // Not supported.
251 std::string InputMethodChromeOS::GetInputLocale() {
252 // Not supported.
253 return "";
256 bool InputMethodChromeOS::IsActive() {
257 return true;
260 bool InputMethodChromeOS::IsCandidatePopupOpen() const {
261 // TODO(yukishiino): Implement this method.
262 return false;
265 void InputMethodChromeOS::OnWillChangeFocusedClient(
266 TextInputClient* focused_before,
267 TextInputClient* focused) {
268 ConfirmCompositionText();
270 if (GetEngine())
271 GetEngine()->FocusOut();
274 void InputMethodChromeOS::OnDidChangeFocusedClient(
275 TextInputClient* focused_before,
276 TextInputClient* focused) {
277 // Force to update the input type since client's TextInputStateChanged()
278 // function might not be called if text input types before the client loses
279 // focus and after it acquires focus again are the same.
280 UpdateContextFocusState();
282 if (GetEngine()) {
283 chromeos::IMEEngineHandlerInterface::InputContext context(
284 GetTextInputType(), GetTextInputMode(), GetTextInputFlags());
285 GetEngine()->FocusIn(context);
289 void InputMethodChromeOS::ConfirmCompositionText() {
290 TextInputClient* client = GetTextInputClient();
291 if (client && client->HasCompositionText())
292 client->ConfirmCompositionText();
294 ResetContext();
297 void InputMethodChromeOS::ResetContext() {
298 if (!IsNonPasswordInputFieldFocused() || !GetTextInputClient())
299 return;
301 DCHECK(system_toplevel_window_focused());
303 composition_.Clear();
304 result_text_.clear();
305 composing_text_ = false;
306 composition_changed_ = false;
308 // This function runs asynchronously.
309 // Note: some input method engines may not support reset method, such as
310 // ibus-anthy. But as we control all input method engines by ourselves, we can
311 // make sure that all of the engines we are using support it correctly.
312 if (GetEngine())
313 GetEngine()->Reset();
315 character_composer_.Reset();
318 void InputMethodChromeOS::UpdateContextFocusState() {
319 ResetContext();
320 OnInputMethodChanged();
322 // Propagate the focus event to the candidate window handler which also
323 // manages the input method mode indicator.
324 chromeos::IMECandidateWindowHandlerInterface* candidate_window =
325 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
326 if (candidate_window)
327 candidate_window->FocusStateChanged(IsNonPasswordInputFieldFocused());
329 chromeos::IMEEngineHandlerInterface::InputContext context(
330 GetTextInputType(), GetTextInputMode(), GetTextInputFlags());
331 chromeos::IMEBridge::Get()->SetCurrentInputContext(context);
333 if (!IsTextInputTypeNone())
334 OnCaretBoundsChanged(GetTextInputClient());
337 void InputMethodChromeOS::ProcessKeyEventPostIME(const ui::KeyEvent& event,
338 bool handled) {
339 TextInputClient* client = GetTextInputClient();
340 if (!client) {
341 // As ibus works asynchronously, there is a chance that the focused client
342 // loses focus before this method gets called.
343 DispatchKeyEventPostIME(event);
344 return;
347 if (event.type() == ET_KEY_PRESSED && handled)
348 ProcessFilteredKeyPressEvent(event);
350 // In case the focus was changed by the key event. The |context_| should have
351 // been reset when the focused window changed.
352 if (client != GetTextInputClient())
353 return;
355 if (HasInputMethodResult())
356 ProcessInputMethodResult(event, handled);
358 // In case the focus was changed when sending input method results to the
359 // focused window.
360 if (client != GetTextInputClient())
361 return;
363 if (handled)
364 return; // IME handled the key event. do not forward.
366 if (event.type() == ET_KEY_PRESSED)
367 ProcessUnfilteredKeyPressEvent(event);
368 else if (event.type() == ET_KEY_RELEASED)
369 DispatchKeyEventPostIME(event);
372 void InputMethodChromeOS::ProcessFilteredKeyPressEvent(
373 const ui::KeyEvent& event) {
374 if (NeedInsertChar()) {
375 DispatchKeyEventPostIME(event);
376 } else {
377 const ui::KeyEvent fabricated_event(ET_KEY_PRESSED,
378 VKEY_PROCESSKEY,
379 event.flags());
380 DispatchKeyEventPostIME(fabricated_event);
384 void InputMethodChromeOS::ProcessUnfilteredKeyPressEvent(
385 const ui::KeyEvent& event) {
386 const TextInputClient* prev_client = GetTextInputClient();
387 DispatchKeyEventPostIME(event);
389 // We shouldn't dispatch the character anymore if the key event dispatch
390 // caused focus change. For example, in the following scenario,
391 // 1. visit a web page which has a <textarea>.
392 // 2. click Omnibox.
393 // 3. enable Korean IME, press A, then press Tab to move the focus to the web
394 // page.
395 // We should return here not to send the Tab key event to RWHV.
396 TextInputClient* client = GetTextInputClient();
397 if (!client || client != prev_client)
398 return;
400 // If a key event was not filtered by |context_| and |character_composer_|,
401 // then it means the key event didn't generate any result text. So we need
402 // to send corresponding character to the focused text input client.
403 uint16 ch = event.GetCharacter();
404 if (ch)
405 client->InsertChar(ch, event.flags());
408 void InputMethodChromeOS::ProcessInputMethodResult(const ui::KeyEvent& event,
409 bool handled) {
410 TextInputClient* client = GetTextInputClient();
411 DCHECK(client);
413 if (result_text_.length()) {
414 if (handled && NeedInsertChar()) {
415 for (base::string16::const_iterator i = result_text_.begin();
416 i != result_text_.end(); ++i) {
417 client->InsertChar(*i, event.flags());
419 } else {
420 client->InsertText(result_text_);
421 composing_text_ = false;
425 if (composition_changed_ && !IsTextInputTypeNone()) {
426 if (composition_.text.length()) {
427 composing_text_ = true;
428 client->SetCompositionText(composition_);
429 } else if (result_text_.empty()) {
430 client->ClearCompositionText();
434 // We should not clear composition text here, as it may belong to the next
435 // composition session.
436 result_text_.clear();
437 composition_changed_ = false;
440 bool InputMethodChromeOS::NeedInsertChar() const {
441 return GetTextInputClient() &&
442 (IsTextInputTypeNone() ||
443 (!composing_text_ && result_text_.length() == 1));
446 bool InputMethodChromeOS::HasInputMethodResult() const {
447 return result_text_.length() || composition_changed_;
450 void InputMethodChromeOS::SendFakeProcessKeyEvent(bool pressed) const {
451 if (!GetTextInputClient())
452 return;
453 KeyEvent evt(pressed ? ET_KEY_PRESSED : ET_KEY_RELEASED,
454 pressed ? VKEY_PROCESSKEY : VKEY_UNKNOWN,
455 EF_IME_FABRICATED_KEY);
456 DispatchKeyEventPostIME(evt);
459 void InputMethodChromeOS::CommitText(const std::string& text) {
460 if (text.empty())
461 return;
463 // We need to receive input method result even if the text input type is
464 // TEXT_INPUT_TYPE_NONE, to make sure we can always send correct
465 // character for each key event to the focused text input client.
466 if (!GetTextInputClient())
467 return;
469 const base::string16 utf16_text = base::UTF8ToUTF16(text);
470 if (utf16_text.empty())
471 return;
473 // Append the text to the buffer, because commit signal might be fired
474 // multiple times when processing a key event.
475 result_text_.append(utf16_text);
477 // If we are not handling key event, do not bother sending text result if the
478 // focused text input client does not support text input.
479 if (!handling_key_event_ && !IsTextInputTypeNone()) {
480 SendFakeProcessKeyEvent(true);
481 GetTextInputClient()->InsertText(utf16_text);
482 SendFakeProcessKeyEvent(false);
483 result_text_.clear();
487 void InputMethodChromeOS::UpdateCompositionText(
488 const chromeos::CompositionText& text,
489 uint32 cursor_pos,
490 bool visible) {
491 if (IsTextInputTypeNone())
492 return;
494 if (!CanComposeInline()) {
495 chromeos::IMECandidateWindowHandlerInterface* candidate_window =
496 chromeos::IMEBridge::Get()->GetCandidateWindowHandler();
497 if (candidate_window)
498 candidate_window->UpdatePreeditText(text.text(), cursor_pos, visible);
501 // |visible| argument is very confusing. For example, what's the correct
502 // behavior when:
503 // 1. OnUpdatePreeditText() is called with a text and visible == false, then
504 // 2. OnShowPreeditText() is called afterwards.
506 // If it's only for clearing the current preedit text, then why not just use
507 // OnHidePreeditText()?
508 if (!visible) {
509 HidePreeditText();
510 return;
513 ExtractCompositionText(text, cursor_pos, &composition_);
515 composition_changed_ = true;
517 // In case OnShowPreeditText() is not called.
518 if (composition_.text.length())
519 composing_text_ = true;
521 if (!handling_key_event_) {
522 // If we receive a composition text without pending key event, then we need
523 // to send it to the focused text input client directly.
524 SendFakeProcessKeyEvent(true);
525 GetTextInputClient()->SetCompositionText(composition_);
526 SendFakeProcessKeyEvent(false);
527 composition_changed_ = false;
528 composition_.Clear();
532 void InputMethodChromeOS::HidePreeditText() {
533 if (composition_.text.empty() || IsTextInputTypeNone())
534 return;
536 // Intentionally leaves |composing_text_| unchanged.
537 composition_changed_ = true;
538 composition_.Clear();
540 if (!handling_key_event_) {
541 TextInputClient* client = GetTextInputClient();
542 if (client && client->HasCompositionText()) {
543 SendFakeProcessKeyEvent(true);
544 client->ClearCompositionText();
545 SendFakeProcessKeyEvent(false);
547 composition_changed_ = false;
551 void InputMethodChromeOS::DeleteSurroundingText(int32 offset, uint32 length) {
552 if (!composition_.text.empty())
553 return; // do nothing if there is ongoing composition.
555 if (GetTextInputClient()) {
556 uint32 before = offset >= 0 ? 0U : static_cast<uint32>(-1 * offset);
557 GetTextInputClient()->ExtendSelectionAndDelete(before, length - before);
561 bool InputMethodChromeOS::ExecuteCharacterComposer(const ui::KeyEvent& event) {
562 if (!character_composer_.FilterKeyPress(event))
563 return false;
565 // CharacterComposer consumed the key event. Update the composition text.
566 chromeos::CompositionText preedit;
567 preedit.set_text(character_composer_.preedit_string());
568 UpdateCompositionText(preedit, preedit.text().size(),
569 !preedit.text().empty());
570 std::string commit_text =
571 base::UTF16ToUTF8(character_composer_.composed_character());
572 if (!commit_text.empty()) {
573 CommitText(commit_text);
575 return true;
578 void InputMethodChromeOS::ExtractCompositionText(
579 const chromeos::CompositionText& text,
580 uint32 cursor_position,
581 CompositionText* out_composition) const {
582 out_composition->Clear();
583 out_composition->text = text.text();
585 if (out_composition->text.empty())
586 return;
588 // ibus uses character index for cursor position and attribute range, but we
589 // use char16 offset for them. So we need to do conversion here.
590 std::vector<size_t> char16_offsets;
591 size_t length = out_composition->text.length();
592 base::i18n::UTF16CharIterator char_iterator(&out_composition->text);
593 do {
594 char16_offsets.push_back(char_iterator.array_pos());
595 } while (char_iterator.Advance());
597 // The text length in Unicode characters.
598 uint32 char_length = static_cast<uint32>(char16_offsets.size());
599 // Make sure we can convert the value of |char_length| as well.
600 char16_offsets.push_back(length);
602 size_t cursor_offset =
603 char16_offsets[std::min(char_length, cursor_position)];
605 out_composition->selection = gfx::Range(cursor_offset);
607 const std::vector<chromeos::CompositionText::UnderlineAttribute>&
608 underline_attributes = text.underline_attributes();
609 if (!underline_attributes.empty()) {
610 for (size_t i = 0; i < underline_attributes.size(); ++i) {
611 const uint32 start = underline_attributes[i].start_index;
612 const uint32 end = underline_attributes[i].end_index;
613 if (start >= end)
614 continue;
615 CompositionUnderline underline(char16_offsets[start],
616 char16_offsets[end],
617 SK_ColorBLACK,
618 false /* thick */,
619 SK_ColorTRANSPARENT);
620 if (underline_attributes[i].type ==
621 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_DOUBLE)
622 underline.thick = true;
623 else if (underline_attributes[i].type ==
624 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_ERROR)
625 underline.color = SK_ColorRED;
626 else if (underline_attributes[i].type ==
627 chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_NONE)
628 underline.color = SK_ColorTRANSPARENT;
629 out_composition->underlines.push_back(underline);
633 DCHECK(text.selection_start() <= text.selection_end());
634 if (text.selection_start() < text.selection_end()) {
635 const uint32 start = text.selection_start();
636 const uint32 end = text.selection_end();
637 CompositionUnderline underline(char16_offsets[start],
638 char16_offsets[end],
639 SK_ColorBLACK,
640 true /* thick */,
641 SK_ColorTRANSPARENT);
642 out_composition->underlines.push_back(underline);
644 // If the cursor is at start or end of this underline, then we treat
645 // it as the selection range as well, but make sure to set the cursor
646 // position to the selection end.
647 if (underline.start_offset == cursor_offset) {
648 out_composition->selection.set_start(underline.end_offset);
649 out_composition->selection.set_end(cursor_offset);
650 } else if (underline.end_offset == cursor_offset) {
651 out_composition->selection.set_start(underline.start_offset);
652 out_composition->selection.set_end(cursor_offset);
656 // Use a black thin underline by default.
657 if (out_composition->underlines.empty()) {
658 out_composition->underlines.push_back(CompositionUnderline(
659 0, length, SK_ColorBLACK, false /* thick */, SK_ColorTRANSPARENT));
663 bool InputMethodChromeOS::IsNonPasswordInputFieldFocused() {
664 TextInputType type = GetTextInputType();
665 return (type != TEXT_INPUT_TYPE_NONE) && (type != TEXT_INPUT_TYPE_PASSWORD);
668 bool InputMethodChromeOS::IsInputFieldFocused() {
669 return GetTextInputType() != TEXT_INPUT_TYPE_NONE;
672 } // namespace ui