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.
5 #include "chrome/browser/ui/views/omnibox/omnibox_view_views.h"
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/command_updater.h"
16 #include "chrome/browser/search/search.h"
17 #include "chrome/browser/ui/omnibox/omnibox_edit_controller.h"
18 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
19 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
20 #include "chrome/browser/ui/view_ids.h"
21 #include "chrome/browser/ui/views/location_bar/location_bar_view.h"
22 #include "chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h"
23 #include "chrome/browser/ui/views/settings_api_bubble_helper_views.h"
24 #include "chrome/browser/ui/views/website_settings/website_settings_popup_view.h"
25 #include "components/bookmarks/core/browser/bookmark_node_data.h"
26 #include "content/public/browser/web_contents.h"
27 #include "extensions/common/constants.h"
28 #include "grit/app_locale_settings.h"
29 #include "grit/generated_resources.h"
30 #include "grit/ui_strings.h"
31 #include "net/base/escape.h"
32 #include "third_party/skia/include/core/SkColor.h"
33 #include "ui/accessibility/ax_view_state.h"
34 #include "ui/aura/client/focus_client.h"
35 #include "ui/aura/window_event_dispatcher.h"
36 #include "ui/base/clipboard/scoped_clipboard_writer.h"
37 #include "ui/base/dragdrop/drag_drop_types.h"
38 #include "ui/base/dragdrop/os_exchange_data.h"
39 #include "ui/base/ime/text_input_client.h"
40 #include "ui/base/ime/text_input_type.h"
41 #include "ui/base/l10n/l10n_util.h"
42 #include "ui/base/models/simple_menu_model.h"
43 #include "ui/base/resource/resource_bundle.h"
44 #include "ui/compositor/layer.h"
45 #include "ui/events/event.h"
46 #include "ui/gfx/animation/slide_animation.h"
47 #include "ui/gfx/canvas.h"
48 #include "ui/gfx/font_list.h"
49 #include "ui/gfx/selection_model.h"
50 #include "ui/views/border.h"
51 #include "ui/views/button_drag_utils.h"
52 #include "ui/views/controls/textfield/textfield.h"
53 #include "ui/views/ime/input_method.h"
54 #include "ui/views/layout/fill_layout.h"
55 #include "ui/views/views_delegate.h"
56 #include "ui/views/widget/widget.h"
60 #include "chrome/browser/browser_process.h"
65 // Stores omnibox state for each tab.
66 struct OmniboxState : public base::SupportsUserData::Data {
67 static const char kKey[];
69 OmniboxState(const OmniboxEditModel::State& model_state,
70 const gfx::Range& selection,
71 const gfx::Range& saved_selection_for_focus_change);
72 virtual ~OmniboxState();
74 const OmniboxEditModel::State model_state;
76 // We store both the actual selection and any saved selection (for when the
77 // omnibox is not focused). This allows us to properly handle cases like
78 // selecting text, tabbing out of the omnibox, switching tabs away and back,
79 // and tabbing back into the omnibox.
80 const gfx::Range selection;
81 const gfx::Range saved_selection_for_focus_change;
85 const char OmniboxState::kKey[] = "OmniboxState";
87 OmniboxState::OmniboxState(const OmniboxEditModel::State& model_state,
88 const gfx::Range& selection,
89 const gfx::Range& saved_selection_for_focus_change)
90 : model_state(model_state),
92 saved_selection_for_focus_change(saved_selection_for_focus_change) {
95 OmniboxState::~OmniboxState() {}
97 // We'd like to set the text input type to TEXT_INPUT_TYPE_URL, because this
98 // triggers URL-specific layout in software keyboards, e.g. adding top-level "/"
99 // and ".com" keys for English. However, this also causes IMEs to default to
100 // Latin character mode, which makes entering search queries difficult for IME
101 // users. Therefore, we try to guess whether an IME will be used based on the
102 // application language, and set the input type accordingly.
103 ui::TextInputType DetermineTextInputType() {
105 DCHECK(g_browser_process);
106 const std::string& locale = g_browser_process->GetApplicationLocale();
107 const std::string& language = locale.substr(0, 2);
108 // Assume CJK + Thai users are using an IME.
109 if (language == "ja" ||
113 return ui::TEXT_INPUT_TYPE_SEARCH;
115 return ui::TEXT_INPUT_TYPE_URL;
121 const char OmniboxViewViews::kViewClassName[] = "OmniboxViewViews";
123 OmniboxViewViews::OmniboxViewViews(OmniboxEditController* controller,
125 CommandUpdater* command_updater,
126 bool popup_window_mode,
127 LocationBarView* location_bar,
128 const gfx::FontList& font_list)
129 : OmniboxView(profile, controller, command_updater),
130 popup_window_mode_(popup_window_mode),
131 security_level_(ToolbarModel::NONE),
132 saved_selection_for_focus_change_(gfx::Range::InvalidRange()),
133 ime_composing_before_change_(false),
134 delete_at_end_pressed_(false),
135 location_bar_view_(location_bar),
136 ime_candidate_window_open_(false),
137 select_all_on_mouse_release_(false),
138 select_all_on_gesture_tap_(false) {
139 SetBorder(views::Border::NullBorder());
140 set_id(VIEW_ID_OMNIBOX);
141 SetFontList(font_list);
144 OmniboxViewViews::~OmniboxViewViews() {
145 #if defined(OS_CHROMEOS)
146 chromeos::input_method::InputMethodManager::Get()->
147 RemoveCandidateWindowObserver(this);
150 // Explicitly teardown members which have a reference to us. Just to be safe
151 // we want them to be destroyed before destroying any other internal state.
155 ////////////////////////////////////////////////////////////////////////////////
156 // OmniboxViewViews public:
158 void OmniboxViewViews::Init() {
159 set_controller(this);
160 SetTextInputType(DetermineTextInputType());
162 if (popup_window_mode_)
165 // Initialize the popup view using the same font.
166 popup_view_.reset(OmniboxPopupContentsView::Create(
167 GetFontList(), this, model(), location_bar_view_));
169 #if defined(OS_CHROMEOS)
170 chromeos::input_method::InputMethodManager::Get()->
171 AddCandidateWindowObserver(this);
174 fade_in_animation_.reset(new gfx::SlideAnimation(this));
175 fade_in_animation_->SetTweenType(gfx::Tween::LINEAR);
176 fade_in_animation_->SetSlideDuration(300);
179 void OmniboxViewViews::FadeIn() {
180 fade_in_animation_->Show();
183 ////////////////////////////////////////////////////////////////////////////////
184 // OmniboxViewViews, public OmniboxView implementation:
186 void OmniboxViewViews::SaveStateToTab(content::WebContents* tab) {
189 // We don't want to keep the IME status, so force quit the current
190 // session here. It may affect the selection status, so order is
192 if (IsIMEComposing()) {
193 GetTextInputClient()->ConfirmCompositionText();
194 GetInputMethod()->CancelComposition(this);
197 // NOTE: GetStateForTabSwitch() may affect GetSelectedRange(), so order is
199 OmniboxEditModel::State state = model()->GetStateForTabSwitch();
200 tab->SetUserData(OmniboxState::kKey, new OmniboxState(
201 state, GetSelectedRange(), saved_selection_for_focus_change_));
204 void OmniboxViewViews::OnTabChanged(const content::WebContents* web_contents) {
205 security_level_ = controller()->GetToolbarModel()->GetSecurityLevel(false);
207 const OmniboxState* state = static_cast<OmniboxState*>(
208 web_contents->GetUserData(&OmniboxState::kKey));
209 model()->RestoreState(state ? &state->model_state : NULL);
211 // This assumes that the omnibox has already been focused or blurred as
212 // appropriate; otherwise, a subsequent OnFocus() or OnBlur() call could
213 // goof up the selection. See comments at the end of
214 // BrowserView::ActiveTabChanged().
215 SelectRange(state->selection);
216 saved_selection_for_focus_change_ = state->saved_selection_for_focus_change;
219 // TODO(msw|oshima): Consider saving/restoring edit history.
223 void OmniboxViewViews::Update() {
224 if (chrome::ShouldDisplayOriginChip() || chrome::ShouldDisplayOriginChipV2())
225 set_placeholder_text(GetHintText());
227 const ToolbarModel::SecurityLevel old_security_level = security_level_;
228 security_level_ = controller()->GetToolbarModel()->GetSecurityLevel(false);
229 if (model()->UpdatePermanentText()) {
230 // Something visibly changed. Re-enable URL replacement.
231 controller()->GetToolbarModel()->set_url_replacement_enabled(true);
232 model()->UpdatePermanentText();
234 // Select all the new text if the user had all the old text selected, or if
235 // there was no previous text (for new tab page URL replacement extensions).
236 // This makes one particular case better: the user clicks in the box to
237 // change it right before the permanent URL is changed. Since the new URL
238 // is still fully selected, the user's typing will replace the edit contents
239 // as they'd intended.
240 const bool was_select_all = IsSelectAll();
241 const bool was_reversed = GetSelectedRange().is_reversed();
245 // Only select all when we have focus. If we don't have focus, selecting
246 // all is unnecessary since the selection will change on regaining focus,
247 // and can in fact cause artifacts, e.g. if the user is on the NTP and
248 // clicks a link to navigate, causing |was_select_all| to be vacuously true
249 // for the empty omnibox, and we then select all here, leading to the
250 // trailing portion of a long URL being scrolled into view. We could try
251 // and address cases like this, but it seems better to just not muck with
252 // things when the omnibox isn't focused to begin with.
253 if (was_select_all && model()->has_focus())
254 SelectAll(was_reversed);
255 } else if (old_security_level != security_level_) {
256 EmphasizeURLComponents();
260 base::string16 OmniboxViewViews::GetText() const {
261 // TODO(oshima): IME support
265 void OmniboxViewViews::SetUserText(const base::string16& text,
266 const base::string16& display_text,
268 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
269 OmniboxView::SetUserText(text, display_text, update_popup);
272 void OmniboxViewViews::SetForcedQuery() {
273 const base::string16 current_text(text());
274 const size_t start = current_text.find_first_not_of(base::kWhitespaceUTF16);
275 if (start == base::string16::npos || (current_text[start] != '?'))
276 OmniboxView::SetUserText(base::ASCIIToUTF16("?"));
278 SelectRange(gfx::Range(current_text.size(), start + 1));
281 void OmniboxViewViews::GetSelectionBounds(
282 base::string16::size_type* start,
283 base::string16::size_type* end) const {
284 const gfx::Range range = GetSelectedRange();
285 *start = static_cast<size_t>(range.start());
286 *end = static_cast<size_t>(range.end());
289 void OmniboxViewViews::SelectAll(bool reversed) {
290 views::Textfield::SelectAll(reversed);
293 void OmniboxViewViews::RevertAll() {
294 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
295 OmniboxView::RevertAll();
298 void OmniboxViewViews::SetFocus() {
300 // Restore caret visibility if focus is explicitly requested. This is
301 // necessary because if we already have invisible focus, the RequestFocus()
302 // call above will short-circuit, preventing us from reaching
303 // OmniboxEditModel::OnSetFocus(), which handles restoring visibility when the
304 // omnibox regains focus after losing focus.
305 model()->SetCaretVisibility(true);
308 int OmniboxViewViews::GetTextWidth() const {
309 // Returns the width necessary to display the current text, including any
310 // necessary space for the cursor or border/margin.
311 return GetRenderText()->GetContentWidth() + GetInsets().width();
314 bool OmniboxViewViews::IsImeComposing() const {
315 return IsIMEComposing();
318 void OmniboxViewViews::ExecuteCommand(int command_id, int event_flags) {
319 switch (command_id) {
320 // These commands don't invoke the popup via OnBefore/AfterPossibleChange().
321 case IDS_PASTE_AND_GO:
322 model()->PasteAndGo(GetClipboardText());
325 controller()->ShowURL();
327 case IDC_EDIT_SEARCH_ENGINES:
328 command_updater()->ExecuteCommand(command_id);
332 model()->OnUpOrDownKeyPressed(command_id == IDS_MOVE_DOWN ? 1 : -1);
336 OnBeforePossibleChange();
337 if (command_id == IDS_APP_PASTE)
339 else if (Textfield::IsCommandIdEnabled(command_id))
340 Textfield::ExecuteCommand(command_id, event_flags);
342 command_updater()->ExecuteCommand(command_id);
343 OnAfterPossibleChange();
348 ////////////////////////////////////////////////////////////////////////////////
349 // OmniboxViewViews, private:
351 int OmniboxViewViews::GetOmniboxTextLength() const {
352 // TODO(oshima): Support IME.
353 return static_cast<int>(text().length());
356 void OmniboxViewViews::EmphasizeURLComponents() {
357 // See whether the contents are a URL with a non-empty host portion, which we
358 // should emphasize. To check for a URL, rather than using the type returned
359 // by Parse(), ask the model, which will check the desired page transition for
360 // this input. This can tell us whether an UNKNOWN input string is going to
361 // be treated as a search or a navigation, and is the same method the Paste
362 // And Go system uses.
363 url::Component scheme, host;
364 AutocompleteInput::ParseForEmphasizeComponents(text(), &scheme, &host);
365 bool grey_out_url = text().substr(scheme.begin, scheme.len) ==
366 base::UTF8ToUTF16(extensions::kExtensionScheme);
367 bool grey_base = model()->CurrentTextIsURL() &&
368 (host.is_nonempty() || grey_out_url);
369 SetColor(location_bar_view_->GetColor(
371 grey_base ? LocationBarView::DEEMPHASIZED_TEXT : LocationBarView::TEXT));
372 if (grey_base && !grey_out_url) {
374 location_bar_view_->GetColor(security_level_, LocationBarView::TEXT),
375 gfx::Range(host.begin, host.end()));
378 // Emphasize the scheme for security UI display purposes (if necessary).
379 // Note that we check CurrentTextIsURL() because if we're replacing search
380 // URLs with search terms, we may have a non-URL even when the user is not
381 // editing; and in some cases, e.g. for "site:foo.com" searches, the parser
382 // may have incorrectly identified a qualifier as a scheme.
383 SetStyle(gfx::DIAGONAL_STRIKE, false);
384 if (!model()->user_input_in_progress() && model()->CurrentTextIsURL() &&
385 scheme.is_nonempty() && (security_level_ != ToolbarModel::NONE)) {
386 SkColor security_color = location_bar_view_->GetColor(
387 security_level_, LocationBarView::SECURITY_TEXT);
388 const bool strike = (security_level_ == ToolbarModel::SECURITY_ERROR);
389 const gfx::Range scheme_range(scheme.begin, scheme.end());
390 ApplyColor(security_color, scheme_range);
391 ApplyStyle(gfx::DIAGONAL_STRIKE, strike, scheme_range);
395 void OmniboxViewViews::SetTextAndSelectedRange(const base::string16& text,
396 const gfx::Range& range) {
401 base::string16 OmniboxViewViews::GetSelectedText() const {
402 // TODO(oshima): Support IME.
403 return views::Textfield::GetSelectedText();
406 void OmniboxViewViews::OnPaste() {
407 const base::string16 text(GetClipboardText());
409 // Record this paste, so we can do different behavior.
411 // Force a Paste operation to trigger the text_changed code in
412 // OnAfterPossibleChange(), even if identical contents are pasted.
413 text_before_change_.clear();
414 InsertOrReplaceText(text);
418 bool OmniboxViewViews::HandleEarlyTabActions(const ui::KeyEvent& event) {
419 // This must run before acclerator handling invokes a focus change on tab.
420 // Note the parallel with SkipDefaultKeyEventProcessing above.
421 if (views::FocusManager::IsTabTraversalKeyEvent(event)) {
422 if (model()->is_keyword_hint() && !event.IsShiftDown()) {
423 model()->AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_TAB);
426 if (model()->popup_model()->IsOpen()) {
427 if (event.IsShiftDown() &&
428 model()->popup_model()->selected_line_state() ==
429 OmniboxPopupModel::KEYWORD) {
430 model()->ClearKeyword(text());
432 model()->OnUpOrDownKeyPressed(event.IsShiftDown() ? -1 : 1);
441 ////////////////////////////////////////////////////////////////////////////////
442 // OmniboxViewViews, private View implementation:
444 void OmniboxViewViews::OnNativeThemeChanged(const ui::NativeTheme* theme) {
445 views::Textfield::OnNativeThemeChanged(theme);
446 SetBackgroundColor(location_bar_view_->GetColor(
447 ToolbarModel::NONE, LocationBarView::BACKGROUND));
448 EmphasizeURLComponents();
451 ////////////////////////////////////////////////////////////////////////////////
452 // OmniboxViewViews, private OmniboxView implementation:
454 void OmniboxViewViews::SetWindowTextAndCaretPos(const base::string16& text,
457 bool notify_text_changed) {
458 const gfx::Range range(caret_pos, caret_pos);
459 SetTextAndSelectedRange(text, range);
464 if (notify_text_changed)
468 bool OmniboxViewViews::IsSelectAll() const {
469 // TODO(oshima): IME support.
470 return text() == GetSelectedText();
473 bool OmniboxViewViews::DeleteAtEndPressed() {
474 return delete_at_end_pressed_;
477 void OmniboxViewViews::UpdatePopup() {
478 model()->SetInputInProgress(true);
479 if (!model()->has_focus())
482 // Prevent inline autocomplete when the caret isn't at the end of the text.
483 const gfx::Range sel = GetSelectedRange();
484 model()->StartAutocomplete(!sel.is_empty(), sel.GetMax() < text().length());
487 void OmniboxViewViews::ApplyCaretVisibility() {
488 SetCursorEnabled(model()->is_caret_visible());
491 void OmniboxViewViews::OnTemporaryTextMaybeChanged(
492 const base::string16& display_text,
493 bool save_original_selection,
494 bool notify_text_changed) {
495 if (save_original_selection)
496 saved_temporary_selection_ = GetSelectedRange();
498 SetWindowTextAndCaretPos(display_text, display_text.length(), false,
499 notify_text_changed);
502 bool OmniboxViewViews::OnInlineAutocompleteTextMaybeChanged(
503 const base::string16& display_text,
504 size_t user_text_length) {
505 if (display_text == text())
508 if (IsIMEComposing()) {
509 location_bar_view_->SetImeInlineAutocompletion(
510 display_text.substr(user_text_length));
512 gfx::Range range(display_text.size(), user_text_length);
513 SetTextAndSelectedRange(display_text, range);
519 void OmniboxViewViews::OnInlineAutocompleteTextCleared() {
520 // Hide the inline autocompletion for IME users.
521 location_bar_view_->SetImeInlineAutocompletion(base::string16());
524 void OmniboxViewViews::OnRevertTemporaryText() {
525 SelectRange(saved_temporary_selection_);
526 // We got here because the user hit the Escape key. We explicitly don't call
527 // TextChanged(), since OmniboxPopupModel::ResetToDefaultMatch() has already
528 // been called by now, and it would've called TextChanged() if it was
532 void OmniboxViewViews::OnBeforePossibleChange() {
534 text_before_change_ = text();
535 sel_before_change_ = GetSelectedRange();
536 ime_composing_before_change_ = IsIMEComposing();
539 bool OmniboxViewViews::OnAfterPossibleChange() {
540 // See if the text or selection have changed since OnBeforePossibleChange().
541 const base::string16 new_text = text();
542 const gfx::Range new_sel = GetSelectedRange();
543 const bool text_changed = (new_text != text_before_change_) ||
544 (ime_composing_before_change_ != IsIMEComposing());
545 const bool selection_differs =
546 !((sel_before_change_.is_empty() && new_sel.is_empty()) ||
547 sel_before_change_.EqualsIgnoringDirection(new_sel));
549 // When the user has deleted text, we don't allow inline autocomplete. Make
550 // sure to not flag cases like selecting part of the text and then pasting
551 // (or typing) the prefix of that selection. (We detect these by making
552 // sure the caret, which should be after any insertion, hasn't moved
553 // forward of the old selection start.)
554 const bool just_deleted_text =
555 (text_before_change_.length() > new_text.length()) &&
556 (new_sel.start() <= sel_before_change_.GetMin());
558 const bool something_changed = model()->OnAfterPossibleChange(
559 text_before_change_, new_text, new_sel.start(), new_sel.end(),
560 selection_differs, text_changed, just_deleted_text, !IsIMEComposing());
562 // If only selection was changed, we don't need to call model()'s
563 // OnChanged() method, which is called in TextChanged().
564 // But we still need to call EmphasizeURLComponents() to make sure the text
565 // attributes are updated correctly.
566 if (something_changed && text_changed)
568 else if (selection_differs)
569 EmphasizeURLComponents();
570 else if (delete_at_end_pressed_)
571 model()->OnChanged();
573 return something_changed;
576 gfx::NativeView OmniboxViewViews::GetNativeView() const {
577 return GetWidget()->GetNativeView();
580 gfx::NativeView OmniboxViewViews::GetRelativeWindowForPopup() const {
581 return GetWidget()->GetTopLevelWidget()->GetNativeView();
584 void OmniboxViewViews::SetGrayTextAutocompletion(const base::string16& input) {
585 location_bar_view_->SetGrayTextAutocompletion(input);
588 base::string16 OmniboxViewViews::GetGrayTextAutocompletion() const {
589 return location_bar_view_->GetGrayTextAutocompletion();
592 int OmniboxViewViews::GetWidth() const {
593 return location_bar_view_->width();
596 bool OmniboxViewViews::IsImeShowingPopup() const {
597 #if defined(OS_CHROMEOS)
598 return ime_candidate_window_open_;
600 const views::InputMethod* input_method = this->GetInputMethod();
601 return input_method && input_method->IsCandidatePopupOpen();
605 void OmniboxViewViews::ShowImeIfNeeded() {
606 GetInputMethod()->ShowImeIfNeeded();
609 void OmniboxViewViews::OnMatchOpened(const AutocompleteMatch& match,
611 content::WebContents* web_contents) const {
612 extensions::MaybeShowExtensionControlledSearchNotification(
613 profile, web_contents, match);
616 bool OmniboxViewViews::IsCommandIdEnabled(int command_id) const {
617 if (command_id == IDS_APP_PASTE)
618 return !read_only() && !GetClipboardText().empty();
619 if (command_id == IDS_PASTE_AND_GO)
620 return !read_only() && model()->CanPasteAndGo(GetClipboardText());
621 if (command_id == IDS_SHOW_URL)
622 return controller()->GetToolbarModel()->WouldReplaceURL();
623 return command_id == IDS_MOVE_DOWN || command_id == IDS_MOVE_UP ||
624 Textfield::IsCommandIdEnabled(command_id) ||
625 command_updater()->IsCommandEnabled(command_id);
628 bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id) const {
629 return command_id == IDS_PASTE_AND_GO;
632 base::string16 OmniboxViewViews::GetLabelForCommandId(int command_id) const {
633 DCHECK_EQ(IDS_PASTE_AND_GO, command_id);
634 return l10n_util::GetStringUTF16(
635 model()->IsPasteAndSearch(GetClipboardText()) ?
636 IDS_PASTE_AND_SEARCH : IDS_PASTE_AND_GO);
639 ////////////////////////////////////////////////////////////////////////////////
640 // OmniboxViewViews, private views::Textfield implementation:
642 const char* OmniboxViewViews::GetClassName() const {
643 return kViewClassName;
646 void OmniboxViewViews::OnPaint(gfx::Canvas* canvas) {
647 if (fade_in_animation_->is_animating()) {
648 canvas->SaveLayerAlpha(static_cast<uint8>(
649 fade_in_animation_->CurrentValueBetween(0, 255)));
650 views::Textfield::OnPaint(canvas);
653 views::Textfield::OnPaint(canvas);
657 bool OmniboxViewViews::OnMousePressed(const ui::MouseEvent& event) {
658 select_all_on_mouse_release_ =
659 (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) &&
660 (!HasFocus() || (model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE));
661 if (select_all_on_mouse_release_) {
662 // Restore caret visibility whenever the user clicks in the omnibox in a way
663 // that would give it focus. We must handle this case separately here
664 // because if the omnibox currently has invisible focus, the mouse event
665 // won't trigger either SetFocus() or OmniboxEditModel::OnSetFocus().
666 model()->SetCaretVisibility(true);
668 // When we're going to select all on mouse release, invalidate any saved
669 // selection lest restoring it fights with the "select all" action. It's
670 // possible to later set select_all_on_mouse_release_ back to false, but
671 // that happens for things like dragging, which are cases where having
672 // invalidated this saved selection is still OK.
673 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
675 return views::Textfield::OnMousePressed(event);
678 bool OmniboxViewViews::OnMouseDragged(const ui::MouseEvent& event) {
679 if (ExceededDragThreshold(event.location() - last_click_location()))
680 select_all_on_mouse_release_ = false;
682 if (HasTextBeingDragged())
685 return views::Textfield::OnMouseDragged(event);
688 void OmniboxViewViews::OnMouseReleased(const ui::MouseEvent& event) {
689 views::Textfield::OnMouseReleased(event);
690 if (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) {
691 // When the user has clicked and released to give us focus, select all
692 // unless we're omitting the URL (in which case refining an existing query
693 // is common enough that we do click-to-place-cursor).
694 if (select_all_on_mouse_release_ &&
695 !controller()->GetToolbarModel()->WouldReplaceURL()) {
696 // Select all in the reverse direction so as not to scroll the caret
697 // into view and shift the contents jarringly.
701 HandleOriginChipMouseRelease();
703 select_all_on_mouse_release_ = false;
706 bool OmniboxViewViews::OnKeyPressed(const ui::KeyEvent& event) {
707 // Skip processing of [Alt]+<num-pad digit> Unicode alt key codes.
708 // Otherwise, if num-lock is off, the events are handled as [Up], [Down], etc.
709 if (event.IsUnicodeKeyCode())
710 return views::Textfield::OnKeyPressed(event);
712 const bool shift = event.IsShiftDown();
713 const bool control = event.IsControlDown();
714 const bool alt = event.IsAltDown() || event.IsAltGrDown();
715 switch (event.key_code()) {
716 case ui::VKEY_RETURN:
717 model()->AcceptInput(alt ? NEW_FOREGROUND_TAB : CURRENT_TAB, false);
719 case ui::VKEY_ESCAPE:
720 return model()->OnEscapeKeyPressed();
721 case ui::VKEY_CONTROL:
722 model()->OnControlKeyChanged(true);
724 case ui::VKEY_DELETE:
725 if (shift && model()->popup_model()->IsOpen())
726 model()->popup_model()->TryDeletingCurrentItem();
730 model()->OnUpOrDownKeyPressed(-1);
736 model()->OnUpOrDownKeyPressed(1);
741 if (control || alt || shift)
743 model()->OnUpOrDownKeyPressed(-1 * model()->result().size());
746 if (control || alt || shift)
748 model()->OnUpOrDownKeyPressed(model()->result().size());
751 if (control && !alt && !read_only()) {
752 ExecuteCommand(IDS_APP_PASTE, 0);
756 case ui::VKEY_INSERT:
757 if (shift && !control && !read_only()) {
758 ExecuteCommand(IDS_APP_PASTE, 0);
766 return views::Textfield::OnKeyPressed(event) || HandleEarlyTabActions(event);
769 bool OmniboxViewViews::OnKeyReleased(const ui::KeyEvent& event) {
770 // The omnibox contents may change while the control key is pressed.
771 if (event.key_code() == ui::VKEY_CONTROL)
772 model()->OnControlKeyChanged(false);
773 return views::Textfield::OnKeyReleased(event);
776 void OmniboxViewViews::OnGestureEvent(ui::GestureEvent* event) {
777 if (!HasFocus() && event->type() == ui::ET_GESTURE_TAP_DOWN) {
778 select_all_on_gesture_tap_ = true;
780 // If we're trying to select all on tap, invalidate any saved selection lest
781 // restoring it fights with the "select all" action.
782 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
785 if (select_all_on_gesture_tap_ && event->type() == ui::ET_GESTURE_TAP)
788 if (event->type() == ui::ET_GESTURE_TAP ||
789 event->type() == ui::ET_GESTURE_TAP_CANCEL ||
790 event->type() == ui::ET_GESTURE_TWO_FINGER_TAP ||
791 event->type() == ui::ET_GESTURE_SCROLL_BEGIN ||
792 event->type() == ui::ET_GESTURE_PINCH_BEGIN ||
793 event->type() == ui::ET_GESTURE_LONG_PRESS ||
794 event->type() == ui::ET_GESTURE_LONG_TAP) {
795 select_all_on_gesture_tap_ = false;
798 views::Textfield::OnGestureEvent(event);
801 void OmniboxViewViews::AboutToRequestFocusFromTabTraversal(bool reverse) {
802 views::Textfield::AboutToRequestFocusFromTabTraversal(reverse);
803 // Tabbing into the omnibox should affect the origin chip in the same way
804 // clicking it should.
805 HandleOriginChipMouseRelease();
808 bool OmniboxViewViews::SkipDefaultKeyEventProcessing(
809 const ui::KeyEvent& event) {
810 if (views::FocusManager::IsTabTraversalKeyEvent(event) &&
811 ((model()->is_keyword_hint() && !event.IsShiftDown()) ||
812 model()->popup_model()->IsOpen())) {
815 return Textfield::SkipDefaultKeyEventProcessing(event);
818 void OmniboxViewViews::GetAccessibleState(ui::AXViewState* state) {
819 location_bar_view_->GetAccessibleState(state);
820 state->role = ui::AX_ROLE_TEXT_FIELD;
823 void OmniboxViewViews::OnFocus() {
824 views::Textfield::OnFocus();
825 // TODO(oshima): Get control key state.
826 model()->OnSetFocus(false);
827 // Don't call controller()->OnSetFocus, this view has already acquired focus.
829 // Restore the selection we saved in OnBlur() if it's still valid.
830 if (saved_selection_for_focus_change_.IsValid()) {
831 SelectRange(saved_selection_for_focus_change_);
832 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
836 void OmniboxViewViews::OnBlur() {
837 // Save the user's existing selection to restore it later.
838 saved_selection_for_focus_change_ = GetSelectedRange();
840 views::Textfield::OnBlur();
841 gfx::NativeView native_view = NULL;
842 views::Widget* widget = GetWidget();
844 aura::client::FocusClient* client =
845 aura::client::GetFocusClient(widget->GetNativeView());
847 native_view = client->GetFocusedWindow();
849 model()->OnWillKillFocus(native_view);
853 // Tell the model to reset itself.
854 model()->OnKillFocus();
856 // Ignore loss of focus if we lost focus because the website settings popup
857 // is open. When the popup is destroyed, focus will return to the Omnibox.
858 if (!WebsiteSettingsPopupView::IsPopupShowing())
861 // Make sure the beginning of the text is visible.
862 SelectRange(gfx::Range(0));
865 base::string16 OmniboxViewViews::GetSelectionClipboardText() const {
866 return SanitizeTextForPaste(Textfield::GetSelectionClipboardText());
869 ////////////////////////////////////////////////////////////////////////////////
870 // OmniboxViewViews, private gfx::AnimationDelegate implementation:
872 void OmniboxViewViews::AnimationProgressed(const gfx::Animation* animation) {
876 void OmniboxViewViews::AnimationEnded(const gfx::Animation* animation) {
877 fade_in_animation_->Reset();
880 ////////////////////////////////////////////////////////////////////////////////
882 // chromeos::input_method::InputMethodManager::CandidateWindowObserver
883 // private implementation:
885 #if defined(OS_CHROMEOS)
886 void OmniboxViewViews::CandidateWindowOpened(
887 chromeos::input_method::InputMethodManager* manager) {
888 ime_candidate_window_open_ = true;
891 void OmniboxViewViews::CandidateWindowClosed(
892 chromeos::input_method::InputMethodManager* manager) {
893 ime_candidate_window_open_ = false;
897 ////////////////////////////////////////////////////////////////////////////////
898 // OmniboxViewViews, private views::TextfieldController implementation:
900 void OmniboxViewViews::ContentsChanged(views::Textfield* sender,
901 const base::string16& new_contents) {
904 bool OmniboxViewViews::HandleKeyEvent(views::Textfield* textfield,
905 const ui::KeyEvent& event) {
906 delete_at_end_pressed_ = false;
908 if (event.key_code() == ui::VKEY_BACK) {
909 // No extra handling is needed in keyword search mode, if there is a
910 // non-empty selection, or if the cursor is not leading the text.
911 if (model()->is_keyword_hint() || model()->keyword().empty() ||
912 HasSelection() || GetCursorPosition() != 0)
914 model()->ClearKeyword(text());
918 if (event.key_code() == ui::VKEY_DELETE && !event.IsAltDown()) {
919 delete_at_end_pressed_ =
920 (!HasSelection() && GetCursorPosition() == text().length());
923 // Handle the right-arrow key for LTR text and the left-arrow key for RTL text
924 // if there is gray text that needs to be committed.
925 if (GetCursorPosition() == text().length()) {
926 base::i18n::TextDirection direction = GetTextDirection();
927 if ((direction == base::i18n::LEFT_TO_RIGHT &&
928 event.key_code() == ui::VKEY_RIGHT) ||
929 (direction == base::i18n::RIGHT_TO_LEFT &&
930 event.key_code() == ui::VKEY_LEFT)) {
931 return model()->CommitSuggestedText();
938 void OmniboxViewViews::OnBeforeUserAction(views::Textfield* sender) {
939 OnBeforePossibleChange();
942 void OmniboxViewViews::OnAfterUserAction(views::Textfield* sender) {
943 OnAfterPossibleChange();
946 void OmniboxViewViews::OnAfterCutOrCopy(ui::ClipboardType clipboard_type) {
947 ui::Clipboard* cb = ui::Clipboard::GetForCurrentThread();
948 base::string16 selected_text;
949 cb->ReadText(clipboard_type, &selected_text);
952 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
953 &selected_text, &url, &write_url);
955 UMA_HISTOGRAM_COUNTS(OmniboxEditModel::kCutOrCopyAllTextHistogram, 1);
958 BookmarkNodeData data;
959 data.ReadFromTuple(url, selected_text);
960 data.WriteToClipboard(clipboard_type);
962 ui::ScopedClipboardWriter scoped_clipboard_writer(
963 ui::Clipboard::GetForCurrentThread(), clipboard_type);
964 scoped_clipboard_writer.WriteText(selected_text);
968 void OmniboxViewViews::OnWriteDragData(ui::OSExchangeData* data) {
971 bool is_all_selected = IsSelectAll();
972 base::string16 selected_text = GetSelectedText();
973 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), is_all_selected,
974 &selected_text, &url, &write_url);
975 data->SetString(selected_text);
978 base::string16 title = selected_text;
980 model()->GetDataForURLExport(&url, &title, &favicon);
981 button_drag_utils::SetURLAndDragImage(url, title, favicon.AsImageSkia(),
983 data->SetURL(url, title);
987 void OmniboxViewViews::OnGetDragOperationsForTextfield(int* drag_operations) {
988 base::string16 selected_text = GetSelectedText();
991 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
992 &selected_text, &url, &write_url);
994 *drag_operations |= ui::DragDropTypes::DRAG_LINK;
997 void OmniboxViewViews::AppendDropFormats(
999 std::set<ui::OSExchangeData::CustomFormat>* custom_formats) {
1000 *formats = *formats | ui::OSExchangeData::URL;
1003 int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) {
1004 if (HasTextBeingDragged())
1005 return ui::DragDropTypes::DRAG_NONE;
1007 if (data.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)) {
1009 base::string16 title;
1010 if (data.GetURLAndTitle(
1011 ui::OSExchangeData::CONVERT_FILENAMES, &url, &title)) {
1012 base::string16 text(
1013 StripJavascriptSchemas(base::UTF8ToUTF16(url.spec())));
1014 if (model()->CanPasteAndGo(text)) {
1015 model()->PasteAndGo(text);
1016 return ui::DragDropTypes::DRAG_COPY;
1019 } else if (data.HasString()) {
1020 base::string16 text;
1021 if (data.GetString(&text)) {
1022 base::string16 collapsed_text(base::CollapseWhitespace(text, true));
1023 if (model()->CanPasteAndGo(collapsed_text))
1024 model()->PasteAndGo(collapsed_text);
1025 return ui::DragDropTypes::DRAG_COPY;
1029 return ui::DragDropTypes::DRAG_NONE;
1032 void OmniboxViewViews::UpdateContextMenu(ui::SimpleMenuModel* menu_contents) {
1033 int paste_position = menu_contents->GetIndexOfCommandId(IDS_APP_PASTE);
1034 DCHECK_GE(paste_position, 0);
1035 menu_contents->InsertItemWithStringIdAt(
1036 paste_position + 1, IDS_PASTE_AND_GO, IDS_PASTE_AND_GO);
1038 menu_contents->AddSeparator(ui::NORMAL_SEPARATOR);
1040 if (chrome::IsQueryExtractionEnabled() || chrome::ShouldDisplayOriginChip() ||
1041 chrome::ShouldDisplayOriginChipV2()) {
1042 int select_all_position = menu_contents->GetIndexOfCommandId(
1043 IDS_APP_SELECT_ALL);
1044 DCHECK_GE(select_all_position, 0);
1045 menu_contents->InsertItemWithStringIdAt(
1046 select_all_position + 1, IDS_SHOW_URL, IDS_SHOW_URL);
1049 // Minor note: We use IDC_ for command id here while the underlying textfield
1050 // is using IDS_ for all its command ids. This is because views cannot depend
1052 menu_contents->AddItemWithStringId(IDC_EDIT_SEARCH_ENGINES,
1053 IDS_EDIT_SEARCH_ENGINES);