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