1 // Copyright (c) 2012 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_ibus.h"
18 #include "base/basictypes.h"
19 #include "base/bind.h"
20 #include "base/i18n/char_iterator.h"
21 #include "base/logging.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/third_party/icu/icu_utf.h"
25 #include "chromeos/dbus/ibus/ibus_text.h"
26 #include "chromeos/ime/input_method_descriptor.h"
27 #include "chromeos/ime/input_method_manager.h"
28 #include "ui/base/ime/text_input_client.h"
29 #include "ui/events/event.h"
30 #include "ui/events/event_constants.h"
31 #include "ui/events/event_utils.h"
32 #include "ui/events/keycodes/keyboard_code_conversion.h"
33 #include "ui/events/keycodes/keyboard_code_conversion_x.h"
34 #include "ui/events/keycodes/keyboard_codes.h"
35 #include "ui/gfx/rect.h"
39 const int kIBusReleaseMask = 1 << 30;
41 XKeyEvent* GetKeyEvent(XEvent* event) {
42 DCHECK(event && (event->type == KeyPress || event->type == KeyRelease));
46 // Converts X (and ibus) state to event flags.
47 int EventFlagsFromXState(unsigned int state) {
48 return (state & LockMask ? ui::EF_CAPS_LOCK_DOWN : 0) |
49 (state & ControlMask ? ui::EF_CONTROL_DOWN : 0) |
50 (state & ShiftMask ? ui::EF_SHIFT_DOWN : 0) |
51 (state & Mod1Mask ? ui::EF_ALT_DOWN : 0) |
52 (state & Button1Mask ? ui::EF_LEFT_MOUSE_BUTTON : 0) |
53 (state & Button2Mask ? ui::EF_MIDDLE_MOUSE_BUTTON : 0) |
54 (state & Button3Mask ? ui::EF_RIGHT_MOUSE_BUTTON : 0);
57 // Converts X state to ibus key and button state.
58 uint32 IBusStateFromXState(unsigned int state) {
59 return (state & (LockMask | ControlMask | ShiftMask | Mod1Mask |
60 Button1Mask | Button2Mask | Button3Mask));
63 // Converts gfx::Rect to ibus::Rect.
64 chromeos::ibus::Rect GfxRectToIBusRect(const gfx::Rect& rect) {
65 return chromeos::ibus::Rect(rect.x(), rect.y(), rect.width(), rect.height());
68 chromeos::IBusEngineHandlerInterface* GetEngine() {
69 return chromeos::IBusBridge::Get()->GetEngineHandler();
72 // Check ui::TextInputType and chrome::ibus::TextInputType is kept in sync.
73 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_NONE) == \
74 int(chromeos::ibus::TEXT_INPUT_TYPE_NONE), mismatching_enums);
75 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_TEXT) == \
76 int(chromeos::ibus::TEXT_INPUT_TYPE_TEXT), mismatching_enums);
77 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_PASSWORD) == \
78 int(chromeos::ibus::TEXT_INPUT_TYPE_PASSWORD),
80 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_SEARCH) == \
81 int(chromeos::ibus::TEXT_INPUT_TYPE_SEARCH), mismatching_enums);
82 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_EMAIL) == \
83 int(chromeos::ibus::TEXT_INPUT_TYPE_EMAIL), mismatching_enums);
84 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_NUMBER) == \
85 int(chromeos::ibus::TEXT_INPUT_TYPE_NUMBER), mismatching_enums);
86 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_TELEPHONE) == \
87 int(chromeos::ibus::TEXT_INPUT_TYPE_TELEPHONE),
89 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_URL) == \
90 int(chromeos::ibus::TEXT_INPUT_TYPE_URL), mismatching_enums);
91 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_DATE) == \
92 int(chromeos::ibus::TEXT_INPUT_TYPE_DATE), mismatching_enum);
93 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_DATE_TIME) == \
94 int(chromeos::ibus::TEXT_INPUT_TYPE_DATE_TIME),
96 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL) == \
97 int(chromeos::ibus::TEXT_INPUT_TYPE_DATE_TIME_LOCAL),
99 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_MONTH) == \
100 int(chromeos::ibus::TEXT_INPUT_TYPE_MONTH), mismatching_enum);
101 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_TIME) == \
102 int(chromeos::ibus::TEXT_INPUT_TYPE_TIME), mismatching_enum);
103 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_WEEK) == \
104 int(chromeos::ibus::TEXT_INPUT_TYPE_WEEK), mismatching_enum);
105 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_TEXT_AREA) == \
106 int(chromeos::ibus::TEXT_INPUT_TYPE_TEXT_AREA),
108 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_CONTENT_EDITABLE) == \
109 int(chromeos::ibus::TEXT_INPUT_TYPE_CONTENT_EDITABLE),
111 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_DATE_TIME_FIELD) == \
112 int(chromeos::ibus::TEXT_INPUT_TYPE_DATE_TIME_FIELD),
115 chromeos::ibus::TextInputType UiToIbusTextInputType(ui::TextInputType type) {
116 // Check the type is in the range representable by
117 // chrome::ibus::TextInputType.
118 DCHECK_LE(type, static_cast<int>(chromeos::ibus::TEXT_INPUT_TYPE_MAX)) <<
119 "ui::TextInputType and chromeos::ibus::TextInputType not synchronized";
120 return static_cast<chromeos::ibus::TextInputType>(type);
127 // InputMethodIBus implementation -----------------------------------------
128 InputMethodIBus::InputMethodIBus(
129 internal::InputMethodDelegate* delegate)
130 : context_focused_(false),
131 composing_text_(false),
132 composition_changed_(false),
133 suppress_next_result_(false),
134 current_keyevent_id_(0),
135 previous_textinput_type_(TEXT_INPUT_TYPE_NONE),
136 weak_ptr_factory_(this) {
137 SetDelegate(delegate);
138 chromeos::IBusBridge::Get()->SetInputContextHandler(this);
140 UpdateContextFocusState();
141 OnInputMethodChanged();
144 InputMethodIBus::~InputMethodIBus() {
145 AbandonAllPendingKeyEvents();
146 context_focused_ = false;
147 ConfirmCompositionText();
148 // We are dead, so we need to ask the client to stop relying on us.
149 OnInputMethodChanged();
151 chromeos::IBusBridge::Get()->SetInputContextHandler(NULL);
154 void InputMethodIBus::OnFocus() {
155 InputMethodBase::OnFocus();
156 UpdateContextFocusState();
159 void InputMethodIBus::OnBlur() {
160 ConfirmCompositionText();
161 InputMethodBase::OnBlur();
162 UpdateContextFocusState();
165 bool InputMethodIBus::OnUntranslatedIMEMessage(const base::NativeEvent& event,
166 NativeEventResult* result) {
170 void InputMethodIBus::ProcessKeyEventDone(uint32 id,
177 std::set<uint32>::iterator it = pending_key_events_.find(id);
179 if (it == pending_key_events_.end())
180 return; // Abandoned key event.
182 if (event->type == KeyPress) {
184 // IME event has a priority to be handled, so that character composer
186 character_composer_.Reset();
188 // If IME does not handle key event, passes keyevent to character composer
189 // to be able to compose complex characters.
190 is_handled = ExecuteCharacterComposer(ibus_keyval, ibus_keycode,
195 if (event->type == KeyPress || event->type == KeyRelease)
196 ProcessKeyEventPostIME(event, ibus_state, is_handled);
198 // Do not use |it| for erasing, ProcessKeyEventPostIME may change the
199 // |pending_key_events_|.
200 pending_key_events_.erase(id);
203 bool InputMethodIBus::DispatchKeyEvent(const base::NativeEvent& native_event) {
204 DCHECK(native_event && (native_event->type == KeyPress ||
205 native_event->type == KeyRelease));
206 DCHECK(system_toplevel_window_focused());
208 uint32 ibus_keyval = 0;
209 uint32 ibus_keycode = 0;
210 uint32 ibus_state = 0;
211 IBusKeyEventFromNativeKeyEvent(
213 &ibus_keyval, &ibus_keycode, &ibus_state);
215 // If |context_| is not usable, then we can only dispatch the key event as is.
216 // We also dispatch the key event directly if the current text input type is
217 // TEXT_INPUT_TYPE_PASSWORD, to bypass the input method.
218 // Note: We need to send the key event to ibus even if the |context_| is not
219 // enabled, so that ibus can have a chance to enable the |context_|.
220 if (!context_focused_ || !GetEngine() ||
221 GetTextInputType() == TEXT_INPUT_TYPE_PASSWORD ) {
222 if (native_event->type == KeyPress) {
223 if (ExecuteCharacterComposer(ibus_keyval, ibus_keycode, ibus_state)) {
224 // Treating as PostIME event if character composer handles key event and
225 // generates some IME event,
226 ProcessKeyEventPostIME(native_event, ibus_state, true);
229 ProcessUnfilteredKeyPressEvent(native_event, ibus_state);
231 DispatchKeyEventPostIME(native_event);
236 pending_key_events_.insert(current_keyevent_id_);
238 // Since |native_event| might be treated as XEvent whose size is bigger than
239 // XKeyEvent e.g. in CopyNativeEvent() in ui/events/event.cc, allocating
240 // |event| as XKeyEvent and casting it to XEvent is unsafe. crbug.com/151884
241 XEvent* event = new XEvent;
242 *event = *native_event;
243 GetEngine()->ProcessKeyEvent(
247 base::Bind(&InputMethodIBus::ProcessKeyEventDone,
248 weak_ptr_factory_.GetWeakPtr(),
249 current_keyevent_id_,
250 base::Owned(event), // Pass the ownership of |event|.
255 ++current_keyevent_id_;
257 // We don't want to suppress the result generated by this key event, but it
258 // may cause problem. See comment in ResetContext() method.
259 suppress_next_result_ = false;
263 bool InputMethodIBus::DispatchFabricatedKeyEvent(const ui::KeyEvent& event) {
264 // TODO(bryeung): The fabricated events should also pass through IME.
265 if (event.type() == ET_KEY_PRESSED) {
266 ProcessUnfilteredFabricatedKeyPressEvent(
267 ET_KEY_PRESSED, event.key_code(), event.flags());
269 DispatchFabricatedKeyEventPostIME(
277 void InputMethodIBus::OnTextInputTypeChanged(const TextInputClient* client) {
278 if (IsTextInputClientFocused(client)) {
280 UpdateContextFocusState();
281 if (previous_textinput_type_ != client->GetTextInputType())
282 OnInputMethodChanged();
283 previous_textinput_type_ = client->GetTextInputType();
285 InputMethodBase::OnTextInputTypeChanged(client);
288 void InputMethodIBus::OnCaretBoundsChanged(const TextInputClient* client) {
289 OnCaretBoundsChangedInternal(client);
290 InputMethodBase::OnCaretBoundsChanged(client);
293 void InputMethodIBus::CancelComposition(const TextInputClient* client) {
294 if (context_focused_ && IsTextInputClientFocused(client))
298 std::string InputMethodIBus::GetInputLocale() {
303 base::i18n::TextDirection InputMethodIBus::GetInputTextDirection() {
305 return base::i18n::UNKNOWN_DIRECTION;
308 bool InputMethodIBus::IsActive() {
312 bool InputMethodIBus::IsCandidatePopupOpen() const {
313 // TODO(yukishiino): Implement this method.
317 void InputMethodIBus::OnWillChangeFocusedClient(TextInputClient* focused_before,
318 TextInputClient* focused) {
319 ConfirmCompositionText();
322 void InputMethodIBus::OnDidChangeFocusedClient(TextInputClient* focused_before,
323 TextInputClient* focused) {
324 // Force to update the input type since client's TextInputStateChanged()
325 // function might not be called if text input types before the client loses
326 // focus and after it acquires focus again are the same.
327 OnTextInputTypeChanged(focused);
329 UpdateContextFocusState();
330 // Force to update caret bounds, in case the client thinks that the caret
331 // bounds has not changed.
332 OnCaretBoundsChanged(focused);
335 void InputMethodIBus::ConfirmCompositionText() {
336 TextInputClient* client = GetTextInputClient();
337 if (client && client->HasCompositionText())
338 client->ConfirmCompositionText();
343 void InputMethodIBus::ResetContext() {
344 if (!context_focused_ || !GetTextInputClient())
347 DCHECK(system_toplevel_window_focused());
349 // Because ibus runs in asynchronous mode, the input method may still send us
350 // results after sending out the reset request, so we use a flag to discard
351 // all results generated by previous key events. But because ibus does not
352 // have a mechanism to identify each key event and corresponding results, this
353 // approach will not work for some corner cases. For example if the user types
354 // very fast, then the next key event may come in before the |context_| is
355 // really reset. Then we actually cannot know whether or not the next
356 // result should be discard.
357 suppress_next_result_ = true;
359 composition_.Clear();
360 result_text_.clear();
361 composing_text_ = false;
362 composition_changed_ = false;
364 // We need to abandon all pending key events, but as above comment says, there
365 // is no reliable way to abandon all results generated by these abandoned key
367 AbandonAllPendingKeyEvents();
369 // This function runs asynchronously.
370 // Note: some input method engines may not support reset method, such as
371 // ibus-anthy. But as we control all input method engines by ourselves, we can
372 // make sure that all of the engines we are using support it correctly.
374 GetEngine()->Reset();
376 character_composer_.Reset();
379 void InputMethodIBus::UpdateContextFocusState() {
380 const bool old_context_focused = context_focused_;
381 const TextInputType current_text_input_type = GetTextInputType();
382 // Use switch here in case we are going to add more text input types.
383 switch (current_text_input_type) {
384 case TEXT_INPUT_TYPE_NONE:
385 case TEXT_INPUT_TYPE_PASSWORD:
386 context_focused_ = false;
389 context_focused_ = true;
395 // We only focus in |context_| when the focus is in a normal textfield.
396 // ibus_input_context_focus_{in|out}() run asynchronously.
397 if (old_context_focused && !context_focused_) {
398 GetEngine()->FocusOut();
399 } else if (!old_context_focused && context_focused_) {
400 GetEngine()->FocusIn(UiToIbusTextInputType(current_text_input_type));
401 OnCaretBoundsChanged(GetTextInputClient());
402 } else if (context_focused_ &&
403 current_text_input_type != previous_textinput_type_) {
404 GetEngine()->FocusOut();
405 GetEngine()->FocusIn(UiToIbusTextInputType(current_text_input_type));
406 OnCaretBoundsChanged(GetTextInputClient());
410 void InputMethodIBus::ProcessKeyEventPostIME(
411 const base::NativeEvent& native_event,
414 TextInputClient* client = GetTextInputClient();
417 // As ibus works asynchronously, there is a chance that the focused client
418 // loses focus before this method gets called.
419 DispatchKeyEventPostIME(native_event);
423 if (native_event->type == KeyPress && handled)
424 ProcessFilteredKeyPressEvent(native_event);
426 // In case the focus was changed by the key event. The |context_| should have
427 // been reset when the focused window changed.
428 if (client != GetTextInputClient())
431 if (HasInputMethodResult())
432 ProcessInputMethodResult(native_event, handled);
434 // In case the focus was changed when sending input method results to the
436 if (client != GetTextInputClient())
439 if (native_event->type == KeyPress && !handled)
440 ProcessUnfilteredKeyPressEvent(native_event, ibus_state);
441 else if (native_event->type == KeyRelease)
442 DispatchKeyEventPostIME(native_event);
445 void InputMethodIBus::IBusKeyEventFromNativeKeyEvent(
446 const base::NativeEvent& native_event,
448 uint32* ibus_keycode,
449 uint32* ibus_state) {
450 DCHECK(native_event); // A fabricated event is not supported here.
451 XKeyEvent* x_key = GetKeyEvent(native_event);
453 // Yes, ibus uses X11 keysym. We cannot use XLookupKeysym(), which doesn't
454 // translate Shift and CapsLock states.
455 KeySym keysym = NoSymbol;
456 ::XLookupString(x_key, NULL, 0, &keysym, NULL);
457 *ibus_keyval = keysym;
458 *ibus_keycode = x_key->keycode;
459 *ibus_state = IBusStateFromXState(x_key->state);
460 if (native_event->type == KeyRelease)
461 *ibus_state |= kIBusReleaseMask;
464 void InputMethodIBus::ProcessFilteredKeyPressEvent(
465 const base::NativeEvent& native_event) {
466 if (NeedInsertChar())
467 DispatchKeyEventPostIME(native_event);
469 DispatchFabricatedKeyEventPostIME(
472 EventFlagsFromXState(GetKeyEvent(native_event)->state));
475 void InputMethodIBus::ProcessUnfilteredKeyPressEvent(
476 const base::NativeEvent& native_event,
478 // For a fabricated event, ProcessUnfilteredFabricatedKeyPressEvent should be
480 DCHECK(native_event);
482 TextInputClient* client = GetTextInputClient();
483 DispatchKeyEventPostIME(native_event);
485 // We shouldn't dispatch the character anymore if the key event dispatch
486 // caused focus change. For example, in the following scenario,
487 // 1. visit a web page which has a <textarea>.
489 // 3. enable Korean IME, press A, then press Tab to move the focus to the web
491 // We should return here not to send the Tab key event to RWHV.
492 if (client != GetTextInputClient())
495 const uint32 event_flags = EventFlagsFromXState(ibus_state);
497 // If a key event was not filtered by |context_| and |character_composer_|,
498 // then it means the key event didn't generate any result text. So we need
499 // to send corresponding character to the focused text input client.
500 client = GetTextInputClient();
503 if (!(event_flags & ui::EF_CONTROL_DOWN))
504 ch = ui::GetCharacterFromXEvent(native_event);
506 ch = ui::GetCharacterFromKeyCode(
507 ui::KeyboardCodeFromNative(native_event), event_flags);
511 client->InsertChar(ch, event_flags);
514 void InputMethodIBus::ProcessUnfilteredFabricatedKeyPressEvent(
516 KeyboardCode key_code,
518 TextInputClient* client = GetTextInputClient();
519 DispatchFabricatedKeyEventPostIME(type, key_code, event_flags);
521 if (client != GetTextInputClient())
524 client = GetTextInputClient();
525 const uint16 ch = ui::GetCharacterFromKeyCode(key_code, event_flags);
527 client->InsertChar(ch, event_flags);
530 void InputMethodIBus::ProcessInputMethodResult(
531 const base::NativeEvent& native_event,
533 TextInputClient* client = GetTextInputClient();
536 if (result_text_.length()) {
537 if (handled && NeedInsertChar()) {
539 EventFlagsFromXState(GetKeyEvent(native_event)->state);
540 for (string16::const_iterator i = result_text_.begin();
541 i != result_text_.end(); ++i) {
542 client->InsertChar(*i, state);
545 client->InsertText(result_text_);
546 composing_text_ = false;
550 if (composition_changed_ && !IsTextInputTypeNone()) {
551 if (composition_.text.length()) {
552 composing_text_ = true;
553 client->SetCompositionText(composition_);
554 } else if (result_text_.empty()) {
555 client->ClearCompositionText();
559 // We should not clear composition text here, as it may belong to the next
560 // composition session.
561 result_text_.clear();
562 composition_changed_ = false;
565 bool InputMethodIBus::NeedInsertChar() const {
566 return GetTextInputClient() &&
567 (IsTextInputTypeNone() ||
568 (!composing_text_ && result_text_.length() == 1));
571 bool InputMethodIBus::HasInputMethodResult() const {
572 return result_text_.length() || composition_changed_;
575 void InputMethodIBus::AbandonAllPendingKeyEvents() {
576 pending_key_events_.clear();
579 void InputMethodIBus::CommitText(const std::string& text) {
580 if (suppress_next_result_ || text.empty())
583 // We need to receive input method result even if the text input type is
584 // TEXT_INPUT_TYPE_NONE, to make sure we can always send correct
585 // character for each key event to the focused text input client.
586 if (!GetTextInputClient())
589 const string16 utf16_text = UTF8ToUTF16(text);
590 if (utf16_text.empty())
593 // Append the text to the buffer, because commit signal might be fired
594 // multiple times when processing a key event.
595 result_text_.append(utf16_text);
597 // If we are not handling key event, do not bother sending text result if the
598 // focused text input client does not support text input.
599 if (pending_key_events_.empty() && !IsTextInputTypeNone()) {
600 GetTextInputClient()->InsertText(utf16_text);
601 result_text_.clear();
605 void InputMethodIBus::ForwardKeyEvent(uint32 keyval,
608 KeyboardCode ui_key_code = KeyboardCodeFromXKeysym(keyval);
612 const EventType event_type =
613 (state & kIBusReleaseMask) ? ET_KEY_RELEASED : ET_KEY_PRESSED;
614 const int event_flags = EventFlagsFromXState(state);
616 // It is not clear when the input method will forward us a fake key event.
617 // If there is a pending key event, then we may already received some input
618 // method results, so we dispatch this fake key event directly rather than
619 // calling ProcessKeyEventPostIME(), which will clear pending input method
621 if (event_type == ET_KEY_PRESSED) {
622 ProcessUnfilteredFabricatedKeyPressEvent(event_type, ui_key_code,
625 DispatchFabricatedKeyEventPostIME(event_type, ui_key_code, event_flags);
629 void InputMethodIBus::ShowPreeditText() {
630 if (suppress_next_result_ || IsTextInputTypeNone())
633 composing_text_ = true;
636 void InputMethodIBus::UpdatePreeditText(const chromeos::IBusText& text,
639 if (suppress_next_result_ || IsTextInputTypeNone())
642 if (!CanComposeInline()) {
643 chromeos::IBusPanelCandidateWindowHandlerInterface* candidate_window =
644 chromeos::IBusBridge::Get()->GetCandidateWindowHandler();
645 if (candidate_window)
646 candidate_window->UpdatePreeditText(text.text(), cursor_pos, visible);
649 // |visible| argument is very confusing. For example, what's the correct
651 // 1. OnUpdatePreeditText() is called with a text and visible == false, then
652 // 2. OnShowPreeditText() is called afterwards.
654 // If it's only for clearing the current preedit text, then why not just use
655 // OnHidePreeditText()?
661 ExtractCompositionText(text, cursor_pos, &composition_);
663 composition_changed_ = true;
665 // In case OnShowPreeditText() is not called.
666 if (composition_.text.length())
667 composing_text_ = true;
669 // If we receive a composition text without pending key event, then we need to
670 // send it to the focused text input client directly.
671 if (pending_key_events_.empty()) {
672 GetTextInputClient()->SetCompositionText(composition_);
673 composition_changed_ = false;
674 composition_.Clear();
678 void InputMethodIBus::HidePreeditText() {
679 if (composition_.text.empty() || IsTextInputTypeNone())
682 // Intentionally leaves |composing_text_| unchanged.
683 composition_changed_ = true;
684 composition_.Clear();
686 if (pending_key_events_.empty()) {
687 TextInputClient* client = GetTextInputClient();
688 if (client && client->HasCompositionText())
689 client->ClearCompositionText();
690 composition_changed_ = false;
694 void InputMethodIBus::DeleteSurroundingText(int32 offset, uint32 length) {
695 if (!composition_.text.empty())
696 return; // do nothing if there is ongoing composition.
697 if (offset < 0 && static_cast<uint32>(-1 * offset) != length)
698 return; // only preceding text can be deletable.
699 if (GetTextInputClient())
700 GetTextInputClient()->ExtendSelectionAndDelete(length, 0U);
703 bool InputMethodIBus::ExecuteCharacterComposer(uint32 ibus_keyval,
706 bool consumed = character_composer_.FilterKeyPress(
709 EventFlagsFromXState(ibus_state));
711 suppress_next_result_ = false;
712 chromeos::IBusText preedit;
714 UTF16ToUTF8(character_composer_.preedit_string()));
715 UpdatePreeditText(preedit, preedit.text().size(),
716 !preedit.text().empty());
717 std::string commit_text =
718 UTF16ToUTF8(character_composer_.composed_character());
719 if (!commit_text.empty()) {
720 CommitText(commit_text);
725 void InputMethodIBus::ExtractCompositionText(
726 const chromeos::IBusText& text,
727 uint32 cursor_position,
728 CompositionText* out_composition) const {
729 out_composition->Clear();
730 out_composition->text = UTF8ToUTF16(text.text());
732 if (out_composition->text.empty())
735 // ibus uses character index for cursor position and attribute range, but we
736 // use char16 offset for them. So we need to do conversion here.
737 std::vector<size_t> char16_offsets;
738 size_t length = out_composition->text.length();
739 base::i18n::UTF16CharIterator char_iterator(&out_composition->text);
741 char16_offsets.push_back(char_iterator.array_pos());
742 } while (char_iterator.Advance());
744 // The text length in Unicode characters.
745 uint32 char_length = static_cast<uint32>(char16_offsets.size());
746 // Make sure we can convert the value of |char_length| as well.
747 char16_offsets.push_back(length);
749 size_t cursor_offset =
750 char16_offsets[std::min(char_length, cursor_position)];
752 out_composition->selection = gfx::Range(cursor_offset);
754 const std::vector<chromeos::IBusText::UnderlineAttribute>&
755 underline_attributes = text.underline_attributes();
756 const std::vector<chromeos::IBusText::SelectionAttribute>&
757 selection_attributes = text.selection_attributes();
759 if (!underline_attributes.empty()) {
760 for (size_t i = 0; i < underline_attributes.size(); ++i) {
761 const uint32 start = underline_attributes[i].start_index;
762 const uint32 end = underline_attributes[i].end_index;
765 CompositionUnderline underline(
766 char16_offsets[start], char16_offsets[end],
767 SK_ColorBLACK, false /* thick */);
768 if (underline_attributes[i].type ==
769 chromeos::IBusText::IBUS_TEXT_UNDERLINE_DOUBLE)
770 underline.thick = true;
771 else if (underline_attributes[i].type ==
772 chromeos::IBusText::IBUS_TEXT_UNDERLINE_ERROR)
773 underline.color = SK_ColorRED;
774 out_composition->underlines.push_back(underline);
778 if (!selection_attributes.empty()) {
779 LOG_IF(ERROR, selection_attributes.size() != 1)
780 << "Chrome does not support multiple selection";
781 for (uint32 i = 0; i < selection_attributes.size(); ++i) {
782 const uint32 start = selection_attributes[i].start_index;
783 const uint32 end = selection_attributes[i].end_index;
786 CompositionUnderline underline(
787 char16_offsets[start], char16_offsets[end],
788 SK_ColorBLACK, true /* thick */);
789 out_composition->underlines.push_back(underline);
790 // If the cursor is at start or end of this underline, then we treat
791 // it as the selection range as well, but make sure to set the cursor
792 // position to the selection end.
793 if (underline.start_offset == cursor_offset) {
794 out_composition->selection.set_start(underline.end_offset);
795 out_composition->selection.set_end(cursor_offset);
796 } else if (underline.end_offset == cursor_offset) {
797 out_composition->selection.set_start(underline.start_offset);
798 out_composition->selection.set_end(cursor_offset);
803 // Use a black thin underline by default.
804 if (out_composition->underlines.empty()) {
805 out_composition->underlines.push_back(CompositionUnderline(
806 0, length, SK_ColorBLACK, false /* thick */));
810 void InputMethodIBus::OnCaretBoundsChangedInternal(
811 const TextInputClient* client) {
812 if (!context_focused_ || !IsTextInputClientFocused(client))
815 // The current text input type should not be NONE if |context_| is focused.
816 DCHECK(!IsTextInputTypeNone());
817 const gfx::Rect rect = GetTextInputClient()->GetCaretBounds();
819 gfx::Rect composition_head;
820 if (!GetTextInputClient()->GetCompositionCharacterBounds(0,
821 &composition_head)) {
822 composition_head = rect;
825 chromeos::IBusPanelCandidateWindowHandlerInterface* candidate_window =
826 chromeos::IBusBridge::Get()->GetCandidateWindowHandler();
827 if (!candidate_window)
829 candidate_window->SetCursorLocation(
830 GfxRectToIBusRect(rect),
831 GfxRectToIBusRect(composition_head));
833 gfx::Range text_range;
834 gfx::Range selection_range;
835 string16 surrounding_text;
836 if (!GetTextInputClient()->GetTextRange(&text_range) ||
837 !GetTextInputClient()->GetTextFromRange(text_range, &surrounding_text) ||
838 !GetTextInputClient()->GetSelectionRange(&selection_range)) {
839 previous_surrounding_text_.clear();
840 previous_selection_range_ = gfx::Range::InvalidRange();
844 if (previous_selection_range_ == selection_range &&
845 previous_surrounding_text_ == surrounding_text)
848 previous_selection_range_ = selection_range;
849 previous_surrounding_text_ = surrounding_text;
851 if (!selection_range.IsValid()) {
852 // TODO(nona): Ideally selection_range should not be invalid.
853 // TODO(nona): If javascript changes the focus on page loading, even (0,0)
854 // can not be obtained. Need investigation.
858 // Here SetSurroundingText accepts relative position of |surrounding_text|, so
859 // we have to convert |selection_range| from node coordinates to
860 // |surrounding_text| coordinates.
863 GetEngine()->SetSurroundingText(
864 UTF16ToUTF8(surrounding_text),
865 selection_range.start() - text_range.start(),
866 selection_range.end() - text_range.start());