gtk_im_context_wrapper.cc revision 21d179b334e59e9a3bfcaed4c4430bef1bc5759d
1// Copyright (c) 2010 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 "chrome/browser/renderer_host/gtk_im_context_wrapper.h"
6
7#include <gdk/gdk.h>
8#include <gdk/gdkkeysyms.h>
9#include <gtk/gtk.h>
10#include <algorithm>
11
12#include "app/l10n_util.h"
13#include "base/logging.h"
14#include "base/string_util.h"
15#include "base/third_party/icu/icu_utf.h"
16#include "base/utf_string_conversions.h"
17#include "chrome/app/chrome_command_ids.h"
18#include "chrome/browser/gtk/gtk_util.h"
19#if !defined(TOOLKIT_VIEWS)
20#include "chrome/browser/gtk/menu_gtk.h"
21#endif
22#include "chrome/browser/renderer_host/render_widget_host.h"
23#include "chrome/browser/renderer_host/render_widget_host_view_gtk.h"
24#include "chrome/common/native_web_keyboard_event.h"
25#include "chrome/common/render_messages.h"
26#include "gfx/gtk_util.h"
27#include "gfx/rect.h"
28#include "grit/generated_resources.h"
29#include "third_party/skia/include/core/SkColor.h"
30
31namespace {
32// Copied from third_party/WebKit/WebCore/page/EventHandler.cpp
33//
34// Match key code of composition keydown event on windows.
35// IE sends VK_PROCESSKEY which has value 229;
36//
37// Please refer to following documents for detals:
38// - Virtual-Key Codes
39//   http://msdn.microsoft.com/en-us/library/ms645540(VS.85).aspx
40// - How the IME System Works
41//   http://msdn.microsoft.com/en-us/library/cc194848.aspx
42// - ImmGetVirtualKey Function
43//   http://msdn.microsoft.com/en-us/library/dd318570(VS.85).aspx
44const int kCompositionEventKeyCode = 229;
45}  // namespace
46
47GtkIMContextWrapper::GtkIMContextWrapper(RenderWidgetHostViewGtk* host_view)
48    : host_view_(host_view),
49      context_(gtk_im_multicontext_new()),
50      context_simple_(gtk_im_context_simple_new()),
51      is_focused_(false),
52      is_composing_text_(false),
53      is_enabled_(false),
54      is_in_key_event_handler_(false),
55      preedit_selection_start_(0),
56      preedit_selection_end_(0),
57      is_preedit_changed_(false),
58      suppress_next_commit_(false) {
59  DCHECK(context_);
60  DCHECK(context_simple_);
61
62  // context_ and context_simple_ share the same callback handlers.
63  // All data come from them are treated equally.
64  // context_ is for full input method support.
65  // context_simple_ is for supporting dead/compose keys when input method is
66  // disabled by webkit, eg. in password input box.
67  g_signal_connect(context_, "preedit_start",
68                   G_CALLBACK(HandlePreeditStartThunk), this);
69  g_signal_connect(context_, "preedit_end",
70                   G_CALLBACK(HandlePreeditEndThunk), this);
71  g_signal_connect(context_, "preedit_changed",
72                   G_CALLBACK(HandlePreeditChangedThunk), this);
73  g_signal_connect(context_, "commit",
74                   G_CALLBACK(HandleCommitThunk), this);
75
76  g_signal_connect(context_simple_, "preedit_start",
77                   G_CALLBACK(HandlePreeditStartThunk), this);
78  g_signal_connect(context_simple_, "preedit_end",
79                   G_CALLBACK(HandlePreeditEndThunk), this);
80  g_signal_connect(context_simple_, "preedit_changed",
81                   G_CALLBACK(HandlePreeditChangedThunk), this);
82  g_signal_connect(context_simple_, "commit",
83                   G_CALLBACK(HandleCommitThunk), this);
84
85  GtkWidget* widget = host_view->native_view();
86  DCHECK(widget);
87
88  g_signal_connect(widget, "realize",
89                   G_CALLBACK(HandleHostViewRealizeThunk), this);
90  g_signal_connect(widget, "unrealize",
91                   G_CALLBACK(HandleHostViewUnrealizeThunk), this);
92
93  // Set client window if the widget is already realized.
94  HandleHostViewRealize(widget);
95}
96
97GtkIMContextWrapper::~GtkIMContextWrapper() {
98  if (context_)
99    g_object_unref(context_);
100  if (context_simple_)
101    g_object_unref(context_simple_);
102}
103
104void GtkIMContextWrapper::ProcessKeyEvent(GdkEventKey* event) {
105  suppress_next_commit_ = false;
106
107  // Indicates preedit-changed and commit signal handlers that we are
108  // processing a key event.
109  is_in_key_event_handler_ = true;
110  // Reset this flag so that we can know if preedit is changed after
111  // processing this key event.
112  is_preedit_changed_ = false;
113  // Clear it so that we can know if something needs committing after
114  // processing this key event.
115  commit_text_.clear();
116
117  // According to Document Object Model (DOM) Level 3 Events Specification
118  // Appendix A: Keyboard events and key identifiers
119  // http://www.w3.org/TR/DOM-Level-3-Events/keyset.html:
120  // The event sequence would be:
121  // 1. keydown
122  // 2. textInput
123  // 3. keyup
124  //
125  // So keydown must be sent to webkit before sending input method result,
126  // while keyup must be sent afterwards.
127  // However on Windows, if a keydown event has been processed by IME, its
128  // virtual keycode will be changed to VK_PROCESSKEY(0xE5) before being sent
129  // to application.
130  // To emulate the windows behavior as much as possible, we need to send the
131  // key event to the GtkIMContext object first, and decide whether or not to
132  // send the original key event to webkit according to the result from IME.
133  //
134  // If IME is enabled by WebKit, this event will be dispatched to context_
135  // to get full IME support. Otherwise it'll be dispatched to
136  // context_simple_, so that dead/compose keys can still work.
137  //
138  // It sends a "commit" signal when it has a character to be inserted
139  // even when we use a US keyboard so that we can send a Char event
140  // (or an IME event) to the renderer in our "commit"-signal handler.
141  // We should send a KeyDown (or a KeyUp) event before dispatching this
142  // event to the GtkIMContext object (and send a Char event) so that WebKit
143  // can dispatch the JavaScript events in the following order: onkeydown(),
144  // onkeypress(), and onkeyup(). (Many JavaScript pages assume this.)
145  gboolean filtered = false;
146  if (is_enabled_) {
147    filtered = gtk_im_context_filter_keypress(context_, event);
148  } else {
149    filtered = gtk_im_context_filter_keypress(context_simple_, event);
150  }
151
152  // Reset this flag here, as it's only used in input method callbacks.
153  is_in_key_event_handler_ = false;
154
155  NativeWebKeyboardEvent wke(event);
156
157  // If the key event was handled by the input method, then we need to prevent
158  // RenderView::UnhandledKeyboardEvent() from processing it.
159  // Otherwise unexpected result may occur. For example if it's a
160  // Backspace key event, the browser may go back to previous page.
161  if (filtered)
162    wke.skip_in_browser = true;
163
164  // Send filtered keydown event before sending IME result.
165  if (event->type == GDK_KEY_PRESS && filtered)
166    ProcessFilteredKeyPressEvent(&wke);
167
168  // Send IME results. In most cases, it's only available if the key event
169  // is filtered by IME. But in rare cases, an unfiltered key event may also
170  // generate IME results.
171  // Any IME results generated by a unfiltered key down event must be sent
172  // before the key down event, to avoid some tricky issues. For example,
173  // when using latin-post input method, pressing 'a' then Backspace, may
174  // generate following events in sequence:
175  //  1. keydown 'a' (filtered)
176  //  2. preedit changed to "a"
177  //  3. keyup 'a' (unfiltered)
178  //  4. keydown Backspace (unfiltered)
179  //  5. commit "a"
180  //  6. preedit end
181  //  7. keyup Backspace (unfiltered)
182  //
183  // In this case, the input box will be in a strange state if keydown
184  // Backspace is sent to webkit before commit "a" and preedit end.
185  ProcessInputMethodResult(event, filtered);
186
187  // Send unfiltered keydown and keyup events after sending IME result.
188  if (event->type == GDK_KEY_PRESS && !filtered)
189    ProcessUnfilteredKeyPressEvent(&wke);
190  else if (event->type == GDK_KEY_RELEASE)
191    host_view_->ForwardKeyboardEvent(wke);
192}
193
194void GtkIMContextWrapper::UpdateInputMethodState(WebKit::WebTextInputType type,
195                                                 const gfx::Rect& caret_rect) {
196  suppress_next_commit_ = false;
197
198  // The renderer has updated its IME status.
199  // Control the GtkIMContext object according to this status.
200  if (!context_ || !is_focused_)
201    return;
202
203  DCHECK(!is_in_key_event_handler_);
204
205  bool is_enabled = (type == WebKit::WebTextInputTypeText);
206  if (is_enabled_ != is_enabled) {
207    is_enabled_ = is_enabled;
208    if (is_enabled)
209      gtk_im_context_focus_in(context_);
210    else
211      gtk_im_context_focus_out(context_);
212  }
213
214  if (is_enabled) {
215    // Updates the position of the IME candidate window.
216    // The position sent from the renderer is a relative one, so we need to
217    // attach the GtkIMContext object to this window before changing the
218    // position.
219    GdkRectangle cursor_rect(caret_rect.ToGdkRectangle());
220    gtk_im_context_set_cursor_location(context_, &cursor_rect);
221  }
222}
223
224void GtkIMContextWrapper::OnFocusIn() {
225  if (is_focused_)
226    return;
227
228  // Tracks the focused state so that we can give focus to the
229  // GtkIMContext object correctly later when IME is enabled by WebKit.
230  is_focused_ = true;
231
232  // Notify the GtkIMContext object of this focus-in event only if IME is
233  // enabled by WebKit.
234  if (is_enabled_)
235    gtk_im_context_focus_in(context_);
236
237  // context_simple_ is always enabled.
238  // Actually it doesn't care focus state at all.
239  gtk_im_context_focus_in(context_simple_);
240
241  // Enables RenderWidget's IME related events, so that we can be notified
242  // when WebKit wants to enable or disable IME.
243  if (host_view_->GetRenderWidgetHost())
244    host_view_->GetRenderWidgetHost()->SetInputMethodActive(true);
245}
246
247void GtkIMContextWrapper::OnFocusOut() {
248  if (!is_focused_)
249    return;
250
251  // Tracks the focused state so that we won't give focus to the
252  // GtkIMContext object unexpectly.
253  is_focused_ = false;
254
255  // Notify the GtkIMContext object of this focus-out event only if IME is
256  // enabled by WebKit.
257  if (is_enabled_) {
258    // To reset the GtkIMContext object and prevent data loss.
259    ConfirmComposition();
260    gtk_im_context_focus_out(context_);
261  }
262
263  // To make sure it'll be in correct state when focused in again.
264  gtk_im_context_reset(context_simple_);
265  gtk_im_context_focus_out(context_simple_);
266
267  is_composing_text_ = false;
268
269  // Disable RenderWidget's IME related events to save bandwidth.
270  if (host_view_->GetRenderWidgetHost())
271    host_view_->GetRenderWidgetHost()->SetInputMethodActive(false);
272}
273
274#if !defined(TOOLKIT_VIEWS)
275// Not defined for views because the views context menu doesn't
276// implement input methods yet.
277void GtkIMContextWrapper::AppendInputMethodsContextMenu(MenuGtk* menu) {
278  gboolean show_input_method_menu = TRUE;
279
280  g_object_get(gtk_widget_get_settings(GTK_WIDGET(host_view_->native_view())),
281               "gtk-show-input-method-menu", &show_input_method_menu, NULL);
282  if (!show_input_method_menu)
283    return;
284
285  std::string label = gfx::ConvertAcceleratorsFromWindowsStyle(
286      l10n_util::GetStringUTF8(IDS_CONTENT_CONTEXT_INPUT_METHODS_MENU));
287  GtkWidget* menuitem = gtk_menu_item_new_with_mnemonic(label.c_str());
288  GtkWidget* submenu = gtk_menu_new();
289  gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem), submenu);
290  gtk_im_multicontext_append_menuitems(GTK_IM_MULTICONTEXT(context_),
291                                       GTK_MENU_SHELL(submenu));
292  menu->AppendSeparator();
293  menu->AppendMenuItem(IDC_INPUT_METHODS_MENU, menuitem);
294}
295#endif
296
297void GtkIMContextWrapper::CancelComposition() {
298  if (!is_enabled_)
299    return;
300
301  DCHECK(!is_in_key_event_handler_);
302
303  // To prevent any text from being committed when resetting the |context_|;
304  is_in_key_event_handler_ = true;
305  suppress_next_commit_ = true;
306
307  gtk_im_context_reset(context_);
308  gtk_im_context_reset(context_simple_);
309
310  if (is_focused_) {
311    // Some input methods may not honour the reset call. Focusing out/in the
312    // |context_| to make sure it gets reset correctly.
313    gtk_im_context_focus_out(context_);
314    gtk_im_context_focus_in(context_);
315  }
316
317  is_composing_text_ = false;
318  preedit_text_.clear();
319  preedit_underlines_.clear();
320  commit_text_.clear();
321
322  is_in_key_event_handler_ = false;
323}
324
325bool GtkIMContextWrapper::NeedCommitByForwardingCharEvent() {
326  // If there is no composition text and has only one character to be
327  // committed, then the character will be send to webkit as a Char event
328  // instead of a confirmed composition text.
329  // It should be fine to handle BMP character only, as non-BMP characters
330  // can always be committed as confirmed composition text.
331  return !is_composing_text_ && commit_text_.length() == 1;
332}
333
334void GtkIMContextWrapper::ProcessFilteredKeyPressEvent(
335    NativeWebKeyboardEvent* wke) {
336  // If IME has filtered this event, then replace virtual key code with
337  // VK_PROCESSKEY. See comment in ProcessKeyEvent() for details.
338  // It's only required for keydown events.
339  // To emulate windows behavior, when input method is enabled, if the commit
340  // text can be emulated by a Char event, then don't do this replacement.
341  if (!NeedCommitByForwardingCharEvent()) {
342    wke->windowsKeyCode = kCompositionEventKeyCode;
343    // keyidentifier must be updated accordingly, otherwise this key event may
344    // still be processed by webkit.
345    wke->setKeyIdentifierFromWindowsKeyCode();
346  }
347  host_view_->ForwardKeyboardEvent(*wke);
348}
349
350void GtkIMContextWrapper::ProcessUnfilteredKeyPressEvent(
351    NativeWebKeyboardEvent* wke) {
352  // Send keydown event as it, because it's not filtered by IME.
353  host_view_->ForwardKeyboardEvent(*wke);
354
355  // IME is disabled by WebKit or the GtkIMContext object cannot handle
356  // this key event.
357  // This case is caused by two reasons:
358  // 1. The given key event is a control-key event, (e.g. return, page up,
359  //    page down, tab, arrows, etc.) or;
360  // 2. The given key event is not a control-key event but printable
361  //    characters aren't assigned to the event, (e.g. alt+d, etc.)
362  // Create a Char event manually from this key event and send it to the
363  // renderer when this Char event contains a printable character which
364  // should be processed by WebKit.
365  // isSystemKey will be set to true if this key event has Alt modifier,
366  // see WebInputEventFactory::keyboardEvent() for details.
367  if (wke->text[0]) {
368    wke->type = WebKit::WebInputEvent::Char;
369    wke->skip_in_browser = true;
370    host_view_->ForwardKeyboardEvent(*wke);
371  }
372}
373
374void GtkIMContextWrapper::ProcessInputMethodResult(const GdkEventKey* event,
375                                                   bool filtered) {
376  RenderWidgetHost* host = host_view_->GetRenderWidgetHost();
377  if (!host)
378    return;
379
380  bool committed = false;
381  // We do commit before preedit change, so that we can optimize some
382  // unnecessary preedit changes.
383  if (commit_text_.length()) {
384    if (filtered && NeedCommitByForwardingCharEvent()) {
385      // Send a Char event when we input a composed character without IMEs
386      // so that this event is to be dispatched to onkeypress() handlers,
387      // autofill, etc.
388      // Only commit text generated by a filtered key down event can be sent
389      // as a Char event, because a unfiltered key down event will probably
390      // generate another Char event.
391      // TODO(james.su@gmail.com): Is it necessary to support non BMP chars
392      // here?
393      NativeWebKeyboardEvent char_event(commit_text_[0],
394                                        event->state,
395                                        base::Time::Now().ToDoubleT());
396      char_event.skip_in_browser = true;
397      host_view_->ForwardKeyboardEvent(char_event);
398    } else {
399      committed = true;
400      // Send an IME event.
401      // Unlike a Char event, an IME event is NOT dispatched to onkeypress()
402      // handlers or autofill.
403      host->ImeConfirmComposition(commit_text_);
404      // Set this flag to false, as this composition session has been
405      // finished.
406      is_composing_text_ = false;
407    }
408  }
409
410  // Send preedit text only if it's changed.
411  // If a text has been committed, then we don't need to send the empty
412  // preedit text again.
413  if (is_preedit_changed_) {
414    if (preedit_text_.length()) {
415      // Another composition session has been started.
416      is_composing_text_ = true;
417      host->ImeSetComposition(preedit_text_, preedit_underlines_,
418                              preedit_selection_start_, preedit_selection_end_);
419    } else if (!committed) {
420      host->ImeCancelComposition();
421    }
422  }
423}
424
425void GtkIMContextWrapper::ConfirmComposition() {
426  if (!is_enabled_)
427    return;
428
429  DCHECK(!is_in_key_event_handler_);
430
431  if (is_composing_text_) {
432    if (host_view_->GetRenderWidgetHost())
433      host_view_->GetRenderWidgetHost()->ImeConfirmComposition();
434
435    // Reset the input method.
436    CancelComposition();
437  }
438}
439
440void GtkIMContextWrapper::HandleCommit(const string16& text) {
441  if (suppress_next_commit_) {
442    suppress_next_commit_ = false;
443    return;
444  }
445
446  // Append the text to the buffer, because commit signal might be fired
447  // multiple times when processing a key event.
448  commit_text_.append(text);
449  // Nothing needs to do, if it's currently in ProcessKeyEvent()
450  // handler, which will send commit text to webkit later. Otherwise,
451  // we need send it here.
452  // It's possible that commit signal is fired without a key event, for
453  // example when user input via a voice or handwriting recognition software.
454  // In this case, the text must be committed directly.
455  if (!is_in_key_event_handler_ && host_view_->GetRenderWidgetHost()) {
456    // Workaround http://crbug.com/45478 by sending fake key down/up events.
457    SendFakeCompositionKeyEvent(WebKit::WebInputEvent::RawKeyDown);
458    host_view_->GetRenderWidgetHost()->ImeConfirmComposition(text);
459    SendFakeCompositionKeyEvent(WebKit::WebInputEvent::KeyUp);
460  }
461}
462
463void GtkIMContextWrapper::HandlePreeditStart() {
464  // Ignore preedit related signals triggered by CancelComposition() method.
465  if (suppress_next_commit_)
466    return;
467  is_composing_text_ = true;
468}
469
470void GtkIMContextWrapper::HandlePreeditChanged(const gchar* text,
471                                               PangoAttrList* attrs,
472                                               int cursor_position) {
473  // Ignore preedit related signals triggered by CancelComposition() method.
474  if (suppress_next_commit_)
475    return;
476
477  // Don't set is_preedit_changed_ to false if there is no change, because
478  // this handler might be called multiple times with the same data.
479  is_preedit_changed_ = true;
480  preedit_text_.clear();
481  preedit_underlines_.clear();
482  preedit_selection_start_ = 0;
483  preedit_selection_end_ = 0;
484
485  ExtractCompositionInfo(text, attrs, cursor_position, &preedit_text_,
486                         &preedit_underlines_, &preedit_selection_start_,
487                         &preedit_selection_end_);
488
489  // In case we are using a buggy input method which doesn't fire
490  // "preedit_start" signal.
491  if (preedit_text_.length())
492    is_composing_text_ = true;
493
494  // Nothing needs to do, if it's currently in ProcessKeyEvent()
495  // handler, which will send preedit text to webkit later.
496  // Otherwise, we need send it here if it's been changed.
497  if (!is_in_key_event_handler_ && is_composing_text_ &&
498      host_view_->GetRenderWidgetHost()) {
499    // Workaround http://crbug.com/45478 by sending fake key down/up events.
500    SendFakeCompositionKeyEvent(WebKit::WebInputEvent::RawKeyDown);
501    host_view_->GetRenderWidgetHost()->ImeSetComposition(
502        preedit_text_, preedit_underlines_, preedit_selection_start_,
503        preedit_selection_end_);
504    SendFakeCompositionKeyEvent(WebKit::WebInputEvent::KeyUp);
505  }
506}
507
508void GtkIMContextWrapper::HandlePreeditEnd() {
509  if (preedit_text_.length()) {
510    // The composition session has been finished.
511    preedit_text_.clear();
512    preedit_underlines_.clear();
513    is_preedit_changed_ = true;
514
515    // If there is still a preedit text when firing "preedit-end" signal,
516    // we need inform webkit to clear it.
517    // It's only necessary when it's not in ProcessKeyEvent ().
518    if (!is_in_key_event_handler_ && host_view_->GetRenderWidgetHost())
519      host_view_->GetRenderWidgetHost()->ImeCancelComposition();
520  }
521
522  // Don't set is_composing_text_ to false here, because "preedit_end"
523  // signal may be fired before "commit" signal.
524}
525
526void GtkIMContextWrapper::HandleHostViewRealize(GtkWidget* widget) {
527  // We should only set im context's client window once, because when setting
528  // client window.im context may destroy and recreate its internal states and
529  // objects.
530  if (widget->window) {
531    gtk_im_context_set_client_window(context_, widget->window);
532    gtk_im_context_set_client_window(context_simple_, widget->window);
533  }
534}
535
536void GtkIMContextWrapper::HandleHostViewUnrealize() {
537  gtk_im_context_set_client_window(context_, NULL);
538  gtk_im_context_set_client_window(context_simple_, NULL);
539}
540
541void GtkIMContextWrapper::SendFakeCompositionKeyEvent(
542    WebKit::WebInputEvent::Type type) {
543  NativeWebKeyboardEvent fake_event;
544  fake_event.windowsKeyCode = kCompositionEventKeyCode;
545  fake_event.skip_in_browser = true;
546  fake_event.type = type;
547  host_view_->ForwardKeyboardEvent(fake_event);
548}
549
550void GtkIMContextWrapper::HandleCommitThunk(
551    GtkIMContext* context, gchar* text, GtkIMContextWrapper* self) {
552  self->HandleCommit(UTF8ToUTF16(text));
553}
554
555void GtkIMContextWrapper::HandlePreeditStartThunk(
556    GtkIMContext* context, GtkIMContextWrapper* self) {
557  self->HandlePreeditStart();
558}
559
560void GtkIMContextWrapper::HandlePreeditChangedThunk(
561    GtkIMContext* context, GtkIMContextWrapper* self) {
562  gchar* text = NULL;
563  PangoAttrList* attrs = NULL;
564  gint cursor_position = 0;
565  gtk_im_context_get_preedit_string(context, &text, &attrs, &cursor_position);
566  self->HandlePreeditChanged(text, attrs, cursor_position);
567  g_free(text);
568  pango_attr_list_unref(attrs);
569}
570
571void GtkIMContextWrapper::HandlePreeditEndThunk(
572    GtkIMContext* context, GtkIMContextWrapper* self) {
573  self->HandlePreeditEnd();
574}
575
576void GtkIMContextWrapper::HandleHostViewRealizeThunk(
577    GtkWidget* widget, GtkIMContextWrapper* self) {
578  self->HandleHostViewRealize(widget);
579}
580
581void GtkIMContextWrapper::HandleHostViewUnrealizeThunk(
582    GtkWidget* widget, GtkIMContextWrapper* self) {
583  self->HandleHostViewUnrealize();
584}
585
586void GtkIMContextWrapper::ExtractCompositionInfo(
587      const gchar* utf8_text,
588      PangoAttrList* attrs,
589      int cursor_position,
590      string16* utf16_text,
591      std::vector<WebKit::WebCompositionUnderline>* underlines,
592      int* selection_start,
593      int* selection_end) {
594  *utf16_text = UTF8ToUTF16(utf8_text);
595
596  if (utf16_text->empty())
597    return;
598
599  // Gtk/Pango uses character index for cursor position and byte index for
600  // attribute range, but we use char16 offset for them. So we need to do
601  // conversion here.
602  std::vector<int> char16_offsets;
603  int length = static_cast<int>(utf16_text->length());
604  for (int offset = 0; offset < length; ++offset) {
605    char16_offsets.push_back(offset);
606    if (CBU16_IS_SURROGATE((*utf16_text)[offset]))
607      ++offset;
608  }
609
610  // The text length in Unicode characters.
611  int char_length = static_cast<int>(char16_offsets.size());
612  // Make sure we can convert the value of |char_length| as well.
613  char16_offsets.push_back(length);
614
615  int cursor_offset =
616      char16_offsets[std::max(0, std::min(char_length, cursor_position))];
617
618  // TODO(suzhe): due to a bug of webkit, we currently can't use selection range
619  // with composition string. See: https://bugs.webkit.org/show_bug.cgi?id=40805
620  *selection_start = *selection_end = cursor_offset;
621
622  if (attrs) {
623    int utf8_length = strlen(utf8_text);
624    PangoAttrIterator* iter = pango_attr_list_get_iterator(attrs);
625
626    // We only care about underline and background attributes and convert
627    // background attribute into selection if possible.
628    do {
629      gint start, end;
630      pango_attr_iterator_range(iter, &start, &end);
631
632      start = std::min(start, utf8_length);
633      end = std::min(end, utf8_length);
634      if (start >= end)
635        continue;
636
637      start = g_utf8_pointer_to_offset(utf8_text, utf8_text + start);
638      end = g_utf8_pointer_to_offset(utf8_text, utf8_text + end);
639
640      // Double check, in case |utf8_text| is not a valid utf-8 string.
641      start = std::min(start, char_length);
642      end = std::min(end, char_length);
643      if (start >= end)
644        continue;
645
646      PangoAttribute* background_attr =
647          pango_attr_iterator_get(iter, PANGO_ATTR_BACKGROUND);
648      PangoAttribute* underline_attr =
649          pango_attr_iterator_get(iter, PANGO_ATTR_UNDERLINE);
650
651      if (background_attr || underline_attr) {
652        // Use a black thin underline by default.
653        WebKit::WebCompositionUnderline underline(
654            char16_offsets[start], char16_offsets[end], SK_ColorBLACK, false);
655
656        // Always use thick underline for a range with background color, which
657        // is usually the selection range.
658        if (background_attr)
659          underline.thick = true;
660        if (underline_attr) {
661          int type = reinterpret_cast<PangoAttrInt*>(underline_attr)->value;
662          if (type == PANGO_UNDERLINE_DOUBLE)
663            underline.thick = true;
664          else if (type == PANGO_UNDERLINE_ERROR)
665            underline.color = SK_ColorRED;
666        }
667        underlines->push_back(underline);
668      }
669    } while (pango_attr_iterator_next(iter));
670    pango_attr_iterator_destroy(iter);
671  }
672
673  // Use a black thin underline by default.
674  if (underlines->empty()) {
675    underlines->push_back(
676        WebKit::WebCompositionUnderline(0, length, SK_ColorBLACK, false));
677  }
678}
679