- add sources.
[platform/framework/web/crosswalk.git] / src / ui / base / ime / input_method_ibus.cc
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.
4
5 #include "ui/base/ime/input_method_ibus.h"
6
7 #include <X11/X.h>
8 #include <X11/Xlib.h>
9 #include <X11/Xutil.h>
10 #undef FocusIn
11 #undef FocusOut
12
13 #include <algorithm>
14 #include <cstring>
15 #include <set>
16 #include <vector>
17
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"
36
37 namespace {
38
39 const int kIBusReleaseMask = 1 << 30;
40
41 XKeyEvent* GetKeyEvent(XEvent* event) {
42   DCHECK(event && (event->type == KeyPress || event->type == KeyRelease));
43   return &event->xkey;
44 }
45
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);
55 }
56
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));
61 }
62
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());
66 }
67
68 chromeos::IBusEngineHandlerInterface* GetEngine() {
69   return chromeos::IBusBridge::Get()->GetEngineHandler();
70 }
71
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),
79                mismatching_enums);
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),
88                mismatching_enums);
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),
95                mismatching_enum);
96 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL) == \
97                int(chromeos::ibus::TEXT_INPUT_TYPE_DATE_TIME_LOCAL),
98                mismatching_enum);
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),
107                mismatching_enums);
108 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_CONTENT_EDITABLE) == \
109                int(chromeos::ibus::TEXT_INPUT_TYPE_CONTENT_EDITABLE),
110                mismatching_enums);
111 COMPILE_ASSERT(int(ui::TEXT_INPUT_TYPE_DATE_TIME_FIELD) == \
112                int(chromeos::ibus::TEXT_INPUT_TYPE_DATE_TIME_FIELD),
113                mismatching_enums);
114
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);
121 }
122
123 }  // namespace
124
125 namespace ui {
126
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);
139
140   UpdateContextFocusState();
141   OnInputMethodChanged();
142 }
143
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();
150
151   chromeos::IBusBridge::Get()->SetInputContextHandler(NULL);
152 }
153
154 void InputMethodIBus::OnFocus() {
155   InputMethodBase::OnFocus();
156   UpdateContextFocusState();
157 }
158
159 void InputMethodIBus::OnBlur() {
160   ConfirmCompositionText();
161   InputMethodBase::OnBlur();
162   UpdateContextFocusState();
163 }
164
165 bool InputMethodIBus::OnUntranslatedIMEMessage(const base::NativeEvent& event,
166                                                NativeEventResult* result) {
167   return false;
168 }
169
170 void InputMethodIBus::ProcessKeyEventDone(uint32 id,
171                                           XEvent* event,
172                                           uint32 ibus_keyval,
173                                           uint32 ibus_keycode,
174                                           uint32 ibus_state,
175                                           bool is_handled) {
176   DCHECK(event);
177   std::set<uint32>::iterator it = pending_key_events_.find(id);
178
179   if (it == pending_key_events_.end())
180     return;  // Abandoned key event.
181
182   if (event->type == KeyPress) {
183     if (is_handled) {
184       // IME event has a priority to be handled, so that character composer
185       // should be reset.
186       character_composer_.Reset();
187     } else {
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,
191                                             ibus_state);
192     }
193   }
194
195   if (event->type == KeyPress || event->type == KeyRelease)
196     ProcessKeyEventPostIME(event, ibus_state, is_handled);
197
198   // Do not use |it| for erasing, ProcessKeyEventPostIME may change the
199   // |pending_key_events_|.
200   pending_key_events_.erase(id);
201 }
202
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());
207
208   uint32 ibus_keyval = 0;
209   uint32 ibus_keycode = 0;
210   uint32 ibus_state = 0;
211   IBusKeyEventFromNativeKeyEvent(
212       native_event,
213       &ibus_keyval, &ibus_keycode, &ibus_state);
214
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);
227         return true;
228       }
229       ProcessUnfilteredKeyPressEvent(native_event, ibus_state);
230     } else {
231       DispatchKeyEventPostIME(native_event);
232     }
233     return true;
234   }
235
236   pending_key_events_.insert(current_keyevent_id_);
237
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(
244       ibus_keyval,
245       ibus_keycode,
246       ibus_state,
247       base::Bind(&InputMethodIBus::ProcessKeyEventDone,
248                  weak_ptr_factory_.GetWeakPtr(),
249                  current_keyevent_id_,
250                  base::Owned(event),  // Pass the ownership of |event|.
251                  ibus_keyval,
252                  ibus_keycode,
253                  ibus_state));
254
255   ++current_keyevent_id_;
256
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;
260   return true;
261 }
262
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());
268   } else {
269     DispatchFabricatedKeyEventPostIME(
270         ET_KEY_RELEASED,
271         event.key_code(),
272         event.flags());
273   }
274   return true;
275 }
276
277 void InputMethodIBus::OnTextInputTypeChanged(const TextInputClient* client) {
278   if (IsTextInputClientFocused(client)) {
279     ResetContext();
280     UpdateContextFocusState();
281     if (previous_textinput_type_ != client->GetTextInputType())
282       OnInputMethodChanged();
283     previous_textinput_type_ = client->GetTextInputType();
284   }
285   InputMethodBase::OnTextInputTypeChanged(client);
286 }
287
288 void InputMethodIBus::OnCaretBoundsChanged(const TextInputClient* client) {
289   OnCaretBoundsChangedInternal(client);
290   InputMethodBase::OnCaretBoundsChanged(client);
291 }
292
293 void InputMethodIBus::CancelComposition(const TextInputClient* client) {
294   if (context_focused_ && IsTextInputClientFocused(client))
295     ResetContext();
296 }
297
298 std::string InputMethodIBus::GetInputLocale() {
299   // Not supported.
300   return "";
301 }
302
303 base::i18n::TextDirection InputMethodIBus::GetInputTextDirection() {
304   // Not supported.
305   return base::i18n::UNKNOWN_DIRECTION;
306 }
307
308 bool InputMethodIBus::IsActive() {
309   return true;
310 }
311
312 bool InputMethodIBus::IsCandidatePopupOpen() const {
313   // TODO(yukishiino): Implement this method.
314   return false;
315 }
316
317 void InputMethodIBus::OnWillChangeFocusedClient(TextInputClient* focused_before,
318                                                 TextInputClient* focused) {
319   ConfirmCompositionText();
320 }
321
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);
328
329   UpdateContextFocusState();
330   // Force to update caret bounds, in case the client thinks that the caret
331   // bounds has not changed.
332   OnCaretBoundsChanged(focused);
333 }
334
335 void InputMethodIBus::ConfirmCompositionText() {
336   TextInputClient* client = GetTextInputClient();
337   if (client && client->HasCompositionText())
338     client->ConfirmCompositionText();
339
340   ResetContext();
341 }
342
343 void InputMethodIBus::ResetContext() {
344   if (!context_focused_ || !GetTextInputClient())
345     return;
346
347   DCHECK(system_toplevel_window_focused());
348
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;
358
359   composition_.Clear();
360   result_text_.clear();
361   composing_text_ = false;
362   composition_changed_ = false;
363
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
366   // events.
367   AbandonAllPendingKeyEvents();
368
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.
373   if (GetEngine())
374     GetEngine()->Reset();
375
376   character_composer_.Reset();
377 }
378
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;
387       break;
388     default:
389       context_focused_ = true;
390       break;
391   }
392   if (!GetEngine())
393     return;
394
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());
407   }
408 }
409
410 void InputMethodIBus::ProcessKeyEventPostIME(
411     const base::NativeEvent& native_event,
412     uint32 ibus_state,
413     bool handled) {
414   TextInputClient* client = GetTextInputClient();
415
416   if (!client) {
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);
420     return;
421   }
422
423   if (native_event->type == KeyPress && handled)
424     ProcessFilteredKeyPressEvent(native_event);
425
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())
429     return;
430
431   if (HasInputMethodResult())
432     ProcessInputMethodResult(native_event, handled);
433
434   // In case the focus was changed when sending input method results to the
435   // focused window.
436   if (client != GetTextInputClient())
437     return;
438
439   if (native_event->type == KeyPress && !handled)
440     ProcessUnfilteredKeyPressEvent(native_event, ibus_state);
441   else if (native_event->type == KeyRelease)
442     DispatchKeyEventPostIME(native_event);
443 }
444
445 void InputMethodIBus::IBusKeyEventFromNativeKeyEvent(
446     const base::NativeEvent& native_event,
447     uint32* ibus_keyval,
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);
452
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;
462 }
463
464 void InputMethodIBus::ProcessFilteredKeyPressEvent(
465     const base::NativeEvent& native_event) {
466   if (NeedInsertChar())
467     DispatchKeyEventPostIME(native_event);
468   else
469     DispatchFabricatedKeyEventPostIME(
470         ET_KEY_PRESSED,
471         VKEY_PROCESSKEY,
472         EventFlagsFromXState(GetKeyEvent(native_event)->state));
473 }
474
475 void InputMethodIBus::ProcessUnfilteredKeyPressEvent(
476     const base::NativeEvent& native_event,
477     uint32 ibus_state) {
478   // For a fabricated event, ProcessUnfilteredFabricatedKeyPressEvent should be
479   // called instead.
480   DCHECK(native_event);
481
482   TextInputClient* client = GetTextInputClient();
483   DispatchKeyEventPostIME(native_event);
484
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>.
488   // 2. click Omnibox.
489   // 3. enable Korean IME, press A, then press Tab to move the focus to the web
490   //    page.
491   // We should return here not to send the Tab key event to RWHV.
492   if (client != GetTextInputClient())
493     return;
494
495   const uint32 event_flags = EventFlagsFromXState(ibus_state);
496
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();
501
502   uint16 ch = 0;
503   if (!(event_flags & ui::EF_CONTROL_DOWN))
504     ch = ui::GetCharacterFromXEvent(native_event);
505   if (!ch) {
506     ch = ui::GetCharacterFromKeyCode(
507         ui::KeyboardCodeFromNative(native_event), event_flags);
508   }
509
510   if (client && ch)
511     client->InsertChar(ch, event_flags);
512 }
513
514 void InputMethodIBus::ProcessUnfilteredFabricatedKeyPressEvent(
515     EventType type,
516     KeyboardCode key_code,
517     int event_flags) {
518   TextInputClient* client = GetTextInputClient();
519   DispatchFabricatedKeyEventPostIME(type, key_code, event_flags);
520
521   if (client != GetTextInputClient())
522     return;
523
524   client = GetTextInputClient();
525   const uint16 ch = ui::GetCharacterFromKeyCode(key_code, event_flags);
526   if (client && ch)
527     client->InsertChar(ch, event_flags);
528 }
529
530 void InputMethodIBus::ProcessInputMethodResult(
531     const base::NativeEvent& native_event,
532     bool handled) {
533   TextInputClient* client = GetTextInputClient();
534   DCHECK(client);
535
536   if (result_text_.length()) {
537     if (handled && NeedInsertChar()) {
538       const uint32 state =
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);
543       }
544     } else {
545       client->InsertText(result_text_);
546       composing_text_ = false;
547     }
548   }
549
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();
556     }
557   }
558
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;
563 }
564
565 bool InputMethodIBus::NeedInsertChar() const {
566   return GetTextInputClient() &&
567       (IsTextInputTypeNone() ||
568        (!composing_text_ && result_text_.length() == 1));
569 }
570
571 bool InputMethodIBus::HasInputMethodResult() const {
572   return result_text_.length() || composition_changed_;
573 }
574
575 void InputMethodIBus::AbandonAllPendingKeyEvents() {
576   pending_key_events_.clear();
577 }
578
579 void InputMethodIBus::CommitText(const std::string& text) {
580   if (suppress_next_result_ || text.empty())
581     return;
582
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())
587     return;
588
589   const string16 utf16_text = UTF8ToUTF16(text);
590   if (utf16_text.empty())
591     return;
592
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);
596
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();
602   }
603 }
604
605 void InputMethodIBus::ForwardKeyEvent(uint32 keyval,
606                                       uint32 keycode,
607                                       uint32 state) {
608   KeyboardCode ui_key_code = KeyboardCodeFromXKeysym(keyval);
609   if (!ui_key_code)
610     return;
611
612   const EventType event_type =
613       (state & kIBusReleaseMask) ? ET_KEY_RELEASED : ET_KEY_PRESSED;
614   const int event_flags = EventFlagsFromXState(state);
615
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
620   // results.
621   if (event_type == ET_KEY_PRESSED) {
622     ProcessUnfilteredFabricatedKeyPressEvent(event_type, ui_key_code,
623                                              event_flags);
624   } else {
625     DispatchFabricatedKeyEventPostIME(event_type, ui_key_code, event_flags);
626   }
627 }
628
629 void InputMethodIBus::ShowPreeditText() {
630   if (suppress_next_result_ || IsTextInputTypeNone())
631     return;
632
633   composing_text_ = true;
634 }
635
636 void InputMethodIBus::UpdatePreeditText(const chromeos::IBusText& text,
637                                         uint32 cursor_pos,
638                                         bool visible) {
639   if (suppress_next_result_ || IsTextInputTypeNone())
640     return;
641
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);
647   }
648
649   // |visible| argument is very confusing. For example, what's the correct
650   // behavior when:
651   // 1. OnUpdatePreeditText() is called with a text and visible == false, then
652   // 2. OnShowPreeditText() is called afterwards.
653   //
654   // If it's only for clearing the current preedit text, then why not just use
655   // OnHidePreeditText()?
656   if (!visible) {
657     HidePreeditText();
658     return;
659   }
660
661   ExtractCompositionText(text, cursor_pos, &composition_);
662
663   composition_changed_ = true;
664
665   // In case OnShowPreeditText() is not called.
666   if (composition_.text.length())
667     composing_text_ = true;
668
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();
675   }
676 }
677
678 void InputMethodIBus::HidePreeditText() {
679   if (composition_.text.empty() || IsTextInputTypeNone())
680     return;
681
682   // Intentionally leaves |composing_text_| unchanged.
683   composition_changed_ = true;
684   composition_.Clear();
685
686   if (pending_key_events_.empty()) {
687     TextInputClient* client = GetTextInputClient();
688     if (client && client->HasCompositionText())
689       client->ClearCompositionText();
690     composition_changed_ = false;
691   }
692 }
693
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);
701 }
702
703 bool InputMethodIBus::ExecuteCharacterComposer(uint32 ibus_keyval,
704                                                uint32 ibus_keycode,
705                                                uint32 ibus_state) {
706   bool consumed = character_composer_.FilterKeyPress(
707       ibus_keyval,
708       ibus_keycode,
709       EventFlagsFromXState(ibus_state));
710
711   suppress_next_result_ = false;
712   chromeos::IBusText preedit;
713   preedit.set_text(
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);
721   }
722   return consumed;
723 }
724
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());
731
732   if (out_composition->text.empty())
733     return;
734
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);
740   do {
741     char16_offsets.push_back(char_iterator.array_pos());
742   } while (char_iterator.Advance());
743
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);
748
749   size_t cursor_offset =
750       char16_offsets[std::min(char_length, cursor_position)];
751
752   out_composition->selection = gfx::Range(cursor_offset);
753
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();
758
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;
763       if (start >= end)
764         continue;
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);
775     }
776   }
777
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;
784       if (start >= end)
785         continue;
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);
799       }
800     }
801   }
802
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 */));
807   }
808 }
809
810 void InputMethodIBus::OnCaretBoundsChangedInternal(
811     const TextInputClient* client) {
812   if (!context_focused_ || !IsTextInputClientFocused(client))
813     return;
814
815   // The current text input type should not be NONE if |context_| is focused.
816   DCHECK(!IsTextInputTypeNone());
817   const gfx::Rect rect = GetTextInputClient()->GetCaretBounds();
818
819   gfx::Rect composition_head;
820   if (!GetTextInputClient()->GetCompositionCharacterBounds(0,
821                                                            &composition_head)) {
822     composition_head = rect;
823   }
824
825   chromeos::IBusPanelCandidateWindowHandlerInterface* candidate_window =
826       chromeos::IBusBridge::Get()->GetCandidateWindowHandler();
827   if (!candidate_window)
828     return;
829   candidate_window->SetCursorLocation(
830       GfxRectToIBusRect(rect),
831       GfxRectToIBusRect(composition_head));
832
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();
841     return;
842   }
843
844   if (previous_selection_range_ == selection_range &&
845       previous_surrounding_text_ == surrounding_text)
846     return;
847
848   previous_selection_range_ = selection_range;
849   previous_surrounding_text_ = surrounding_text;
850
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.
855     return;
856   }
857
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.
861   if (!GetEngine())
862     return;
863   GetEngine()->SetSurroundingText(
864       UTF16ToUTF8(surrounding_text),
865       selection_range.start() - text_range.start(),
866       selection_range.end() - text_range.start());
867 }
868
869 }  // namespace ui