aa4241972a88beb3331fdae13f0c231e4f215508
[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     // Tweak: if the user had all the text selected, select all the new text.
496     // This makes one particular case better: the user clicks in the box to
497     // change it right before the permanent URL is changed.  Since the new URL
498     // is still fully selected, the user's typing will replace the edit contents
499     // as they'd intended.
500     const bool was_select_all = !text().empty() && IsSelectAll();
501     const bool was_reversed = GetSelectedRange().is_reversed();
502
503     RevertAll();
504
505     // Only select all when we have focus.  If we don't have focus, selecting
506     // all is unnecessary since the selection will change on regaining focus,
507     // and can in fact cause artifacts, e.g. if the user is on the NTP and
508     // clicks a link to navigate, causing |was_select_all| to be vacuously true
509     // for the empty omnibox, and we then select all here, leading to the
510     // trailing portion of a long URL being scrolled into view.  We could try
511     // and address cases like this, but it seems better to just not muck with
512     // things when the omnibox isn't focused to begin with.
513     if (was_select_all && model()->has_focus())
514       SelectAll(was_reversed);
515   } else if (old_security_level != security_level_) {
516     EmphasizeURLComponents();
517   }
518 }
519
520 base::string16 OmniboxViewViews::GetText() const {
521   // TODO(oshima): IME support
522   return text();
523 }
524
525 void OmniboxViewViews::SetUserText(const base::string16& text,
526                                    const base::string16& display_text,
527                                    bool update_popup) {
528   saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
529   OmniboxView::SetUserText(text, display_text, update_popup);
530 }
531
532 void OmniboxViewViews::SetWindowTextAndCaretPos(const base::string16& text,
533                                                 size_t caret_pos,
534                                                 bool update_popup,
535                                                 bool notify_text_changed) {
536   const gfx::Range range(caret_pos, caret_pos);
537   SetTextAndSelectedRange(text, range);
538
539   if (update_popup)
540     UpdatePopup();
541
542   if (notify_text_changed)
543     TextChanged();
544 }
545
546 void OmniboxViewViews::SetForcedQuery() {
547   const base::string16 current_text(text());
548   const size_t start = current_text.find_first_not_of(base::kWhitespaceUTF16);
549   if (start == base::string16::npos || (current_text[start] != '?'))
550     OmniboxView::SetUserText(base::ASCIIToUTF16("?"));
551   else
552     SelectRange(gfx::Range(current_text.size(), start + 1));
553 }
554
555 bool OmniboxViewViews::IsSelectAll() const {
556   // TODO(oshima): IME support.
557   return text() == GetSelectedText();
558 }
559
560 bool OmniboxViewViews::DeleteAtEndPressed() {
561   return delete_at_end_pressed_;
562 }
563
564 void OmniboxViewViews::GetSelectionBounds(
565     base::string16::size_type* start,
566     base::string16::size_type* end) const {
567   const gfx::Range range = GetSelectedRange();
568   *start = static_cast<size_t>(range.start());
569   *end = static_cast<size_t>(range.end());
570 }
571
572 void OmniboxViewViews::SelectAll(bool reversed) {
573   views::Textfield::SelectAll(reversed);
574 }
575
576 void OmniboxViewViews::RevertAll() {
577   saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
578   OmniboxView::RevertAll();
579 }
580
581 void OmniboxViewViews::UpdatePopup() {
582   model()->SetInputInProgress(true);
583   if (!model()->has_focus())
584     return;
585
586   // Prevent inline autocomplete when the caret isn't at the end of the text,
587   // and during IME composition editing unless
588   // |kEnableOmniboxAutoCompletionForIme| is enabled.
589   const gfx::Range sel = GetSelectedRange();
590   model()->StartAutocomplete(
591       !sel.is_empty(),
592       sel.GetMax() < text().length() ||
593       (IsIMEComposing() && !IsOmniboxAutoCompletionForImeEnabled()));
594 }
595
596 void OmniboxViewViews::SetFocus() {
597   RequestFocus();
598   // Restore caret visibility if focus is explicitly requested. This is
599   // necessary because if we already have invisible focus, the RequestFocus()
600   // call above will short-circuit, preventing us from reaching
601   // OmniboxEditModel::OnSetFocus(), which handles restoring visibility when the
602   // omnibox regains focus after losing focus.
603   model()->SetCaretVisibility(true);
604 }
605
606 void OmniboxViewViews::ApplyCaretVisibility() {
607   SetCursorEnabled(model()->is_caret_visible());
608 }
609
610 void OmniboxViewViews::OnTemporaryTextMaybeChanged(
611     const base::string16& display_text,
612     bool save_original_selection,
613     bool notify_text_changed) {
614   if (save_original_selection)
615     saved_temporary_selection_ = GetSelectedRange();
616
617   SetWindowTextAndCaretPos(display_text, display_text.length(), false,
618                            notify_text_changed);
619 }
620
621 bool OmniboxViewViews::OnInlineAutocompleteTextMaybeChanged(
622     const base::string16& display_text,
623     size_t user_text_length) {
624   if (display_text == text())
625     return false;
626
627   if (IsIMEComposing()) {
628     location_bar_view_->SetImeInlineAutocompletion(
629         display_text.substr(user_text_length));
630   } else {
631     gfx::Range range(display_text.size(), user_text_length);
632     SetTextAndSelectedRange(display_text, range);
633   }
634   TextChanged();
635   return true;
636 }
637
638 void OmniboxViewViews::OnInlineAutocompleteTextCleared() {
639   // Hide the inline autocompletion for IME users.
640   location_bar_view_->SetImeInlineAutocompletion(base::string16());
641 }
642
643 void OmniboxViewViews::OnRevertTemporaryText() {
644   SelectRange(saved_temporary_selection_);
645   // We got here because the user hit the Escape key. We explicitly don't call
646   // TextChanged(), since OmniboxPopupModel::ResetToDefaultMatch() has already
647   // been called by now, and it would've called TextChanged() if it was
648   // warranted.
649 }
650
651 void OmniboxViewViews::OnBeforePossibleChange() {
652   // Record our state.
653   text_before_change_ = text();
654   sel_before_change_ = GetSelectedRange();
655   ime_composing_before_change_ = IsIMEComposing();
656 }
657
658 bool OmniboxViewViews::OnAfterPossibleChange() {
659   // See if the text or selection have changed since OnBeforePossibleChange().
660   const base::string16 new_text = text();
661   const gfx::Range new_sel = GetSelectedRange();
662   const bool text_changed = (new_text != text_before_change_) ||
663       (ime_composing_before_change_ != IsIMEComposing());
664   const bool selection_differs =
665       !((sel_before_change_.is_empty() && new_sel.is_empty()) ||
666         sel_before_change_.EqualsIgnoringDirection(new_sel));
667
668   // When the user has deleted text, we don't allow inline autocomplete.  Make
669   // sure to not flag cases like selecting part of the text and then pasting
670   // (or typing) the prefix of that selection.  (We detect these by making
671   // sure the caret, which should be after any insertion, hasn't moved
672   // forward of the old selection start.)
673   const bool just_deleted_text =
674       (text_before_change_.length() > new_text.length()) &&
675       (new_sel.start() <= sel_before_change_.GetMin());
676
677   const bool something_changed = model()->OnAfterPossibleChange(
678       text_before_change_, new_text, new_sel.start(), new_sel.end(),
679       selection_differs, text_changed, just_deleted_text, !IsIMEComposing());
680
681   // If only selection was changed, we don't need to call model()'s
682   // OnChanged() method, which is called in TextChanged().
683   // But we still need to call EmphasizeURLComponents() to make sure the text
684   // attributes are updated correctly.
685   if (something_changed && text_changed)
686     TextChanged();
687   else if (selection_differs)
688     EmphasizeURLComponents();
689   else if (delete_at_end_pressed_)
690     model()->OnChanged();
691
692   return something_changed;
693 }
694
695 gfx::NativeView OmniboxViewViews::GetNativeView() const {
696   return GetWidget()->GetNativeView();
697 }
698
699 gfx::NativeView OmniboxViewViews::GetRelativeWindowForPopup() const {
700   return GetWidget()->GetTopLevelWidget()->GetNativeView();
701 }
702
703 void OmniboxViewViews::SetGrayTextAutocompletion(const base::string16& input) {
704 #if defined(OS_WIN) || defined(USE_AURA)
705   location_bar_view_->SetGrayTextAutocompletion(input);
706 #endif
707 }
708
709 base::string16 OmniboxViewViews::GetGrayTextAutocompletion() const {
710 #if defined(OS_WIN) || defined(USE_AURA)
711   return location_bar_view_->GetGrayTextAutocompletion();
712 #else
713   return base::string16();
714 #endif
715 }
716
717 int OmniboxViewViews::GetTextWidth() const {
718   // Returns the width necessary to display the current text, including any
719   // necessary space for the cursor or border/margin.
720   return GetRenderText()->GetContentWidth() + GetInsets().width();
721 }
722
723 int OmniboxViewViews::GetWidth() const {
724   return location_bar_view_->width();
725 }
726
727 bool OmniboxViewViews::IsImeComposing() const {
728   return IsIMEComposing();
729 }
730
731 bool OmniboxViewViews::IsImeShowingPopup() const {
732 #if defined(OS_CHROMEOS)
733   return ime_candidate_window_open_;
734 #else
735   const views::InputMethod* input_method = this->GetInputMethod();
736   return input_method && input_method->IsCandidatePopupOpen();
737 #endif
738 }
739
740 void OmniboxViewViews::ShowImeIfNeeded() {
741   GetInputMethod()->ShowImeIfNeeded();
742 }
743
744 void OmniboxViewViews::OnMatchOpened(const AutocompleteMatch& match,
745                                      Profile* profile,
746                                      content::WebContents* web_contents) const {
747   extensions::MaybeShowExtensionControlledSearchNotification(
748       profile, web_contents, match);
749 }
750
751 bool OmniboxViewViews::IsCommandIdEnabled(int command_id) const {
752   if (command_id == IDS_APP_PASTE)
753     return !read_only() && !GetClipboardText().empty();
754   if (command_id == IDS_PASTE_AND_GO)
755     return !read_only() && model()->CanPasteAndGo(GetClipboardText());
756   if (command_id == IDS_SHOW_URL)
757     return controller()->GetToolbarModel()->WouldReplaceURL();
758   return Textfield::IsCommandIdEnabled(command_id) ||
759          command_updater()->IsCommandEnabled(command_id);
760 }
761
762 bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id) const {
763   return command_id == IDS_PASTE_AND_GO;
764 }
765
766 base::string16 OmniboxViewViews::GetLabelForCommandId(int command_id) const {
767   DCHECK_EQ(IDS_PASTE_AND_GO, command_id);
768   return l10n_util::GetStringUTF16(
769       model()->IsPasteAndSearch(GetClipboardText()) ?
770           IDS_PASTE_AND_SEARCH : IDS_PASTE_AND_GO);
771 }
772
773 void OmniboxViewViews::ExecuteCommand(int command_id, int event_flags) {
774   switch (command_id) {
775     // These commands don't invoke the popup via OnBefore/AfterPossibleChange().
776     case IDS_PASTE_AND_GO:
777       model()->PasteAndGo(GetClipboardText());
778       break;
779     case IDS_SHOW_URL:
780       controller()->ShowURL();
781       break;
782     case IDC_EDIT_SEARCH_ENGINES:
783       command_updater()->ExecuteCommand(command_id);
784       break;
785
786     default:
787       OnBeforePossibleChange();
788       if (command_id == IDS_APP_PASTE)
789         OnPaste();
790       else if (Textfield::IsCommandIdEnabled(command_id))
791         Textfield::ExecuteCommand(command_id, event_flags);
792       else
793         command_updater()->ExecuteCommand(command_id);
794       OnAfterPossibleChange();
795       break;
796   }
797 }
798
799 ////////////////////////////////////////////////////////////////////////////////
800 // OmniboxViewViews, gfx::AnimationDelegate implementation:
801
802 void OmniboxViewViews::AnimationProgressed(const gfx::Animation* animation) {
803   SchedulePaint();
804 }
805
806 void OmniboxViewViews::AnimationEnded(const gfx::Animation* animation) {
807   fade_in_animation_->Reset();
808 }
809
810 ////////////////////////////////////////////////////////////////////////////////
811 // OmniboxViewViews, views::TextfieldController implementation:
812
813 void OmniboxViewViews::ContentsChanged(views::Textfield* sender,
814                                        const base::string16& new_contents) {
815 }
816
817 bool OmniboxViewViews::HandleKeyEvent(views::Textfield* textfield,
818                                       const ui::KeyEvent& event) {
819   delete_at_end_pressed_ = false;
820
821   if (event.key_code() == ui::VKEY_BACK) {
822     // No extra handling is needed in keyword search mode, if there is a
823     // non-empty selection, or if the cursor is not leading the text.
824     if (model()->is_keyword_hint() || model()->keyword().empty() ||
825         HasSelection() || GetCursorPosition() != 0)
826       return false;
827     model()->ClearKeyword(text());
828     return true;
829   }
830
831   if (event.key_code() == ui::VKEY_DELETE && !event.IsAltDown()) {
832     delete_at_end_pressed_ =
833         (!HasSelection() && GetCursorPosition() == text().length());
834   }
835
836   // Handle the right-arrow key for LTR text and the left-arrow key for RTL text
837   // if there is gray text that needs to be committed.
838   if (GetCursorPosition() == text().length()) {
839     base::i18n::TextDirection direction = GetTextDirection();
840     if ((direction == base::i18n::LEFT_TO_RIGHT &&
841          event.key_code() == ui::VKEY_RIGHT) ||
842         (direction == base::i18n::RIGHT_TO_LEFT &&
843          event.key_code() == ui::VKEY_LEFT)) {
844       return model()->CommitSuggestedText();
845     }
846   }
847
848   return false;
849 }
850
851 void OmniboxViewViews::OnBeforeUserAction(views::Textfield* sender) {
852   OnBeforePossibleChange();
853 }
854
855 void OmniboxViewViews::OnAfterUserAction(views::Textfield* sender) {
856   OnAfterPossibleChange();
857 }
858
859 void OmniboxViewViews::OnAfterCutOrCopy() {
860   ui::Clipboard* cb = ui::Clipboard::GetForCurrentThread();
861   base::string16 selected_text;
862   cb->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &selected_text);
863   GURL url;
864   bool write_url;
865   model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
866                              &selected_text, &url, &write_url);
867   if (IsSelectAll())
868     UMA_HISTOGRAM_COUNTS(OmniboxEditModel::kCutOrCopyAllTextHistogram, 1);
869
870   if (write_url) {
871     BookmarkNodeData data;
872     data.ReadFromTuple(url, selected_text);
873     data.WriteToClipboard(ui::CLIPBOARD_TYPE_COPY_PASTE);
874   } else {
875     ui::ScopedClipboardWriter scoped_clipboard_writer(
876         ui::Clipboard::GetForCurrentThread(), ui::CLIPBOARD_TYPE_COPY_PASTE);
877     scoped_clipboard_writer.WriteText(selected_text);
878   }
879 }
880
881 void OmniboxViewViews::OnGetDragOperationsForTextfield(int* drag_operations) {
882   base::string16 selected_text = GetSelectedText();
883   GURL url;
884   bool write_url;
885   model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
886                              &selected_text, &url, &write_url);
887   if (write_url)
888     *drag_operations |= ui::DragDropTypes::DRAG_LINK;
889 }
890
891 void OmniboxViewViews::OnWriteDragData(ui::OSExchangeData* data) {
892   GURL url;
893   bool write_url;
894   bool is_all_selected = IsSelectAll();
895   base::string16 selected_text = GetSelectedText();
896   model()->AdjustTextForCopy(GetSelectedRange().GetMin(), is_all_selected,
897                              &selected_text, &url, &write_url);
898   data->SetString(selected_text);
899   if (write_url) {
900     gfx::Image favicon;
901     base::string16 title = selected_text;
902     if (is_all_selected)
903       model()->GetDataForURLExport(&url, &title, &favicon);
904     button_drag_utils::SetURLAndDragImage(url, title, favicon.AsImageSkia(),
905                                           data, GetWidget());
906     data->SetURL(url, title);
907   }
908 }
909
910 void OmniboxViewViews::AppendDropFormats(
911     int* formats,
912     std::set<ui::OSExchangeData::CustomFormat>* custom_formats) {
913   *formats = *formats | ui::OSExchangeData::URL;
914 }
915
916 int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) {
917   if (HasTextBeingDragged())
918     return ui::DragDropTypes::DRAG_NONE;
919
920   if (data.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)) {
921     GURL url;
922     base::string16 title;
923     if (data.GetURLAndTitle(
924             ui::OSExchangeData::CONVERT_FILENAMES, &url, &title)) {
925       base::string16 text(
926           StripJavascriptSchemas(base::UTF8ToUTF16(url.spec())));
927       if (model()->CanPasteAndGo(text)) {
928         model()->PasteAndGo(text);
929         return ui::DragDropTypes::DRAG_COPY;
930       }
931     }
932   } else if (data.HasString()) {
933     base::string16 text;
934     if (data.GetString(&text)) {
935       base::string16 collapsed_text(base::CollapseWhitespace(text, true));
936       if (model()->CanPasteAndGo(collapsed_text))
937         model()->PasteAndGo(collapsed_text);
938       return ui::DragDropTypes::DRAG_COPY;
939     }
940   }
941
942   return ui::DragDropTypes::DRAG_NONE;
943 }
944
945 void OmniboxViewViews::UpdateContextMenu(ui::SimpleMenuModel* menu_contents) {
946   int paste_position = menu_contents->GetIndexOfCommandId(IDS_APP_PASTE);
947   DCHECK_GE(paste_position, 0);
948   menu_contents->InsertItemWithStringIdAt(
949       paste_position + 1, IDS_PASTE_AND_GO, IDS_PASTE_AND_GO);
950
951   menu_contents->AddSeparator(ui::NORMAL_SEPARATOR);
952
953   if (chrome::IsQueryExtractionEnabled() || chrome::ShouldDisplayOriginChip() ||
954       chrome::ShouldDisplayOriginChipV2()) {
955     int select_all_position = menu_contents->GetIndexOfCommandId(
956         IDS_APP_SELECT_ALL);
957     DCHECK_GE(select_all_position, 0);
958     menu_contents->InsertItemWithStringIdAt(
959         select_all_position + 1, IDS_SHOW_URL, IDS_SHOW_URL);
960   }
961
962   // Minor note: We use IDC_ for command id here while the underlying textfield
963   // is using IDS_ for all its command ids. This is because views cannot depend
964   // on IDC_ for now.
965   menu_contents->AddItemWithStringId(IDC_EDIT_SEARCH_ENGINES,
966       IDS_EDIT_SEARCH_ENGINES);
967 }
968
969 #if defined(OS_CHROMEOS)
970 void OmniboxViewViews::CandidateWindowOpened(
971       chromeos::input_method::InputMethodManager* manager) {
972   ime_candidate_window_open_ = true;
973 }
974
975 void OmniboxViewViews::CandidateWindowClosed(
976       chromeos::input_method::InputMethodManager* manager) {
977   ime_candidate_window_open_ = false;
978 }
979 #endif
980
981 ////////////////////////////////////////////////////////////////////////////////
982 // OmniboxViewViews, private:
983
984 int OmniboxViewViews::GetOmniboxTextLength() const {
985   // TODO(oshima): Support IME.
986   return static_cast<int>(text().length());
987 }
988
989 void OmniboxViewViews::EmphasizeURLComponents() {
990   // See whether the contents are a URL with a non-empty host portion, which we
991   // should emphasize.  To check for a URL, rather than using the type returned
992   // by Parse(), ask the model, which will check the desired page transition for
993   // this input.  This can tell us whether an UNKNOWN input string is going to
994   // be treated as a search or a navigation, and is the same method the Paste
995   // And Go system uses.
996   url_parse::Component scheme, host;
997   AutocompleteInput::ParseForEmphasizeComponents(text(), &scheme, &host);
998   bool grey_out_url = text().substr(scheme.begin, scheme.len) ==
999       base::UTF8ToUTF16(extensions::kExtensionScheme);
1000   bool grey_base = model()->CurrentTextIsURL() &&
1001       (host.is_nonempty() || grey_out_url);
1002   SetColor(location_bar_view_->GetColor(
1003       security_level_,
1004       grey_base ? LocationBarView::DEEMPHASIZED_TEXT : LocationBarView::TEXT));
1005   if (grey_base && !grey_out_url) {
1006     ApplyColor(
1007         location_bar_view_->GetColor(security_level_, LocationBarView::TEXT),
1008         gfx::Range(host.begin, host.end()));
1009   }
1010
1011   // Emphasize the scheme for security UI display purposes (if necessary).
1012   // Note that we check CurrentTextIsURL() because if we're replacing search
1013   // URLs with search terms, we may have a non-URL even when the user is not
1014   // editing; and in some cases, e.g. for "site:foo.com" searches, the parser
1015   // may have incorrectly identified a qualifier as a scheme.
1016   SetStyle(gfx::DIAGONAL_STRIKE, false);
1017   if (!model()->user_input_in_progress() && model()->CurrentTextIsURL() &&
1018       scheme.is_nonempty() && (security_level_ != ToolbarModel::NONE)) {
1019     SkColor security_color = location_bar_view_->GetColor(
1020         security_level_, LocationBarView::SECURITY_TEXT);
1021     const bool strike = (security_level_ == ToolbarModel::SECURITY_ERROR);
1022     const gfx::Range scheme_range(scheme.begin, scheme.end());
1023     ApplyColor(security_color, scheme_range);
1024     ApplyStyle(gfx::DIAGONAL_STRIKE, strike, scheme_range);
1025   }
1026 }
1027
1028 void OmniboxViewViews::SetTextAndSelectedRange(const base::string16& text,
1029                                                const gfx::Range& range) {
1030   SetText(text);
1031   SelectRange(range);
1032 }
1033
1034 base::string16 OmniboxViewViews::GetSelectedText() const {
1035   // TODO(oshima): Support IME.
1036   return views::Textfield::GetSelectedText();
1037 }
1038
1039 void OmniboxViewViews::OnPaste() {
1040   const base::string16 text(GetClipboardText());
1041   if (!text.empty()) {
1042     // Record this paste, so we can do different behavior.
1043     model()->OnPaste();
1044     // Force a Paste operation to trigger the text_changed code in
1045     // OnAfterPossibleChange(), even if identical contents are pasted.
1046     text_before_change_.clear();
1047     InsertOrReplaceText(text);
1048   }
1049 }