omnibox_view_views.cc revision 424c4d7b64af9d0d8fd9624f381f469654d5e3d2
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(ui::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      controller()->GetToolbarModel()->GetText(true))) {
385    // Tweak: if the user had all the text selected, select all the new text.
386    // This makes one particular case better: the user clicks in the box to
387    // change it right before the permanent URL is changed.  Since the new URL
388    // is still fully selected, the user's typing will replace the edit contents
389    // as they'd intended.
390    const ui::Range range(GetSelectedRange());
391    const bool was_select_all = (range.length() == text().length());
392
393    RevertAll();
394
395    // Only select all when we have focus.  If we don't have focus, selecting
396    // all is unnecessary since the selection will change on regaining focus,
397    // and can in fact cause artifacts, e.g. if the user is on the NTP and
398    // clicks a link to navigate, causing |was_select_all| to be vacuously true
399    // for the empty omnibox, and we then select all here, leading to the
400    // trailing portion of a long URL being scrolled into view.  We could try
401    // and address cases like this, but it seems better to just not muck with
402    // things when the omnibox isn't focused to begin with.
403    if (was_select_all && model()->has_focus())
404      SelectAll(range.is_reversed());
405  } else if (old_security_level != security_level_) {
406    EmphasizeURLComponents();
407  }
408}
409
410string16 OmniboxViewViews::GetText() const {
411  // TODO(oshima): IME support
412  return text();
413}
414
415void OmniboxViewViews::SetWindowTextAndCaretPos(const string16& text,
416                                                size_t caret_pos,
417                                                bool update_popup,
418                                                bool notify_text_changed) {
419  const ui::Range range(caret_pos, caret_pos);
420  SetTextAndSelectedRange(text, range);
421
422  if (update_popup)
423    UpdatePopup();
424
425  if (notify_text_changed)
426    TextChanged();
427}
428
429void OmniboxViewViews::SetForcedQuery() {
430  const string16 current_text(text());
431  const size_t start = current_text.find_first_not_of(kWhitespaceUTF16);
432  if (start == string16::npos || (current_text[start] != '?'))
433    SetUserText(ASCIIToUTF16("?"));
434  else
435    SelectRange(ui::Range(current_text.size(), start + 1));
436}
437
438bool OmniboxViewViews::IsSelectAll() const {
439  // TODO(oshima): IME support.
440  return text() == GetSelectedText();
441}
442
443bool OmniboxViewViews::DeleteAtEndPressed() {
444  return delete_at_end_pressed_;
445}
446
447void OmniboxViewViews::GetSelectionBounds(string16::size_type* start,
448                                          string16::size_type* end) const {
449  const ui::Range range = GetSelectedRange();
450  *start = static_cast<size_t>(range.start());
451  *end = static_cast<size_t>(range.end());
452}
453
454void OmniboxViewViews::SelectAll(bool reversed) {
455  views::Textfield::SelectAll(reversed);
456}
457
458void OmniboxViewViews::UpdatePopup() {
459  model()->SetInputInProgress(true);
460  if (!model()->has_focus())
461    return;
462
463  // Hide the inline autocompletion for IME users.
464  location_bar_view_->SetImeInlineAutocompletion(string16());
465
466  // Prevent inline autocomplete when the caret isn't at the end of the text,
467  // and during IME composition editing unless
468  // |kEnableOmniboxAutoCompletionForIme| is enabled.
469  const ui::Range sel = GetSelectedRange();
470  model()->StartAutocomplete(
471      !sel.is_empty(),
472      sel.GetMax() < text().length() ||
473      (IsIMEComposing() && !IsOmniboxAutoCompletionForImeEnabled()));
474}
475
476void OmniboxViewViews::SetFocus() {
477  RequestFocus();
478  // Restore caret visibility if focus is explicitly requested. This is
479  // necessary because if we already have invisible focus, the RequestFocus()
480  // call above will short-circuit, preventing us from reaching
481  // OmniboxEditModel::OnSetFocus(), which handles restoring visibility when the
482  // omnibox regains focus after losing focus.
483  model()->SetCaretVisibility(true);
484}
485
486void OmniboxViewViews::ApplyCaretVisibility() {
487  SetCursorEnabled(model()->is_caret_visible());
488}
489
490void OmniboxViewViews::OnTemporaryTextMaybeChanged(
491    const string16& display_text,
492    bool save_original_selection,
493    bool notify_text_changed) {
494  if (save_original_selection)
495    saved_temporary_selection_ = GetSelectedRange();
496
497  SetWindowTextAndCaretPos(display_text, display_text.length(), false,
498                           notify_text_changed);
499}
500
501bool OmniboxViewViews::OnInlineAutocompleteTextMaybeChanged(
502    const string16& display_text,
503    size_t user_text_length) {
504  if (display_text == text())
505    return false;
506
507  if (IsIMEComposing()) {
508    location_bar_view_->SetImeInlineAutocompletion(
509        display_text.substr(user_text_length));
510  } else {
511    ui::Range range(display_text.size(), user_text_length);
512    SetTextAndSelectedRange(display_text, range);
513  }
514  TextChanged();
515  return true;
516}
517
518void OmniboxViewViews::OnRevertTemporaryText() {
519  SelectRange(saved_temporary_selection_);
520  // We got here because the user hit the Escape key. We explicitly don't call
521  // TextChanged(), since OmniboxPopupModel::ResetToDefaultMatch() has already
522  // been called by now, and it would've called TextChanged() if it was
523  // warranted.
524}
525
526void OmniboxViewViews::OnBeforePossibleChange() {
527  // Record our state.
528  text_before_change_ = text();
529  sel_before_change_ = GetSelectedRange();
530  ime_composing_before_change_ = IsIMEComposing();
531}
532
533bool OmniboxViewViews::OnAfterPossibleChange() {
534  // See if the text or selection have changed since OnBeforePossibleChange().
535  const string16 new_text = text();
536  const ui::Range new_sel = GetSelectedRange();
537  const bool text_changed = (new_text != text_before_change_) ||
538      (ime_composing_before_change_ != IsIMEComposing());
539  const bool selection_differs =
540      !((sel_before_change_.is_empty() && new_sel.is_empty()) ||
541        sel_before_change_.EqualsIgnoringDirection(new_sel));
542
543  // When the user has deleted text, we don't allow inline autocomplete.  Make
544  // sure to not flag cases like selecting part of the text and then pasting
545  // (or typing) the prefix of that selection.  (We detect these by making
546  // sure the caret, which should be after any insertion, hasn't moved
547  // forward of the old selection start.)
548  const bool just_deleted_text =
549      (text_before_change_.length() > new_text.length()) &&
550      (new_sel.start() <= sel_before_change_.GetMin());
551
552  const bool something_changed = model()->OnAfterPossibleChange(
553      text_before_change_, new_text, new_sel.start(), new_sel.end(),
554      selection_differs, text_changed, just_deleted_text, !IsIMEComposing());
555
556  // If only selection was changed, we don't need to call model()'s
557  // OnChanged() method, which is called in TextChanged().
558  // But we still need to call EmphasizeURLComponents() to make sure the text
559  // attributes are updated correctly.
560  if (something_changed && text_changed)
561    TextChanged();
562  else if (selection_differs)
563    EmphasizeURLComponents();
564  else if (delete_at_end_pressed_)
565    model()->OnChanged();
566
567  return something_changed;
568}
569
570gfx::NativeView OmniboxViewViews::GetNativeView() const {
571  return GetWidget()->GetNativeView();
572}
573
574gfx::NativeView OmniboxViewViews::GetRelativeWindowForPopup() const {
575  return GetWidget()->GetTopLevelWidget()->GetNativeView();
576}
577
578void OmniboxViewViews::SetGrayTextAutocompletion(const string16& input) {
579#if defined(OS_WIN) || defined(USE_AURA)
580  location_bar_view_->SetGrayTextAutocompletion(input);
581#endif
582}
583
584string16 OmniboxViewViews::GetGrayTextAutocompletion() const {
585#if defined(OS_WIN) || defined(USE_AURA)
586  return location_bar_view_->GetGrayTextAutocompletion();
587#else
588  return string16();
589#endif
590}
591
592int OmniboxViewViews::TextWidth() const {
593  return native_wrapper_->GetWidthNeededForText();
594}
595
596bool OmniboxViewViews::IsImeComposing() const {
597  return IsIMEComposing();
598}
599
600bool OmniboxViewViews::IsImeShowingPopup() const {
601#if defined(OS_CHROMEOS)
602  return ime_candidate_window_open_;
603#else
604  const views::InputMethod* input_method = this->GetInputMethod();
605  return input_method && input_method->IsCandidatePopupOpen();
606#endif
607}
608
609int OmniboxViewViews::GetMaxEditWidth(int entry_width) const {
610  return entry_width;
611}
612
613views::View* OmniboxViewViews::AddToView(views::View* parent) {
614  parent->AddChildView(this);
615  return this;
616}
617
618int OmniboxViewViews::OnPerformDrop(const ui::DropTargetEvent& event) {
619  NOTIMPLEMENTED();
620  return ui::DragDropTypes::DRAG_NONE;
621}
622
623////////////////////////////////////////////////////////////////////////////////
624// OmniboxViewViews, views::TextfieldController implementation:
625
626void OmniboxViewViews::ContentsChanged(views::Textfield* sender,
627                                       const string16& new_contents) {
628}
629
630bool OmniboxViewViews::HandleKeyEvent(views::Textfield* textfield,
631                                      const ui::KeyEvent& event) {
632  delete_at_end_pressed_ = false;
633
634  if (event.key_code() == ui::VKEY_BACK) {
635    // No extra handling is needed in keyword search mode, if there is a
636    // non-empty selection, or if the cursor is not leading the text.
637    if (model()->is_keyword_hint() || model()->keyword().empty() ||
638        HasSelection() || GetCursorPosition() != 0)
639      return false;
640    model()->ClearKeyword(text());
641    return true;
642  }
643
644  if (event.key_code() == ui::VKEY_DELETE && !event.IsAltDown()) {
645    delete_at_end_pressed_ =
646        (!HasSelection() && GetCursorPosition() == text().length());
647  }
648
649  // Handle the right-arrow key for LTR text and the left-arrow key for RTL text
650  // if there is gray text that needs to be committed.
651  if (GetCursorPosition() == text().length()) {
652    base::i18n::TextDirection direction = GetTextDirection();
653    if ((direction == base::i18n::LEFT_TO_RIGHT &&
654         event.key_code() == ui::VKEY_RIGHT) ||
655        (direction == base::i18n::RIGHT_TO_LEFT &&
656         event.key_code() == ui::VKEY_LEFT)) {
657      return model()->CommitSuggestedText();
658    }
659  }
660
661  return false;
662}
663
664void OmniboxViewViews::OnBeforeUserAction(views::Textfield* sender) {
665  OnBeforePossibleChange();
666}
667
668void OmniboxViewViews::OnAfterUserAction(views::Textfield* sender) {
669  OnAfterPossibleChange();
670}
671
672void OmniboxViewViews::OnAfterCutOrCopy() {
673  ui::Clipboard* cb = ui::Clipboard::GetForCurrentThread();
674  string16 selected_text;
675  cb->ReadText(ui::Clipboard::BUFFER_STANDARD, &selected_text);
676  GURL url;
677  bool write_url;
678  model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
679                             &selected_text, &url, &write_url);
680  if (write_url) {
681    DoCopyURL(url, selected_text);
682  } else {
683    ui::ScopedClipboardWriter scoped_clipboard_writer(
684        ui::Clipboard::GetForCurrentThread(), ui::Clipboard::BUFFER_STANDARD);
685    scoped_clipboard_writer.WriteText(selected_text);
686  }
687}
688
689void OmniboxViewViews::OnGetDragOperationsForTextfield(int* drag_operations) {
690  string16 selected_text = GetSelectedText();
691  GURL url;
692  bool write_url;
693  model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
694                             &selected_text, &url, &write_url);
695  if (write_url)
696    *drag_operations |= ui::DragDropTypes::DRAG_LINK;
697}
698
699void OmniboxViewViews::OnWriteDragData(ui::OSExchangeData* data) {
700  string16 selected_text = GetSelectedText();
701  GURL url;
702  bool write_url;
703  bool is_all_selected = IsSelectAll();
704  model()->AdjustTextForCopy(GetSelectedRange().GetMin(), is_all_selected,
705                             &selected_text, &url, &write_url);
706  data->SetString(selected_text);
707  if (write_url) {
708    gfx::Image favicon;
709    string16 title = selected_text;
710    if (is_all_selected)
711      model()->GetDataForURLExport(&url, &title, &favicon);
712    button_drag_utils::SetURLAndDragImage(url, title, favicon.AsImageSkia(),
713                                          data, GetWidget());
714    data->SetURL(url, title);
715  }
716}
717
718void OmniboxViewViews::AppendDropFormats(
719    int* formats,
720    std::set<ui::OSExchangeData::CustomFormat>* custom_formats) {
721  *formats = *formats | ui::OSExchangeData::URL;
722}
723
724int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) {
725  if (HasTextBeingDragged())
726    return ui::DragDropTypes::DRAG_NONE;
727
728  if (data.HasURL()) {
729    GURL url;
730    string16 title;
731    if (data.GetURLAndTitle(&url, &title)) {
732      string16 text(StripJavascriptSchemas(UTF8ToUTF16(url.spec())));
733      if (model()->CanPasteAndGo(text)) {
734        model()->PasteAndGo(text);
735        return ui::DragDropTypes::DRAG_COPY;
736      }
737    }
738  } else if (data.HasString()) {
739    string16 text;
740    if (data.GetString(&text)) {
741      string16 collapsed_text(CollapseWhitespace(text, true));
742      if (model()->CanPasteAndGo(collapsed_text))
743        model()->PasteAndGo(collapsed_text);
744      return ui::DragDropTypes::DRAG_COPY;
745    }
746  }
747
748  return ui::DragDropTypes::DRAG_NONE;
749}
750
751void OmniboxViewViews::UpdateContextMenu(ui::SimpleMenuModel* menu_contents) {
752  if (chrome::IsQueryExtractionEnabled()) {
753    int copy_position = menu_contents->GetIndexOfCommandId(IDS_APP_COPY);
754    DCHECK_GE(copy_position, 0);
755    menu_contents->InsertItemWithStringIdAt(
756        copy_position + 1, IDC_COPY_URL, IDS_COPY_URL);
757  }
758
759  int paste_position = menu_contents->GetIndexOfCommandId(IDS_APP_PASTE);
760  DCHECK_GE(paste_position, 0);
761  menu_contents->InsertItemWithStringIdAt(
762      paste_position + 1, IDS_PASTE_AND_GO, IDS_PASTE_AND_GO);
763
764  menu_contents->AddSeparator(ui::NORMAL_SEPARATOR);
765
766  // Minor note: We use IDC_ for command id here while the underlying textfield
767  // is using IDS_ for all its command ids. This is because views cannot depend
768  // on IDC_ for now.
769  menu_contents->AddItemWithStringId(IDC_EDIT_SEARCH_ENGINES,
770      IDS_EDIT_SEARCH_ENGINES);
771}
772
773bool OmniboxViewViews::IsCommandIdEnabled(int command_id) const {
774  if (command_id == IDS_PASTE_AND_GO)
775    return model()->CanPasteAndGo(GetClipboardText());
776  if (command_id != IDC_COPY_URL)
777    return command_updater()->IsCommandEnabled(command_id);
778  return controller()->GetToolbarModel()->WouldReplaceSearchURLWithSearchTerms(
779      false);
780}
781
782bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id) const {
783  return command_id == IDS_PASTE_AND_GO;
784}
785
786string16 OmniboxViewViews::GetLabelForCommandId(int command_id) const {
787  DCHECK_EQ(IDS_PASTE_AND_GO, command_id);
788  return l10n_util::GetStringUTF16(
789      model()->IsPasteAndSearch(GetClipboardText()) ?
790          IDS_PASTE_AND_SEARCH : IDS_PASTE_AND_GO);
791}
792
793bool OmniboxViewViews::HandlesCommand(int command_id) const {
794  // See description in OnPaste() for details on why we need to handle paste.
795  return command_id == IDS_APP_PASTE;
796}
797
798void OmniboxViewViews::ExecuteCommand(int command_id, int event_flags) {
799  switch (command_id) {
800    // These commands don't invoke the popup via OnBefore/AfterPossibleChange().
801    case IDC_COPY_URL:
802      DoCopyURL(controller()->GetToolbarModel()->GetURL(),
803                controller()->GetToolbarModel()->GetText(false));
804      break;
805    case IDS_PASTE_AND_GO:
806      model()->PasteAndGo(GetClipboardText());
807      break;
808    case IDC_EDIT_SEARCH_ENGINES:
809      command_updater()->ExecuteCommand(command_id);
810      break;
811
812    default:
813      OnBeforePossibleChange();
814      if (command_id == IDS_APP_PASTE)
815        OnPaste();
816      else
817        command_updater()->ExecuteCommand(command_id);
818      OnAfterPossibleChange();
819      break;
820  }
821}
822
823#if defined(OS_CHROMEOS)
824void OmniboxViewViews::CandidateWindowOpened(
825      chromeos::input_method::InputMethodManager* manager) {
826  ime_candidate_window_open_ = true;
827}
828
829void OmniboxViewViews::CandidateWindowClosed(
830      chromeos::input_method::InputMethodManager* manager) {
831  ime_candidate_window_open_ = false;
832}
833#endif
834
835////////////////////////////////////////////////////////////////////////////////
836// OmniboxViewViews, private:
837
838int OmniboxViewViews::GetOmniboxTextLength() const {
839  // TODO(oshima): Support IME.
840  return static_cast<int>(text().length());
841}
842
843void OmniboxViewViews::EmphasizeURLComponents() {
844  // See whether the contents are a URL with a non-empty host portion, which we
845  // should emphasize.  To check for a URL, rather than using the type returned
846  // by Parse(), ask the model, which will check the desired page transition for
847  // this input.  This can tell us whether an UNKNOWN input string is going to
848  // be treated as a search or a navigation, and is the same method the Paste
849  // And Go system uses.
850  url_parse::Component scheme, host;
851  AutocompleteInput::ParseForEmphasizeComponents(text(), &scheme, &host);
852  bool grey_out_url = text().substr(scheme.begin, scheme.len) ==
853      UTF8ToUTF16(extensions::kExtensionScheme);
854  bool grey_base = model()->CurrentTextIsURL() &&
855      (host.is_nonempty() || grey_out_url);
856  SetColor(location_bar_view_->GetColor(
857      security_level_,
858      grey_base ? LocationBarView::DEEMPHASIZED_TEXT : LocationBarView::TEXT));
859  if (grey_base && !grey_out_url) {
860    ApplyColor(
861        location_bar_view_->GetColor(security_level_, LocationBarView::TEXT),
862        ui::Range(host.begin, host.end()));
863  }
864
865  // Emphasize the scheme for security UI display purposes (if necessary).
866  // Note that we check CurrentTextIsURL() because if we're replacing search
867  // URLs with search terms, we may have a non-URL even when the user is not
868  // editing; and in some cases, e.g. for "site:foo.com" searches, the parser
869  // may have incorrectly identified a qualifier as a scheme.
870  SetStyle(gfx::DIAGONAL_STRIKE, false);
871  if (!model()->user_input_in_progress() && model()->CurrentTextIsURL() &&
872      scheme.is_nonempty() && (security_level_ != ToolbarModel::NONE)) {
873    SkColor security_color = location_bar_view_->GetColor(
874        security_level_, LocationBarView::SECURITY_TEXT);
875    const bool strike = (security_level_ == ToolbarModel::SECURITY_ERROR);
876    const ui::Range scheme_range(scheme.begin, scheme.end());
877    ApplyColor(security_color, scheme_range);
878    ApplyStyle(gfx::DIAGONAL_STRIKE, strike, scheme_range);
879  }
880}
881
882void OmniboxViewViews::SetTextAndSelectedRange(const string16& text,
883                                               const ui::Range& range) {
884  SetText(text);
885  SelectRange(range);
886}
887
888string16 OmniboxViewViews::GetSelectedText() const {
889  // TODO(oshima): Support IME.
890  return views::Textfield::GetSelectedText();
891}
892
893void OmniboxViewViews::OnPaste() {
894  const string16 text(GetClipboardText());
895  if (!text.empty()) {
896    // Record this paste, so we can do different behavior.
897    model()->on_paste();
898    // Force a Paste operation to trigger the text_changed code in
899    // OnAfterPossibleChange(), even if identical contents are pasted.
900    text_before_change_.clear();
901    InsertOrReplaceText(text);
902  }
903}
904