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