• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <algorithm>
8 #include <cstring>
9 #include <set>
10 #include <vector>
11 
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/third_party/icu/icu_utf.h"
19 #include "chromeos/ime/ibus_text.h"
20 #include "chromeos/ime/input_method_descriptor.h"
21 #include "chromeos/ime/input_method_manager.h"
22 #include "ui/base/ime/text_input_client.h"
23 #include "ui/events/event.h"
24 #include "ui/events/event_constants.h"
25 #include "ui/events/event_utils.h"
26 #include "ui/events/keycodes/keyboard_code_conversion.h"
27 #include "ui/events/keycodes/keyboard_code_conversion_x.h"
28 #include "ui/events/keycodes/keyboard_codes.h"
29 #include "ui/gfx/rect.h"
30 
31 namespace {
GetEngine()32 chromeos::IBusEngineHandlerInterface* GetEngine() {
33   return chromeos::IBusBridge::Get()->GetCurrentEngineHandler();
34 }
35 }  // namespace
36 
37 namespace ui {
38 
39 // InputMethodIBus implementation -----------------------------------------
InputMethodIBus(internal::InputMethodDelegate * delegate)40 InputMethodIBus::InputMethodIBus(
41     internal::InputMethodDelegate* delegate)
42     : context_focused_(false),
43       composing_text_(false),
44       composition_changed_(false),
45       suppress_next_result_(false),
46       current_keyevent_id_(0),
47       previous_textinput_type_(TEXT_INPUT_TYPE_NONE),
48       weak_ptr_factory_(this) {
49   SetDelegate(delegate);
50   chromeos::IBusBridge::Get()->SetInputContextHandler(this);
51 
52   UpdateContextFocusState();
53   OnInputMethodChanged();
54 }
55 
~InputMethodIBus()56 InputMethodIBus::~InputMethodIBus() {
57   AbandonAllPendingKeyEvents();
58   context_focused_ = false;
59   ConfirmCompositionText();
60   // We are dead, so we need to ask the client to stop relying on us.
61   OnInputMethodChanged();
62 
63   chromeos::IBusBridge::Get()->SetInputContextHandler(NULL);
64 }
65 
OnFocus()66 void InputMethodIBus::OnFocus() {
67   InputMethodBase::OnFocus();
68   UpdateContextFocusState();
69 }
70 
OnBlur()71 void InputMethodIBus::OnBlur() {
72   ConfirmCompositionText();
73   InputMethodBase::OnBlur();
74   UpdateContextFocusState();
75 }
76 
OnUntranslatedIMEMessage(const base::NativeEvent & event,NativeEventResult * result)77 bool InputMethodIBus::OnUntranslatedIMEMessage(const base::NativeEvent& event,
78                                                NativeEventResult* result) {
79   return false;
80 }
81 
ProcessKeyEventDone(uint32 id,ui::KeyEvent * event,bool is_handled)82 void InputMethodIBus::ProcessKeyEventDone(uint32 id,
83                                           ui::KeyEvent* event,
84                                           bool is_handled) {
85   if (pending_key_events_.find(id) == pending_key_events_.end())
86    return;  // Abandoned key event.
87 
88   DCHECK(event);
89   if (event->type() == ET_KEY_PRESSED) {
90     if (is_handled) {
91       // IME event has a priority to be handled, so that character composer
92       // should be reset.
93       character_composer_.Reset();
94     } else {
95       // If IME does not handle key event, passes keyevent to character composer
96       // to be able to compose complex characters.
97       is_handled = ExecuteCharacterComposer(*event);
98     }
99   }
100 
101   if (event->type() == ET_KEY_PRESSED || event->type() == ET_KEY_RELEASED)
102     ProcessKeyEventPostIME(*event, is_handled);
103 
104   // ProcessKeyEventPostIME may change the |pending_key_events_|.
105   pending_key_events_.erase(id);
106 }
107 
DispatchKeyEvent(const ui::KeyEvent & event)108 bool InputMethodIBus::DispatchKeyEvent(const ui::KeyEvent& event) {
109   DCHECK(event.type() == ET_KEY_PRESSED || event.type() == ET_KEY_RELEASED);
110   DCHECK(system_toplevel_window_focused());
111 
112   // If |context_| is not usable, then we can only dispatch the key event as is.
113   // We also dispatch the key event directly if the current text input type is
114   // TEXT_INPUT_TYPE_PASSWORD, to bypass the input method.
115   // Note: We need to send the key event to ibus even if the |context_| is not
116   // enabled, so that ibus can have a chance to enable the |context_|.
117   if (!context_focused_ || !GetEngine() ||
118       GetTextInputType() == TEXT_INPUT_TYPE_PASSWORD ) {
119     if (event.type() == ET_KEY_PRESSED) {
120       if (ExecuteCharacterComposer(event)) {
121         // Treating as PostIME event if character composer handles key event and
122         // generates some IME event,
123         ProcessKeyEventPostIME(event, true);
124         return true;
125       }
126       ProcessUnfilteredKeyPressEvent(event);
127     } else {
128       DispatchKeyEventPostIME(event);
129     }
130     return true;
131   }
132 
133   pending_key_events_.insert(current_keyevent_id_);
134 
135   ui::KeyEvent* copied_event = new ui::KeyEvent(event);
136   GetEngine()->ProcessKeyEvent(
137       event,
138       base::Bind(&InputMethodIBus::ProcessKeyEventDone,
139                  weak_ptr_factory_.GetWeakPtr(),
140                  current_keyevent_id_,
141                  // Pass the ownership of |copied_event|.
142                  base::Owned(copied_event)));
143 
144   ++current_keyevent_id_;
145 
146   // We don't want to suppress the result generated by this key event, but it
147   // may cause problem. See comment in ResetContext() method.
148   suppress_next_result_ = false;
149   return true;
150 }
151 
OnTextInputTypeChanged(const TextInputClient * client)152 void InputMethodIBus::OnTextInputTypeChanged(const TextInputClient* client) {
153   if (IsTextInputClientFocused(client)) {
154     ResetContext();
155     UpdateContextFocusState();
156     if (previous_textinput_type_ != client->GetTextInputType())
157       OnInputMethodChanged();
158     previous_textinput_type_ = client->GetTextInputType();
159   }
160   InputMethodBase::OnTextInputTypeChanged(client);
161 }
162 
OnCaretBoundsChanged(const TextInputClient * client)163 void InputMethodIBus::OnCaretBoundsChanged(const TextInputClient* client) {
164   if (!context_focused_ || !IsTextInputClientFocused(client))
165     return;
166 
167   // The current text input type should not be NONE if |context_| is focused.
168   DCHECK(!IsTextInputTypeNone());
169   const gfx::Rect rect = GetTextInputClient()->GetCaretBounds();
170 
171   gfx::Rect composition_head;
172   if (!GetTextInputClient()->GetCompositionCharacterBounds(0,
173                                                            &composition_head)) {
174     composition_head = rect;
175   }
176 
177   chromeos::IBusPanelCandidateWindowHandlerInterface* candidate_window =
178       chromeos::IBusBridge::Get()->GetCandidateWindowHandler();
179   if (!candidate_window)
180     return;
181   candidate_window->SetCursorBounds(rect, composition_head);
182 
183   gfx::Range text_range;
184   gfx::Range selection_range;
185   string16 surrounding_text;
186   if (!GetTextInputClient()->GetTextRange(&text_range) ||
187       !GetTextInputClient()->GetTextFromRange(text_range, &surrounding_text) ||
188       !GetTextInputClient()->GetSelectionRange(&selection_range)) {
189     previous_surrounding_text_.clear();
190     previous_selection_range_ = gfx::Range::InvalidRange();
191     return;
192   }
193 
194   if (previous_selection_range_ == selection_range &&
195       previous_surrounding_text_ == surrounding_text)
196     return;
197 
198   previous_selection_range_ = selection_range;
199   previous_surrounding_text_ = surrounding_text;
200 
201   if (!selection_range.IsValid()) {
202     // TODO(nona): Ideally selection_range should not be invalid.
203     // TODO(nona): If javascript changes the focus on page loading, even (0,0)
204     //             can not be obtained. Need investigation.
205     return;
206   }
207 
208   // Here SetSurroundingText accepts relative position of |surrounding_text|, so
209   // we have to convert |selection_range| from node coordinates to
210   // |surrounding_text| coordinates.
211   if (!GetEngine())
212     return;
213   GetEngine()->SetSurroundingText(UTF16ToUTF8(surrounding_text),
214                                   selection_range.start() - text_range.start(),
215                                   selection_range.end() - text_range.start());
216 }
217 
CancelComposition(const TextInputClient * client)218 void InputMethodIBus::CancelComposition(const TextInputClient* client) {
219   if (context_focused_ && IsTextInputClientFocused(client))
220     ResetContext();
221 }
222 
OnInputLocaleChanged()223 void InputMethodIBus::OnInputLocaleChanged() {
224   // Not supported.
225 }
226 
GetInputLocale()227 std::string InputMethodIBus::GetInputLocale() {
228   // Not supported.
229   return "";
230 }
231 
GetInputTextDirection()232 base::i18n::TextDirection InputMethodIBus::GetInputTextDirection() {
233   // Not supported.
234   return base::i18n::UNKNOWN_DIRECTION;
235 }
236 
IsActive()237 bool InputMethodIBus::IsActive() {
238   return true;
239 }
240 
IsCandidatePopupOpen() const241 bool InputMethodIBus::IsCandidatePopupOpen() const {
242   // TODO(yukishiino): Implement this method.
243   return false;
244 }
245 
OnWillChangeFocusedClient(TextInputClient * focused_before,TextInputClient * focused)246 void InputMethodIBus::OnWillChangeFocusedClient(TextInputClient* focused_before,
247                                                 TextInputClient* focused) {
248   ConfirmCompositionText();
249 }
250 
OnDidChangeFocusedClient(TextInputClient * focused_before,TextInputClient * focused)251 void InputMethodIBus::OnDidChangeFocusedClient(TextInputClient* focused_before,
252                                                TextInputClient* focused) {
253   // Force to update the input type since client's TextInputStateChanged()
254   // function might not be called if text input types before the client loses
255   // focus and after it acquires focus again are the same.
256   OnTextInputTypeChanged(focused);
257 
258   UpdateContextFocusState();
259   // Force to update caret bounds, in case the client thinks that the caret
260   // bounds has not changed.
261   OnCaretBoundsChanged(focused);
262 }
263 
ConfirmCompositionText()264 void InputMethodIBus::ConfirmCompositionText() {
265   TextInputClient* client = GetTextInputClient();
266   if (client && client->HasCompositionText())
267     client->ConfirmCompositionText();
268 
269   ResetContext();
270 }
271 
ResetContext()272 void InputMethodIBus::ResetContext() {
273   if (!context_focused_ || !GetTextInputClient())
274     return;
275 
276   DCHECK(system_toplevel_window_focused());
277 
278   // Because ibus runs in asynchronous mode, the input method may still send us
279   // results after sending out the reset request, so we use a flag to discard
280   // all results generated by previous key events. But because ibus does not
281   // have a mechanism to identify each key event and corresponding results, this
282   // approach will not work for some corner cases. For example if the user types
283   // very fast, then the next key event may come in before the |context_| is
284   // really reset. Then we actually cannot know whether or not the next
285   // result should be discard.
286   suppress_next_result_ = true;
287 
288   composition_.Clear();
289   result_text_.clear();
290   composing_text_ = false;
291   composition_changed_ = false;
292 
293   // We need to abandon all pending key events, but as above comment says, there
294   // is no reliable way to abandon all results generated by these abandoned key
295   // events.
296   AbandonAllPendingKeyEvents();
297 
298   // This function runs asynchronously.
299   // Note: some input method engines may not support reset method, such as
300   // ibus-anthy. But as we control all input method engines by ourselves, we can
301   // make sure that all of the engines we are using support it correctly.
302   if (GetEngine())
303     GetEngine()->Reset();
304 
305   character_composer_.Reset();
306 }
307 
UpdateContextFocusState()308 void InputMethodIBus::UpdateContextFocusState() {
309   const bool old_context_focused = context_focused_;
310   const TextInputType current_text_input_type = GetTextInputType();
311   // Use switch here in case we are going to add more text input types.
312   switch (current_text_input_type) {
313     case TEXT_INPUT_TYPE_NONE:
314     case TEXT_INPUT_TYPE_PASSWORD:
315       context_focused_ = false;
316       break;
317     default:
318       context_focused_ = true;
319       break;
320   }
321 
322   // Propagate the focus event to the candidate window handler which also
323   // manages the input method mode indicator.
324   chromeos::IBusPanelCandidateWindowHandlerInterface* candidate_window =
325       chromeos::IBusBridge::Get()->GetCandidateWindowHandler();
326   if (candidate_window)
327     candidate_window->FocusStateChanged(context_focused_);
328 
329   if (!GetEngine())
330     return;
331 
332   // We only focus in |context_| when the focus is in a normal textfield.
333   // Even if focus is not changed, a text input type change causes a focus
334   // blink.
335   // ibus_input_context_focus_{in|out}() run asynchronously.
336   bool input_type_change =
337       (current_text_input_type != previous_textinput_type_);
338   if (old_context_focused && (!context_focused_ || input_type_change))
339     GetEngine()->FocusOut();
340   if (context_focused_ && (!old_context_focused || input_type_change)) {
341     chromeos::IBusEngineHandlerInterface::InputContext context(
342         current_text_input_type, GetTextInputMode());
343     GetEngine()->FocusIn(context);
344     OnCaretBoundsChanged(GetTextInputClient());
345   }
346 }
347 
ProcessKeyEventPostIME(const ui::KeyEvent & event,bool handled)348 void InputMethodIBus::ProcessKeyEventPostIME(
349     const ui::KeyEvent& event,
350     bool handled) {
351   TextInputClient* client = GetTextInputClient();
352   if (!client) {
353     // As ibus works asynchronously, there is a chance that the focused client
354     // loses focus before this method gets called.
355     DispatchKeyEventPostIME(event);
356     return;
357   }
358 
359   if (event.type() == ET_KEY_PRESSED && handled)
360     ProcessFilteredKeyPressEvent(event);
361 
362   // In case the focus was changed by the key event. The |context_| should have
363   // been reset when the focused window changed.
364   if (client != GetTextInputClient())
365     return;
366 
367   if (HasInputMethodResult())
368     ProcessInputMethodResult(event, handled);
369 
370   // In case the focus was changed when sending input method results to the
371   // focused window.
372   if (client != GetTextInputClient())
373     return;
374 
375   if (event.type() == ET_KEY_PRESSED && !handled)
376     ProcessUnfilteredKeyPressEvent(event);
377   else if (event.type() == ET_KEY_RELEASED)
378     DispatchKeyEventPostIME(event);
379 }
380 
ProcessFilteredKeyPressEvent(const ui::KeyEvent & event)381 void InputMethodIBus::ProcessFilteredKeyPressEvent(const ui::KeyEvent& event) {
382   if (NeedInsertChar()) {
383     DispatchKeyEventPostIME(event);
384   } else {
385     const ui::KeyEvent fabricated_event(ET_KEY_PRESSED,
386                                         VKEY_PROCESSKEY,
387                                         event.flags(),
388                                         false);  // is_char
389     DispatchKeyEventPostIME(fabricated_event);
390   }
391 }
392 
ProcessUnfilteredKeyPressEvent(const ui::KeyEvent & event)393 void InputMethodIBus::ProcessUnfilteredKeyPressEvent(
394     const ui::KeyEvent& event) {
395   const TextInputClient* prev_client = GetTextInputClient();
396   DispatchKeyEventPostIME(event);
397 
398   // We shouldn't dispatch the character anymore if the key event dispatch
399   // caused focus change. For example, in the following scenario,
400   // 1. visit a web page which has a <textarea>.
401   // 2. click Omnibox.
402   // 3. enable Korean IME, press A, then press Tab to move the focus to the web
403   //    page.
404   // We should return here not to send the Tab key event to RWHV.
405   TextInputClient* client = GetTextInputClient();
406   if (!client || client != prev_client)
407     return;
408 
409   // If a key event was not filtered by |context_| and |character_composer_|,
410   // then it means the key event didn't generate any result text. So we need
411   // to send corresponding character to the focused text input client.
412   const uint32 event_flags = event.flags();
413   uint16 ch = 0;
414   if (event.HasNativeEvent()) {
415     const base::NativeEvent& native_event = event.native_event();
416 
417     if (!(event_flags & ui::EF_CONTROL_DOWN))
418       ch = ui::GetCharacterFromXEvent(native_event);
419     if (!ch) {
420       ch = ui::GetCharacterFromKeyCode(
421           ui::KeyboardCodeFromNative(native_event), event_flags);
422     }
423   } else {
424     ch = ui::GetCharacterFromKeyCode(event.key_code(), event_flags);
425   }
426 
427   if (ch)
428     client->InsertChar(ch, event_flags);
429 }
430 
ProcessInputMethodResult(const ui::KeyEvent & event,bool handled)431 void InputMethodIBus::ProcessInputMethodResult(const ui::KeyEvent& event,
432                                                bool handled) {
433   TextInputClient* client = GetTextInputClient();
434   DCHECK(client);
435 
436   if (result_text_.length()) {
437     if (handled && NeedInsertChar()) {
438       for (string16::const_iterator i = result_text_.begin();
439            i != result_text_.end(); ++i) {
440         client->InsertChar(*i, event.flags());
441       }
442     } else {
443       client->InsertText(result_text_);
444       composing_text_ = false;
445     }
446   }
447 
448   if (composition_changed_ && !IsTextInputTypeNone()) {
449     if (composition_.text.length()) {
450       composing_text_ = true;
451       client->SetCompositionText(composition_);
452     } else if (result_text_.empty()) {
453       client->ClearCompositionText();
454     }
455   }
456 
457   // We should not clear composition text here, as it may belong to the next
458   // composition session.
459   result_text_.clear();
460   composition_changed_ = false;
461 }
462 
NeedInsertChar() const463 bool InputMethodIBus::NeedInsertChar() const {
464   return GetTextInputClient() &&
465       (IsTextInputTypeNone() ||
466        (!composing_text_ && result_text_.length() == 1));
467 }
468 
HasInputMethodResult() const469 bool InputMethodIBus::HasInputMethodResult() const {
470   return result_text_.length() || composition_changed_;
471 }
472 
AbandonAllPendingKeyEvents()473 void InputMethodIBus::AbandonAllPendingKeyEvents() {
474   pending_key_events_.clear();
475 }
476 
CommitText(const std::string & text)477 void InputMethodIBus::CommitText(const std::string& text) {
478   if (suppress_next_result_ || text.empty())
479     return;
480 
481   // We need to receive input method result even if the text input type is
482   // TEXT_INPUT_TYPE_NONE, to make sure we can always send correct
483   // character for each key event to the focused text input client.
484   if (!GetTextInputClient())
485     return;
486 
487   const string16 utf16_text = UTF8ToUTF16(text);
488   if (utf16_text.empty())
489     return;
490 
491   // Append the text to the buffer, because commit signal might be fired
492   // multiple times when processing a key event.
493   result_text_.append(utf16_text);
494 
495   // If we are not handling key event, do not bother sending text result if the
496   // focused text input client does not support text input.
497   if (pending_key_events_.empty() && !IsTextInputTypeNone()) {
498     GetTextInputClient()->InsertText(utf16_text);
499     result_text_.clear();
500   }
501 }
502 
UpdatePreeditText(const chromeos::IBusText & text,uint32 cursor_pos,bool visible)503 void InputMethodIBus::UpdatePreeditText(const chromeos::IBusText& text,
504                                         uint32 cursor_pos,
505                                         bool visible) {
506   if (suppress_next_result_ || IsTextInputTypeNone())
507     return;
508 
509   if (!CanComposeInline()) {
510     chromeos::IBusPanelCandidateWindowHandlerInterface* candidate_window =
511         chromeos::IBusBridge::Get()->GetCandidateWindowHandler();
512     if (candidate_window)
513       candidate_window->UpdatePreeditText(text.text(), cursor_pos, visible);
514   }
515 
516   // |visible| argument is very confusing. For example, what's the correct
517   // behavior when:
518   // 1. OnUpdatePreeditText() is called with a text and visible == false, then
519   // 2. OnShowPreeditText() is called afterwards.
520   //
521   // If it's only for clearing the current preedit text, then why not just use
522   // OnHidePreeditText()?
523   if (!visible) {
524     HidePreeditText();
525     return;
526   }
527 
528   ExtractCompositionText(text, cursor_pos, &composition_);
529 
530   composition_changed_ = true;
531 
532   // In case OnShowPreeditText() is not called.
533   if (composition_.text.length())
534     composing_text_ = true;
535 
536   // If we receive a composition text without pending key event, then we need to
537   // send it to the focused text input client directly.
538   if (pending_key_events_.empty()) {
539     GetTextInputClient()->SetCompositionText(composition_);
540     composition_changed_ = false;
541     composition_.Clear();
542   }
543 }
544 
HidePreeditText()545 void InputMethodIBus::HidePreeditText() {
546   if (composition_.text.empty() || IsTextInputTypeNone())
547     return;
548 
549   // Intentionally leaves |composing_text_| unchanged.
550   composition_changed_ = true;
551   composition_.Clear();
552 
553   if (pending_key_events_.empty()) {
554     TextInputClient* client = GetTextInputClient();
555     if (client && client->HasCompositionText())
556       client->ClearCompositionText();
557     composition_changed_ = false;
558   }
559 }
560 
DeleteSurroundingText(int32 offset,uint32 length)561 void InputMethodIBus::DeleteSurroundingText(int32 offset, uint32 length) {
562   if (!composition_.text.empty())
563     return;  // do nothing if there is ongoing composition.
564   if (offset < 0 && static_cast<uint32>(-1 * offset) != length)
565     return;  // only preceding text can be deletable.
566   if (GetTextInputClient())
567     GetTextInputClient()->ExtendSelectionAndDelete(length, 0U);
568 }
569 
ExecuteCharacterComposer(const ui::KeyEvent & event)570 bool InputMethodIBus::ExecuteCharacterComposer(const ui::KeyEvent& event) {
571   bool consumed = character_composer_.FilterKeyPress(event);
572 
573   suppress_next_result_ = false;
574   chromeos::IBusText preedit;
575   preedit.set_text(
576       UTF16ToUTF8(character_composer_.preedit_string()));
577   UpdatePreeditText(preedit, preedit.text().size(),
578                     !preedit.text().empty());
579    std::string commit_text =
580       UTF16ToUTF8(character_composer_.composed_character());
581   if (!commit_text.empty()) {
582     CommitText(commit_text);
583   }
584   return consumed;
585 }
586 
ExtractCompositionText(const chromeos::IBusText & text,uint32 cursor_position,CompositionText * out_composition) const587 void InputMethodIBus::ExtractCompositionText(
588     const chromeos::IBusText& text,
589     uint32 cursor_position,
590     CompositionText* out_composition) const {
591   out_composition->Clear();
592   out_composition->text = UTF8ToUTF16(text.text());
593 
594   if (out_composition->text.empty())
595     return;
596 
597   // ibus uses character index for cursor position and attribute range, but we
598   // use char16 offset for them. So we need to do conversion here.
599   std::vector<size_t> char16_offsets;
600   size_t length = out_composition->text.length();
601   base::i18n::UTF16CharIterator char_iterator(&out_composition->text);
602   do {
603     char16_offsets.push_back(char_iterator.array_pos());
604   } while (char_iterator.Advance());
605 
606   // The text length in Unicode characters.
607   uint32 char_length = static_cast<uint32>(char16_offsets.size());
608   // Make sure we can convert the value of |char_length| as well.
609   char16_offsets.push_back(length);
610 
611   size_t cursor_offset =
612       char16_offsets[std::min(char_length, cursor_position)];
613 
614   out_composition->selection = gfx::Range(cursor_offset);
615 
616   const std::vector<chromeos::IBusText::UnderlineAttribute>&
617       underline_attributes = text.underline_attributes();
618   if (!underline_attributes.empty()) {
619     for (size_t i = 0; i < underline_attributes.size(); ++i) {
620       const uint32 start = underline_attributes[i].start_index;
621       const uint32 end = underline_attributes[i].end_index;
622       if (start >= end)
623         continue;
624       CompositionUnderline underline(
625           char16_offsets[start], char16_offsets[end],
626           SK_ColorBLACK, false /* thick */);
627       if (underline_attributes[i].type ==
628           chromeos::IBusText::IBUS_TEXT_UNDERLINE_DOUBLE)
629         underline.thick = true;
630       else if (underline_attributes[i].type ==
631                chromeos::IBusText::IBUS_TEXT_UNDERLINE_ERROR)
632         underline.color = SK_ColorRED;
633       out_composition->underlines.push_back(underline);
634     }
635   }
636 
637   DCHECK(text.selection_start() <= text.selection_end());
638   if (text.selection_start() < text.selection_end()) {
639     const uint32 start = text.selection_start();
640     const uint32 end = text.selection_end();
641     CompositionUnderline underline(
642         char16_offsets[start], char16_offsets[end],
643         SK_ColorBLACK, true /* thick */);
644     out_composition->underlines.push_back(underline);
645 
646     // If the cursor is at start or end of this underline, then we treat
647     // it as the selection range as well, but make sure to set the cursor
648     // position to the selection end.
649     if (underline.start_offset == cursor_offset) {
650       out_composition->selection.set_start(underline.end_offset);
651       out_composition->selection.set_end(cursor_offset);
652     } else if (underline.end_offset == cursor_offset) {
653       out_composition->selection.set_start(underline.start_offset);
654       out_composition->selection.set_end(cursor_offset);
655     }
656   }
657 
658   // Use a black thin underline by default.
659   if (out_composition->underlines.empty()) {
660     out_composition->underlines.push_back(CompositionUnderline(
661         0, length, SK_ColorBLACK, false /* thick */));
662   }
663 }
664 
665 }  // namespace ui
666