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