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