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