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