omnibox_view_views.cc revision d0247b1b59f9c528cb6df88b4f2b9afaf80d181e
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 "chrome/browser/ui/views/omnibox/omnibox_view_views.h"
6
7#include "base/command_line.h"
8#include "base/logging.h"
9#include "base/strings/string_util.h"
10#include "base/strings/utf_string_conversions.h"
11#include "chrome/app/chrome_command_ids.h"
12#include "chrome/browser/autocomplete/autocomplete_input.h"
13#include "chrome/browser/autocomplete/autocomplete_match.h"
14#include "chrome/browser/bookmarks/bookmark_node_data.h"
15#include "chrome/browser/command_updater.h"
16#include "chrome/browser/search/search.h"
17#include "chrome/browser/ui/omnibox/omnibox_edit_controller.h"
18#include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
19#include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
20#include "chrome/browser/ui/view_ids.h"
21#include "chrome/browser/ui/views/location_bar/location_bar_view.h"
22#include "chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h"
23#include "chrome/common/chrome_switches.h"
24#include "content/public/browser/web_contents.h"
25#include "extensions/common/constants.h"
26#include "grit/app_locale_settings.h"
27#include "grit/generated_resources.h"
28#include "grit/ui_strings.h"
29#include "net/base/escape.h"
30#include "third_party/skia/include/core/SkColor.h"
31#include "ui/base/accessibility/accessible_view_state.h"
32#include "ui/base/clipboard/scoped_clipboard_writer.h"
33#include "ui/base/dragdrop/drag_drop_types.h"
34#include "ui/base/dragdrop/os_exchange_data.h"
35#include "ui/base/ime/text_input_client.h"
36#include "ui/base/ime/text_input_type.h"
37#include "ui/base/l10n/l10n_util.h"
38#include "ui/base/models/simple_menu_model.h"
39#include "ui/base/resource/resource_bundle.h"
40#include "ui/events/event.h"
41#include "ui/gfx/canvas.h"
42#include "ui/gfx/font_list.h"
43#include "ui/gfx/selection_model.h"
44#include "ui/views/border.h"
45#include "ui/views/button_drag_utils.h"
46#include "ui/views/controls/textfield/textfield.h"
47#include "ui/views/ime/input_method.h"
48#include "ui/views/layout/fill_layout.h"
49#include "ui/views/views_delegate.h"
50#include "ui/views/widget/widget.h"
51#include "url/gurl.h"
52
53#if defined(OS_WIN)
54#include "base/win/metro.h"
55#include "chrome/browser/browser_process.h"
56#endif
57
58#if defined(USE_AURA)
59#include "ui/aura/focus_manager.h"
60#include "ui/aura/root_window.h"
61#include "ui/compositor/layer.h"
62#endif
63
64namespace {
65
66// Stores omnibox state for each tab.
67struct OmniboxState : public base::SupportsUserData::Data {
68  static const char kKey[];
69
70  OmniboxState(const OmniboxEditModel::State& model_state,
71               const gfx::SelectionModel& selection_model);
72  virtual ~OmniboxState();
73
74  const OmniboxEditModel::State model_state;
75  const gfx::SelectionModel selection_model;
76};
77
78// static
79const char OmniboxState::kKey[] = "OmniboxState";
80
81OmniboxState::OmniboxState(const OmniboxEditModel::State& model_state,
82                           const gfx::SelectionModel& selection_model)
83    : model_state(model_state),
84      selection_model(selection_model) {
85}
86
87OmniboxState::~OmniboxState() {}
88
89// We'd like to set the text input type to TEXT_INPUT_TYPE_URL, because this
90// triggers URL-specific layout in software keyboards, e.g. adding top-level "/"
91// and ".com" keys for English.  However, this also causes IMEs to default to
92// Latin character mode, which makes entering search queries difficult for IME
93// users.  Therefore, we try to guess whether an IME will be used based on the
94// application language, and set the input type accordingly.
95ui::TextInputType DetermineTextInputType() {
96#if defined(OS_WIN)
97  if (base::win::IsTSFAwareRequired()) {
98    DCHECK(g_browser_process);
99    const std::string& locale = g_browser_process->GetApplicationLocale();
100    const std::string& language = locale.substr(0, 2);
101    // Assume CJK + Thai users are using an IME.
102    if (language == "ja" ||
103        language == "ko" ||
104        language == "th" ||
105        language == "zh")
106      return ui::TEXT_INPUT_TYPE_SEARCH;
107  }
108#endif
109  return ui::TEXT_INPUT_TYPE_URL;
110}
111
112bool IsOmniboxAutoCompletionForImeEnabled() {
113  return !CommandLine::ForCurrentProcess()->HasSwitch(
114      switches::kDisableOmniboxAutoCompletionForIme);
115}
116
117}  // namespace
118
119// static
120const char OmniboxViewViews::kViewClassName[] = "OmniboxViewViews";
121
122OmniboxViewViews::OmniboxViewViews(OmniboxEditController* controller,
123                                   Profile* profile,
124                                   CommandUpdater* command_updater,
125                                   bool popup_window_mode,
126                                   LocationBarView* location_bar,
127                                   const gfx::FontList& font_list,
128                                   int font_y_offset)
129    : OmniboxView(profile, controller, command_updater),
130      popup_window_mode_(popup_window_mode),
131      security_level_(ToolbarModel::NONE),
132      ime_composing_before_change_(false),
133      delete_at_end_pressed_(false),
134      location_bar_view_(location_bar),
135      ime_candidate_window_open_(false),
136      select_all_on_mouse_release_(false),
137      select_all_on_gesture_tap_(false) {
138  RemoveBorder();
139  set_id(VIEW_ID_OMNIBOX);
140  SetFontList(font_list);
141  SetVerticalMargins(font_y_offset, 0);
142  SetVerticalAlignment(gfx::ALIGN_TOP);
143}
144
145OmniboxViewViews::~OmniboxViewViews() {
146#if defined(OS_CHROMEOS)
147  chromeos::input_method::InputMethodManager::Get()->
148      RemoveCandidateWindowObserver(this);
149#endif
150
151  // Explicitly teardown members which have a reference to us.  Just to be safe
152  // we want them to be destroyed before destroying any other internal state.
153  popup_view_.reset();
154}
155
156////////////////////////////////////////////////////////////////////////////////
157// OmniboxViewViews public:
158
159void OmniboxViewViews::Init() {
160  SetController(this);
161  SetTextInputType(DetermineTextInputType());
162  SetBackgroundColor(location_bar_view_->GetColor(
163      ToolbarModel::NONE, LocationBarView::BACKGROUND));
164
165  if (popup_window_mode_)
166    SetReadOnly(true);
167
168  // Initialize the popup view using the same font.
169  popup_view_.reset(OmniboxPopupContentsView::Create(
170      font_list(), this, model(), location_bar_view_));
171
172#if defined(OS_CHROMEOS)
173  chromeos::input_method::InputMethodManager::Get()->
174      AddCandidateWindowObserver(this);
175#endif
176}
177
178////////////////////////////////////////////////////////////////////////////////
179// OmniboxViewViews, views::Textfield implementation:
180
181const char* OmniboxViewViews::GetClassName() const {
182  return kViewClassName;
183}
184
185void OmniboxViewViews::OnGestureEvent(ui::GestureEvent* event) {
186  views::Textfield::OnGestureEvent(event);
187  if (!HasFocus() && event->type() == ui::ET_GESTURE_TAP_DOWN) {
188    select_all_on_gesture_tap_ = true;
189    return;
190  }
191  if (select_all_on_gesture_tap_ && event->type() == ui::ET_GESTURE_TAP)
192    SelectAll(false);
193  select_all_on_gesture_tap_ = false;
194}
195
196void OmniboxViewViews::GetAccessibleState(ui::AccessibleViewState* state) {
197  location_bar_view_->GetAccessibleState(state);
198  state->role = ui::AccessibilityTypes::ROLE_TEXT;
199}
200
201bool OmniboxViewViews::OnMousePressed(const ui::MouseEvent& event) {
202  select_all_on_mouse_release_ =
203      (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) &&
204      (!HasFocus() || (model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE));
205  // Restore caret visibility whenever the user clicks in the omnibox in a way
206  // that would give it focus.  We must handle this case separately here because
207  // if the omnibox currently has invisible focus, the mouse event won't trigger
208  // either SetFocus() or OmniboxEditModel::OnSetFocus().
209  if (select_all_on_mouse_release_)
210    model()->SetCaretVisibility(true);
211  return views::Textfield::OnMousePressed(event);
212}
213
214bool OmniboxViewViews::OnMouseDragged(const ui::MouseEvent& event) {
215  select_all_on_mouse_release_ = false;
216  return views::Textfield::OnMouseDragged(event);
217}
218
219void OmniboxViewViews::OnMouseReleased(const ui::MouseEvent& event) {
220  views::Textfield::OnMouseReleased(event);
221  // When the user has clicked and released to give us focus, select all unless
222  // we're doing search term replacement (in which case refining the existing
223  // query is common enough that we do click-to-place-cursor).
224  if ((event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) &&
225      select_all_on_mouse_release_ &&
226      !controller()->GetToolbarModel()->WouldPerformSearchTermReplacement(
227          false)) {
228    // Select all in the reverse direction so as not to scroll the caret
229    // into view and shift the contents jarringly.
230    SelectAll(true);
231  }
232  select_all_on_mouse_release_ = false;
233}
234
235bool OmniboxViewViews::OnKeyPressed(const ui::KeyEvent& event) {
236  // Skip processing of [Alt]+<num-pad digit> Unicode alt key codes.
237  // Otherwise, if num-lock is off, the events are handled as [Up], [Down], etc.
238  if (event.IsUnicodeKeyCode())
239    return views::Textfield::OnKeyPressed(event);
240
241  switch (event.key_code()) {
242    case ui::VKEY_RETURN:
243      model()->AcceptInput(event.IsAltDown() ? NEW_FOREGROUND_TAB : CURRENT_TAB,
244                           false);
245      return true;
246    case ui::VKEY_ESCAPE:
247      return model()->OnEscapeKeyPressed();
248    case ui::VKEY_CONTROL:
249      model()->OnControlKeyChanged(true);
250      break;
251    case ui::VKEY_DELETE:
252      if (event.IsShiftDown() && model()->popup_model()->IsOpen())
253        model()->popup_model()->TryDeletingCurrentItem();
254      break;
255    case ui::VKEY_UP:
256      model()->OnUpOrDownKeyPressed(-1);
257      return true;
258    case ui::VKEY_DOWN:
259      model()->OnUpOrDownKeyPressed(1);
260      return true;
261    case ui::VKEY_PRIOR:
262      if (event.IsControlDown() || event.IsAltDown() ||
263          event.IsShiftDown()) {
264        return false;
265      }
266      model()->OnUpOrDownKeyPressed(-1 * model()->result().size());
267      return true;
268    case ui::VKEY_NEXT:
269      if (event.IsControlDown() || event.IsAltDown() ||
270          event.IsShiftDown()) {
271        return false;
272      }
273      model()->OnUpOrDownKeyPressed(model()->result().size());
274      return true;
275    case ui::VKEY_V:
276      if (event.IsControlDown() && !read_only()) {
277        OnBeforePossibleChange();
278        OnPaste();
279        OnAfterPossibleChange();
280        return true;
281      }
282      break;
283    default:
284      break;
285  }
286
287  bool handled = views::Textfield::OnKeyPressed(event);
288#if !defined(OS_WIN) || defined(USE_AURA)
289  // TODO(msw): Avoid this complexity, consolidate cross-platform behavior.
290  handled |= SkipDefaultKeyEventProcessing(event);
291#endif
292  return handled;
293}
294
295bool OmniboxViewViews::OnKeyReleased(const ui::KeyEvent& event) {
296  // The omnibox contents may change while the control key is pressed.
297  if (event.key_code() == ui::VKEY_CONTROL)
298    model()->OnControlKeyChanged(false);
299  return views::Textfield::OnKeyReleased(event);
300}
301
302bool OmniboxViewViews::SkipDefaultKeyEventProcessing(
303    const ui::KeyEvent& event) {
304  // Handle keyword hint tab-to-search and tabbing through dropdown results.
305  // This must run before acclerator handling invokes a focus change on tab.
306  if (views::FocusManager::IsTabTraversalKeyEvent(event)) {
307    if (model()->is_keyword_hint() && !event.IsShiftDown()) {
308      model()->AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_TAB);
309      return true;
310    }
311    if (model()->popup_model()->IsOpen()) {
312      if (event.IsShiftDown() &&
313          model()->popup_model()->selected_line_state() ==
314              OmniboxPopupModel::KEYWORD) {
315        model()->ClearKeyword(text());
316      } else {
317        model()->OnUpOrDownKeyPressed(event.IsShiftDown() ? -1 : 1);
318      }
319      return true;
320    }
321  }
322
323  return Textfield::SkipDefaultKeyEventProcessing(event);
324}
325
326void OmniboxViewViews::OnFocus() {
327  views::Textfield::OnFocus();
328  // TODO(oshima): Get control key state.
329  model()->OnSetFocus(false);
330  // Don't call controller()->OnSetFocus, this view has already acquired focus.
331
332  // Restore a valid saved selection on tab-to-focus.
333  if (location_bar_view_->GetWebContents() && !select_all_on_mouse_release_) {
334    const OmniboxState* state = static_cast<OmniboxState*>(
335        location_bar_view_->GetWebContents()->GetUserData(&OmniboxState::kKey));
336    if (state)
337      SelectSelectionModel(state->selection_model);
338  }
339}
340
341void OmniboxViewViews::OnBlur() {
342  // Save the selection to restore on tab-to-focus.
343  if (location_bar_view_->GetWebContents())
344    SaveStateToTab(location_bar_view_->GetWebContents());
345
346  views::Textfield::OnBlur();
347  gfx::NativeView native_view = NULL;
348#if defined(USE_AURA)
349  views::Widget* widget = GetWidget();
350  if (widget) {
351    aura::client::FocusClient* client =
352        aura::client::GetFocusClient(widget->GetNativeView());
353    if (client)
354      native_view = client->GetFocusedWindow();
355  }
356#endif
357  model()->OnWillKillFocus(native_view);
358  // Close the popup.
359  CloseOmniboxPopup();
360  // Tell the model to reset itself.
361  model()->OnKillFocus();
362  controller()->OnKillFocus();
363
364  // Make sure the beginning of the text is visible.
365  SelectRange(gfx::Range(0));
366}
367
368////////////////////////////////////////////////////////////////////////////////
369// OmniboxViewViews, OmniboxView implementation:
370
371void OmniboxViewViews::SaveStateToTab(content::WebContents* tab) {
372  DCHECK(tab);
373
374  // We don't want to keep the IME status, so force quit the current
375  // session here.  It may affect the selection status, so order is
376  // also important.
377  if (IsIMEComposing()) {
378    GetTextInputClient()->ConfirmCompositionText();
379    GetInputMethod()->CancelComposition(this);
380  }
381
382  // NOTE: GetStateForTabSwitch may affect GetSelection, so order is important.
383  OmniboxEditModel::State state = model()->GetStateForTabSwitch();
384  const gfx::SelectionModel selection = GetSelectionModel();
385  tab->SetUserData(OmniboxState::kKey, new OmniboxState(state, selection));
386}
387
388void OmniboxViewViews::OnTabChanged(const content::WebContents* web_contents) {
389  security_level_ = controller()->GetToolbarModel()->GetSecurityLevel(false);
390
391  const OmniboxState* state = static_cast<OmniboxState*>(
392      web_contents->GetUserData(&OmniboxState::kKey));
393  model()->RestoreState(state ? &state->model_state : NULL);
394  if (state)
395    SelectSelectionModel(state->selection_model);
396
397  // TODO(msw|oshima): Consider saving/restoring edit history.
398  ClearEditHistory();
399}
400
401void OmniboxViewViews::Update() {
402  const ToolbarModel::SecurityLevel old_security_level = security_level_;
403  security_level_ = controller()->GetToolbarModel()->GetSecurityLevel(false);
404  if (model()->UpdatePermanentText()) {
405    // Something visibly changed.  Re-enable search term replacement.
406    controller()->GetToolbarModel()->set_search_term_replacement_enabled(true);
407    model()->UpdatePermanentText();
408
409    // Tweak: if the user had all the text selected, select all the new text.
410    // This makes one particular case better: the user clicks in the box to
411    // change it right before the permanent URL is changed.  Since the new URL
412    // is still fully selected, the user's typing will replace the edit contents
413    // as they'd intended.
414    const gfx::Range range(GetSelectedRange());
415    const bool was_select_all = (range.length() == text().length());
416
417    RevertAll();
418
419    // Only select all when we have focus.  If we don't have focus, selecting
420    // all is unnecessary since the selection will change on regaining focus,
421    // and can in fact cause artifacts, e.g. if the user is on the NTP and
422    // clicks a link to navigate, causing |was_select_all| to be vacuously true
423    // for the empty omnibox, and we then select all here, leading to the
424    // trailing portion of a long URL being scrolled into view.  We could try
425    // and address cases like this, but it seems better to just not muck with
426    // things when the omnibox isn't focused to begin with.
427    if (was_select_all && model()->has_focus())
428      SelectAll(range.is_reversed());
429  } else if (old_security_level != security_level_) {
430    EmphasizeURLComponents();
431  }
432}
433
434string16 OmniboxViewViews::GetText() const {
435  // TODO(oshima): IME support
436  return text();
437}
438
439void OmniboxViewViews::SetWindowTextAndCaretPos(const string16& text,
440                                                size_t caret_pos,
441                                                bool update_popup,
442                                                bool notify_text_changed) {
443  const gfx::Range range(caret_pos, caret_pos);
444  SetTextAndSelectedRange(text, range);
445
446  if (update_popup)
447    UpdatePopup();
448
449  if (notify_text_changed)
450    TextChanged();
451}
452
453void OmniboxViewViews::SetForcedQuery() {
454  const string16 current_text(text());
455  const size_t start = current_text.find_first_not_of(kWhitespaceUTF16);
456  if (start == string16::npos || (current_text[start] != '?'))
457    SetUserText(ASCIIToUTF16("?"));
458  else
459    SelectRange(gfx::Range(current_text.size(), start + 1));
460}
461
462bool OmniboxViewViews::IsSelectAll() const {
463  // TODO(oshima): IME support.
464  return text() == GetSelectedText();
465}
466
467bool OmniboxViewViews::DeleteAtEndPressed() {
468  return delete_at_end_pressed_;
469}
470
471void OmniboxViewViews::GetSelectionBounds(string16::size_type* start,
472                                          string16::size_type* end) const {
473  const gfx::Range range = GetSelectedRange();
474  *start = static_cast<size_t>(range.start());
475  *end = static_cast<size_t>(range.end());
476}
477
478void OmniboxViewViews::SelectAll(bool reversed) {
479  views::Textfield::SelectAll(reversed);
480}
481
482void OmniboxViewViews::UpdatePopup() {
483  model()->SetInputInProgress(true);
484  if (!model()->has_focus())
485    return;
486
487  // Hide the inline autocompletion for IME users.
488  location_bar_view_->SetImeInlineAutocompletion(string16());
489
490  // Prevent inline autocomplete when the caret isn't at the end of the text,
491  // and during IME composition editing unless
492  // |kEnableOmniboxAutoCompletionForIme| is enabled.
493  const gfx::Range sel = GetSelectedRange();
494  model()->StartAutocomplete(
495      !sel.is_empty(),
496      sel.GetMax() < text().length() ||
497      (IsIMEComposing() && !IsOmniboxAutoCompletionForImeEnabled()));
498}
499
500void OmniboxViewViews::SetFocus() {
501  RequestFocus();
502  // Restore caret visibility if focus is explicitly requested. This is
503  // necessary because if we already have invisible focus, the RequestFocus()
504  // call above will short-circuit, preventing us from reaching
505  // OmniboxEditModel::OnSetFocus(), which handles restoring visibility when the
506  // omnibox regains focus after losing focus.
507  model()->SetCaretVisibility(true);
508}
509
510void OmniboxViewViews::ApplyCaretVisibility() {
511  SetCursorEnabled(model()->is_caret_visible());
512}
513
514void OmniboxViewViews::OnTemporaryTextMaybeChanged(
515    const string16& display_text,
516    bool save_original_selection,
517    bool notify_text_changed) {
518  if (save_original_selection)
519    saved_temporary_selection_ = GetSelectedRange();
520
521  SetWindowTextAndCaretPos(display_text, display_text.length(), false,
522                           notify_text_changed);
523}
524
525bool OmniboxViewViews::OnInlineAutocompleteTextMaybeChanged(
526    const string16& display_text,
527    size_t user_text_length) {
528  if (display_text == text())
529    return false;
530
531  if (IsIMEComposing()) {
532    location_bar_view_->SetImeInlineAutocompletion(
533        display_text.substr(user_text_length));
534  } else {
535    gfx::Range range(display_text.size(), user_text_length);
536    SetTextAndSelectedRange(display_text, range);
537  }
538  TextChanged();
539  return true;
540}
541
542void OmniboxViewViews::OnRevertTemporaryText() {
543  SelectRange(saved_temporary_selection_);
544  // We got here because the user hit the Escape key. We explicitly don't call
545  // TextChanged(), since OmniboxPopupModel::ResetToDefaultMatch() has already
546  // been called by now, and it would've called TextChanged() if it was
547  // warranted.
548}
549
550void OmniboxViewViews::OnBeforePossibleChange() {
551  // Record our state.
552  text_before_change_ = text();
553  sel_before_change_ = GetSelectedRange();
554  ime_composing_before_change_ = IsIMEComposing();
555}
556
557bool OmniboxViewViews::OnAfterPossibleChange() {
558  // See if the text or selection have changed since OnBeforePossibleChange().
559  const string16 new_text = text();
560  const gfx::Range new_sel = GetSelectedRange();
561  const bool text_changed = (new_text != text_before_change_) ||
562      (ime_composing_before_change_ != IsIMEComposing());
563  const bool selection_differs =
564      !((sel_before_change_.is_empty() && new_sel.is_empty()) ||
565        sel_before_change_.EqualsIgnoringDirection(new_sel));
566
567  // When the user has deleted text, we don't allow inline autocomplete.  Make
568  // sure to not flag cases like selecting part of the text and then pasting
569  // (or typing) the prefix of that selection.  (We detect these by making
570  // sure the caret, which should be after any insertion, hasn't moved
571  // forward of the old selection start.)
572  const bool just_deleted_text =
573      (text_before_change_.length() > new_text.length()) &&
574      (new_sel.start() <= sel_before_change_.GetMin());
575
576  const bool something_changed = model()->OnAfterPossibleChange(
577      text_before_change_, new_text, new_sel.start(), new_sel.end(),
578      selection_differs, text_changed, just_deleted_text, !IsIMEComposing());
579
580  // If only selection was changed, we don't need to call model()'s
581  // OnChanged() method, which is called in TextChanged().
582  // But we still need to call EmphasizeURLComponents() to make sure the text
583  // attributes are updated correctly.
584  if (something_changed && text_changed)
585    TextChanged();
586  else if (selection_differs)
587    EmphasizeURLComponents();
588  else if (delete_at_end_pressed_)
589    model()->OnChanged();
590
591  return something_changed;
592}
593
594gfx::NativeView OmniboxViewViews::GetNativeView() const {
595  return GetWidget()->GetNativeView();
596}
597
598gfx::NativeView OmniboxViewViews::GetRelativeWindowForPopup() const {
599  return GetWidget()->GetTopLevelWidget()->GetNativeView();
600}
601
602void OmniboxViewViews::SetGrayTextAutocompletion(const string16& input) {
603#if defined(OS_WIN) || defined(USE_AURA)
604  location_bar_view_->SetGrayTextAutocompletion(input);
605#endif
606}
607
608string16 OmniboxViewViews::GetGrayTextAutocompletion() const {
609#if defined(OS_WIN) || defined(USE_AURA)
610  return location_bar_view_->GetGrayTextAutocompletion();
611#else
612  return string16();
613#endif
614}
615
616int OmniboxViewViews::TextWidth() const {
617  return native_wrapper_->GetWidthNeededForText();
618}
619
620bool OmniboxViewViews::IsImeComposing() const {
621  return IsIMEComposing();
622}
623
624bool OmniboxViewViews::IsImeShowingPopup() const {
625#if defined(OS_CHROMEOS)
626  return ime_candidate_window_open_;
627#else
628  const views::InputMethod* input_method = this->GetInputMethod();
629  return input_method && input_method->IsCandidatePopupOpen();
630#endif
631}
632
633int OmniboxViewViews::GetMaxEditWidth(int entry_width) const {
634  return entry_width;
635}
636
637views::View* OmniboxViewViews::AddToView(views::View* parent) {
638  parent->AddChildView(this);
639  return this;
640}
641
642int OmniboxViewViews::OnPerformDrop(const ui::DropTargetEvent& event) {
643  NOTIMPLEMENTED();
644  return ui::DragDropTypes::DRAG_NONE;
645}
646
647////////////////////////////////////////////////////////////////////////////////
648// OmniboxViewViews, views::TextfieldController implementation:
649
650void OmniboxViewViews::ContentsChanged(views::Textfield* sender,
651                                       const string16& new_contents) {
652}
653
654bool OmniboxViewViews::HandleKeyEvent(views::Textfield* textfield,
655                                      const ui::KeyEvent& event) {
656  delete_at_end_pressed_ = false;
657
658  if (event.key_code() == ui::VKEY_BACK) {
659    // No extra handling is needed in keyword search mode, if there is a
660    // non-empty selection, or if the cursor is not leading the text.
661    if (model()->is_keyword_hint() || model()->keyword().empty() ||
662        HasSelection() || GetCursorPosition() != 0)
663      return false;
664    model()->ClearKeyword(text());
665    return true;
666  }
667
668  if (event.key_code() == ui::VKEY_DELETE && !event.IsAltDown()) {
669    delete_at_end_pressed_ =
670        (!HasSelection() && GetCursorPosition() == text().length());
671  }
672
673  // Handle the right-arrow key for LTR text and the left-arrow key for RTL text
674  // if there is gray text that needs to be committed.
675  if (GetCursorPosition() == text().length()) {
676    base::i18n::TextDirection direction = GetTextDirection();
677    if ((direction == base::i18n::LEFT_TO_RIGHT &&
678         event.key_code() == ui::VKEY_RIGHT) ||
679        (direction == base::i18n::RIGHT_TO_LEFT &&
680         event.key_code() == ui::VKEY_LEFT)) {
681      return model()->CommitSuggestedText();
682    }
683  }
684
685  return false;
686}
687
688void OmniboxViewViews::OnBeforeUserAction(views::Textfield* sender) {
689  OnBeforePossibleChange();
690}
691
692void OmniboxViewViews::OnAfterUserAction(views::Textfield* sender) {
693  OnAfterPossibleChange();
694}
695
696void OmniboxViewViews::OnAfterCutOrCopy() {
697  ui::Clipboard* cb = ui::Clipboard::GetForCurrentThread();
698  string16 selected_text;
699  cb->ReadText(ui::Clipboard::BUFFER_STANDARD, &selected_text);
700  GURL url;
701  bool write_url;
702  model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
703                             &selected_text, &url, &write_url);
704  if (write_url) {
705    BookmarkNodeData data;
706    data.ReadFromTuple(url, selected_text);
707    data.WriteToClipboard();
708  } else {
709    ui::ScopedClipboardWriter scoped_clipboard_writer(
710        ui::Clipboard::GetForCurrentThread(), ui::Clipboard::BUFFER_STANDARD);
711    scoped_clipboard_writer.WriteText(selected_text);
712  }
713}
714
715void OmniboxViewViews::OnGetDragOperationsForTextfield(int* drag_operations) {
716  string16 selected_text = GetSelectedText();
717  GURL url;
718  bool write_url;
719  model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
720                             &selected_text, &url, &write_url);
721  if (write_url)
722    *drag_operations |= ui::DragDropTypes::DRAG_LINK;
723}
724
725void OmniboxViewViews::OnWriteDragData(ui::OSExchangeData* data) {
726  string16 selected_text = GetSelectedText();
727  GURL url;
728  bool write_url;
729  bool is_all_selected = IsSelectAll();
730  model()->AdjustTextForCopy(GetSelectedRange().GetMin(), is_all_selected,
731                             &selected_text, &url, &write_url);
732  data->SetString(selected_text);
733  if (write_url) {
734    gfx::Image favicon;
735    string16 title = selected_text;
736    if (is_all_selected)
737      model()->GetDataForURLExport(&url, &title, &favicon);
738    button_drag_utils::SetURLAndDragImage(url, title, favicon.AsImageSkia(),
739                                          data, GetWidget());
740    data->SetURL(url, title);
741  }
742}
743
744void OmniboxViewViews::AppendDropFormats(
745    int* formats,
746    std::set<ui::OSExchangeData::CustomFormat>* custom_formats) {
747  *formats = *formats | ui::OSExchangeData::URL;
748}
749
750int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) {
751  if (HasTextBeingDragged())
752    return ui::DragDropTypes::DRAG_NONE;
753
754  if (data.HasURL()) {
755    GURL url;
756    string16 title;
757    if (data.GetURLAndTitle(&url, &title)) {
758      string16 text(StripJavascriptSchemas(UTF8ToUTF16(url.spec())));
759      if (model()->CanPasteAndGo(text)) {
760        model()->PasteAndGo(text);
761        return ui::DragDropTypes::DRAG_COPY;
762      }
763    }
764  } else if (data.HasString()) {
765    string16 text;
766    if (data.GetString(&text)) {
767      string16 collapsed_text(CollapseWhitespace(text, true));
768      if (model()->CanPasteAndGo(collapsed_text))
769        model()->PasteAndGo(collapsed_text);
770      return ui::DragDropTypes::DRAG_COPY;
771    }
772  }
773
774  return ui::DragDropTypes::DRAG_NONE;
775}
776
777void OmniboxViewViews::UpdateContextMenu(ui::SimpleMenuModel* menu_contents) {
778  int paste_position = menu_contents->GetIndexOfCommandId(IDS_APP_PASTE);
779  DCHECK_GE(paste_position, 0);
780  menu_contents->InsertItemWithStringIdAt(
781      paste_position + 1, IDS_PASTE_AND_GO, IDS_PASTE_AND_GO);
782
783  menu_contents->AddSeparator(ui::NORMAL_SEPARATOR);
784
785  if (chrome::IsQueryExtractionEnabled()) {
786    int select_all_position = menu_contents->GetIndexOfCommandId(
787        IDS_APP_SELECT_ALL);
788    DCHECK_GE(select_all_position, 0);
789    menu_contents->InsertItemWithStringIdAt(
790        select_all_position + 1, IDS_SHOW_URL, IDS_SHOW_URL);
791  }
792
793  // Minor note: We use IDC_ for command id here while the underlying textfield
794  // is using IDS_ for all its command ids. This is because views cannot depend
795  // on IDC_ for now.
796  menu_contents->AddItemWithStringId(IDC_EDIT_SEARCH_ENGINES,
797      IDS_EDIT_SEARCH_ENGINES);
798}
799
800bool OmniboxViewViews::IsCommandIdEnabled(int command_id) const {
801  if (command_id == IDS_PASTE_AND_GO)
802    return model()->CanPasteAndGo(GetClipboardText());
803  if (command_id != IDS_SHOW_URL)
804    return command_updater()->IsCommandEnabled(command_id);
805  return controller()->GetToolbarModel()->WouldPerformSearchTermReplacement(
806      false);
807}
808
809bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id) const {
810  return command_id == IDS_PASTE_AND_GO;
811}
812
813string16 OmniboxViewViews::GetLabelForCommandId(int command_id) const {
814  DCHECK_EQ(IDS_PASTE_AND_GO, command_id);
815  return l10n_util::GetStringUTF16(
816      model()->IsPasteAndSearch(GetClipboardText()) ?
817          IDS_PASTE_AND_SEARCH : IDS_PASTE_AND_GO);
818}
819
820bool OmniboxViewViews::HandlesCommand(int command_id) const {
821  // See description in OnPaste() for details on why we need to handle paste.
822  return command_id == IDS_APP_PASTE;
823}
824
825void OmniboxViewViews::ExecuteCommand(int command_id, int event_flags) {
826  switch (command_id) {
827    // These commands don't invoke the popup via OnBefore/AfterPossibleChange().
828    case IDS_PASTE_AND_GO:
829      model()->PasteAndGo(GetClipboardText());
830      break;
831    case IDS_SHOW_URL:
832      ShowURL();
833      break;
834    case IDC_EDIT_SEARCH_ENGINES:
835      command_updater()->ExecuteCommand(command_id);
836      break;
837
838    default:
839      OnBeforePossibleChange();
840      if (command_id == IDS_APP_PASTE)
841        OnPaste();
842      else
843        command_updater()->ExecuteCommand(command_id);
844      OnAfterPossibleChange();
845      break;
846  }
847}
848
849#if defined(OS_CHROMEOS)
850void OmniboxViewViews::CandidateWindowOpened(
851      chromeos::input_method::InputMethodManager* manager) {
852  ime_candidate_window_open_ = true;
853}
854
855void OmniboxViewViews::CandidateWindowClosed(
856      chromeos::input_method::InputMethodManager* manager) {
857  ime_candidate_window_open_ = false;
858}
859#endif
860
861////////////////////////////////////////////////////////////////////////////////
862// OmniboxViewViews, private:
863
864int OmniboxViewViews::GetOmniboxTextLength() const {
865  // TODO(oshima): Support IME.
866  return static_cast<int>(text().length());
867}
868
869void OmniboxViewViews::EmphasizeURLComponents() {
870  // See whether the contents are a URL with a non-empty host portion, which we
871  // should emphasize.  To check for a URL, rather than using the type returned
872  // by Parse(), ask the model, which will check the desired page transition for
873  // this input.  This can tell us whether an UNKNOWN input string is going to
874  // be treated as a search or a navigation, and is the same method the Paste
875  // And Go system uses.
876  url_parse::Component scheme, host;
877  AutocompleteInput::ParseForEmphasizeComponents(text(), &scheme, &host);
878  bool grey_out_url = text().substr(scheme.begin, scheme.len) ==
879      UTF8ToUTF16(extensions::kExtensionScheme);
880  bool grey_base = model()->CurrentTextIsURL() &&
881      (host.is_nonempty() || grey_out_url);
882  SetColor(location_bar_view_->GetColor(
883      security_level_,
884      grey_base ? LocationBarView::DEEMPHASIZED_TEXT : LocationBarView::TEXT));
885  if (grey_base && !grey_out_url) {
886    ApplyColor(
887        location_bar_view_->GetColor(security_level_, LocationBarView::TEXT),
888        gfx::Range(host.begin, host.end()));
889  }
890
891  // Emphasize the scheme for security UI display purposes (if necessary).
892  // Note that we check CurrentTextIsURL() because if we're replacing search
893  // URLs with search terms, we may have a non-URL even when the user is not
894  // editing; and in some cases, e.g. for "site:foo.com" searches, the parser
895  // may have incorrectly identified a qualifier as a scheme.
896  SetStyle(gfx::DIAGONAL_STRIKE, false);
897  if (!model()->user_input_in_progress() && model()->CurrentTextIsURL() &&
898      scheme.is_nonempty() && (security_level_ != ToolbarModel::NONE)) {
899    SkColor security_color = location_bar_view_->GetColor(
900        security_level_, LocationBarView::SECURITY_TEXT);
901    const bool strike = (security_level_ == ToolbarModel::SECURITY_ERROR);
902    const gfx::Range scheme_range(scheme.begin, scheme.end());
903    ApplyColor(security_color, scheme_range);
904    ApplyStyle(gfx::DIAGONAL_STRIKE, strike, scheme_range);
905  }
906}
907
908void OmniboxViewViews::SetTextAndSelectedRange(const string16& text,
909                                               const gfx::Range& range) {
910  SetText(text);
911  SelectRange(range);
912}
913
914string16 OmniboxViewViews::GetSelectedText() const {
915  // TODO(oshima): Support IME.
916  return views::Textfield::GetSelectedText();
917}
918
919void OmniboxViewViews::OnPaste() {
920  const string16 text(GetClipboardText());
921  if (!text.empty()) {
922    // Record this paste, so we can do different behavior.
923    model()->on_paste();
924    // Force a Paste operation to trigger the text_changed code in
925    // OnAfterPossibleChange(), even if identical contents are pasted.
926    text_before_change_.clear();
927    InsertOrReplaceText(text);
928  }
929}
930