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/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"
66 // OmniboxState ---------------------------------------------------------------
68 // Stores omnibox state for each tab.
69 struct OmniboxState
: public base::SupportsUserData::Data
{
70 static const char kKey
[];
72 OmniboxState(const OmniboxEditModel::State
& model_state
,
73 const gfx::Range
& selection
,
74 const gfx::Range
& saved_selection_for_focus_change
);
75 virtual ~OmniboxState();
77 const OmniboxEditModel::State model_state
;
79 // We store both the actual selection and any saved selection (for when the
80 // omnibox is not focused). This allows us to properly handle cases like
81 // selecting text, tabbing out of the omnibox, switching tabs away and back,
82 // and tabbing back into the omnibox.
83 const gfx::Range selection
;
84 const gfx::Range saved_selection_for_focus_change
;
88 const char OmniboxState::kKey
[] = "OmniboxState";
90 OmniboxState::OmniboxState(const OmniboxEditModel::State
& model_state
,
91 const gfx::Range
& selection
,
92 const gfx::Range
& saved_selection_for_focus_change
)
93 : model_state(model_state
),
95 saved_selection_for_focus_change(saved_selection_for_focus_change
) {
98 OmniboxState::~OmniboxState() {
102 // Helpers --------------------------------------------------------------------
104 // We'd like to set the text input type to TEXT_INPUT_TYPE_URL, because this
105 // triggers URL-specific layout in software keyboards, e.g. adding top-level "/"
106 // and ".com" keys for English. However, this also causes IMEs to default to
107 // Latin character mode, which makes entering search queries difficult for IME
108 // users. Therefore, we try to guess whether an IME will be used based on the
109 // application language, and set the input type accordingly.
110 ui::TextInputType
DetermineTextInputType() {
112 DCHECK(g_browser_process
);
113 const std::string
& locale
= g_browser_process
->GetApplicationLocale();
114 const std::string
& language
= locale
.substr(0, 2);
115 // Assume CJK + Thai users are using an IME.
116 if (language
== "ja" ||
120 return ui::TEXT_INPUT_TYPE_SEARCH
;
122 return ui::TEXT_INPUT_TYPE_URL
;
128 // OmniboxViewViews -----------------------------------------------------------
131 const char OmniboxViewViews::kViewClassName
[] = "OmniboxViewViews";
133 OmniboxViewViews::OmniboxViewViews(OmniboxEditController
* controller
,
135 CommandUpdater
* command_updater
,
136 bool popup_window_mode
,
137 LocationBarView
* location_bar
,
138 const gfx::FontList
& font_list
)
139 : OmniboxView(profile
, controller
, command_updater
),
140 popup_window_mode_(popup_window_mode
),
141 security_level_(ToolbarModel::NONE
),
142 saved_selection_for_focus_change_(gfx::Range::InvalidRange()),
143 ime_composing_before_change_(false),
144 delete_at_end_pressed_(false),
145 location_bar_view_(location_bar
),
146 ime_candidate_window_open_(false),
147 select_all_on_mouse_release_(false),
148 select_all_on_gesture_tap_(false) {
149 SetBorder(views::Border::NullBorder());
150 set_id(VIEW_ID_OMNIBOX
);
151 SetFontList(font_list
);
154 OmniboxViewViews::~OmniboxViewViews() {
155 #if defined(OS_CHROMEOS)
156 chromeos::input_method::InputMethodManager::Get()->
157 RemoveCandidateWindowObserver(this);
160 // Explicitly teardown members which have a reference to us. Just to be safe
161 // we want them to be destroyed before destroying any other internal state.
165 void OmniboxViewViews::Init() {
166 set_controller(this);
167 SetTextInputType(DetermineTextInputType());
169 if (popup_window_mode_
)
172 // Initialize the popup view using the same font.
173 popup_view_
.reset(OmniboxPopupContentsView::Create(
174 GetFontList(), this, model(), location_bar_view_
));
176 #if defined(OS_CHROMEOS)
177 chromeos::input_method::InputMethodManager::Get()->
178 AddCandidateWindowObserver(this);
181 fade_in_animation_
.reset(new gfx::SlideAnimation(this));
182 fade_in_animation_
->SetTweenType(gfx::Tween::LINEAR
);
183 fade_in_animation_
->SetSlideDuration(300);
186 void OmniboxViewViews::FadeIn() {
187 fade_in_animation_
->Show();
190 void OmniboxViewViews::SaveStateToTab(content::WebContents
* tab
) {
193 // We don't want to keep the IME status, so force quit the current
194 // session here. It may affect the selection status, so order is
196 if (IsIMEComposing()) {
197 GetTextInputClient()->ConfirmCompositionText();
198 GetInputMethod()->CancelComposition(this);
201 // NOTE: GetStateForTabSwitch() may affect GetSelectedRange(), so order is
203 OmniboxEditModel::State state
= model()->GetStateForTabSwitch();
204 tab
->SetUserData(OmniboxState::kKey
, new OmniboxState(
205 state
, GetSelectedRange(), saved_selection_for_focus_change_
));
208 void OmniboxViewViews::OnTabChanged(const content::WebContents
* web_contents
) {
209 security_level_
= controller()->GetToolbarModel()->GetSecurityLevel(false);
211 const OmniboxState
* state
= static_cast<OmniboxState
*>(
212 web_contents
->GetUserData(&OmniboxState::kKey
));
213 model()->RestoreState(state
? &state
->model_state
: NULL
);
215 // This assumes that the omnibox has already been focused or blurred as
216 // appropriate; otherwise, a subsequent OnFocus() or OnBlur() call could
217 // goof up the selection. See comments at the end of
218 // BrowserView::ActiveTabChanged().
219 SelectRange(state
->selection
);
220 saved_selection_for_focus_change_
= state
->saved_selection_for_focus_change
;
223 // TODO(msw|oshima): Consider saving/restoring edit history.
227 void OmniboxViewViews::Update() {
228 if (chrome::ShouldDisplayOriginChip())
229 set_placeholder_text(GetHintText());
231 const ToolbarModel::SecurityLevel old_security_level
= security_level_
;
232 security_level_
= controller()->GetToolbarModel()->GetSecurityLevel(false);
233 if (model()->UpdatePermanentText()) {
234 // Something visibly changed. Re-enable URL replacement.
235 controller()->GetToolbarModel()->set_url_replacement_enabled(true);
236 controller()->GetToolbarModel()->set_origin_chip_enabled(true);
237 model()->UpdatePermanentText();
239 // Select all the new text if the user had all the old text selected, or if
240 // there was no previous text (for new tab page URL replacement extensions).
241 // This makes one particular case better: the user clicks in the box to
242 // change it right before the permanent URL is changed. Since the new URL
243 // is still fully selected, the user's typing will replace the edit contents
244 // as they'd intended.
245 const bool was_select_all
= IsSelectAll();
246 const bool was_reversed
= GetSelectedRange().is_reversed();
250 // Only select all when we have focus. If we don't have focus, selecting
251 // all is unnecessary since the selection will change on regaining focus,
252 // and can in fact cause artifacts, e.g. if the user is on the NTP and
253 // clicks a link to navigate, causing |was_select_all| to be vacuously true
254 // for the empty omnibox, and we then select all here, leading to the
255 // trailing portion of a long URL being scrolled into view. We could try
256 // and address cases like this, but it seems better to just not muck with
257 // things when the omnibox isn't focused to begin with.
258 if (was_select_all
&& model()->has_focus())
259 SelectAll(was_reversed
);
260 } else if (old_security_level
!= security_level_
) {
261 EmphasizeURLComponents();
265 base::string16
OmniboxViewViews::GetText() const {
266 // TODO(oshima): IME support
270 void OmniboxViewViews::SetUserText(const base::string16
& text
,
271 const base::string16
& display_text
,
273 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
274 OmniboxView::SetUserText(text
, display_text
, update_popup
);
277 void OmniboxViewViews::SetForcedQuery() {
278 const base::string16
current_text(text());
279 const size_t start
= current_text
.find_first_not_of(base::kWhitespaceUTF16
);
280 if (start
== base::string16::npos
|| (current_text
[start
] != '?'))
281 OmniboxView::SetUserText(base::ASCIIToUTF16("?"));
283 SelectRange(gfx::Range(current_text
.size(), start
+ 1));
286 void OmniboxViewViews::GetSelectionBounds(
287 base::string16::size_type
* start
,
288 base::string16::size_type
* end
) const {
289 const gfx::Range range
= GetSelectedRange();
290 *start
= static_cast<size_t>(range
.start());
291 *end
= static_cast<size_t>(range
.end());
294 void OmniboxViewViews::SelectAll(bool reversed
) {
295 views::Textfield::SelectAll(reversed
);
298 void OmniboxViewViews::RevertAll() {
299 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
300 OmniboxView::RevertAll();
303 void OmniboxViewViews::SetFocus() {
305 // Restore caret visibility if focus is explicitly requested. This is
306 // necessary because if we already have invisible focus, the RequestFocus()
307 // call above will short-circuit, preventing us from reaching
308 // OmniboxEditModel::OnSetFocus(), which handles restoring visibility when the
309 // omnibox regains focus after losing focus.
310 model()->SetCaretVisibility(true);
313 int OmniboxViewViews::GetTextWidth() const {
314 // Returns the width necessary to display the current text, including any
315 // necessary space for the cursor or border/margin.
316 return GetRenderText()->GetContentWidth() + GetInsets().width();
319 bool OmniboxViewViews::IsImeComposing() const {
320 return IsIMEComposing();
323 gfx::Size
OmniboxViewViews::GetMinimumSize() const {
324 const int kMinCharacters
= 10;
326 GetFontList().GetExpectedTextWidth(kMinCharacters
) + GetInsets().width(),
327 GetPreferredSize().height());
330 void OmniboxViewViews::OnNativeThemeChanged(const ui::NativeTheme
* theme
) {
331 views::Textfield::OnNativeThemeChanged(theme
);
332 SetBackgroundColor(location_bar_view_
->GetColor(
333 ToolbarModel::NONE
, LocationBarView::BACKGROUND
));
334 EmphasizeURLComponents();
337 void OmniboxViewViews::ExecuteCommand(int command_id
, int event_flags
) {
338 switch (command_id
) {
339 // These commands don't invoke the popup via OnBefore/AfterPossibleChange().
340 case IDS_PASTE_AND_GO
:
341 model()->PasteAndGo(GetClipboardText());
344 controller()->ShowURL();
346 case IDC_EDIT_SEARCH_ENGINES
:
347 command_updater()->ExecuteCommand(command_id
);
351 model()->OnUpOrDownKeyPressed(command_id
== IDS_MOVE_DOWN
? 1 : -1);
355 OnBeforePossibleChange();
356 if (command_id
== IDS_APP_PASTE
)
358 else if (Textfield::IsCommandIdEnabled(command_id
))
359 Textfield::ExecuteCommand(command_id
, event_flags
);
361 command_updater()->ExecuteCommand(command_id
);
362 OnAfterPossibleChange();
367 void OmniboxViewViews::SetTextAndSelectedRange(const base::string16
& text
,
368 const gfx::Range
& range
) {
373 base::string16
OmniboxViewViews::GetSelectedText() const {
374 // TODO(oshima): Support IME.
375 return views::Textfield::GetSelectedText();
378 void OmniboxViewViews::OnPaste() {
379 const base::string16
text(GetClipboardText());
381 // Record this paste, so we can do different behavior.
383 // Force a Paste operation to trigger the text_changed code in
384 // OnAfterPossibleChange(), even if identical contents are pasted.
385 text_before_change_
.clear();
386 InsertOrReplaceText(text
);
390 bool OmniboxViewViews::HandleEarlyTabActions(const ui::KeyEvent
& event
) {
391 // This must run before acclerator handling invokes a focus change on tab.
392 // Note the parallel with SkipDefaultKeyEventProcessing above.
393 if (views::FocusManager::IsTabTraversalKeyEvent(event
)) {
394 if (model()->is_keyword_hint() && !event
.IsShiftDown()) {
395 model()->AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_TAB
);
398 if (model()->popup_model()->IsOpen()) {
399 if (event
.IsShiftDown() &&
400 model()->popup_model()->selected_line_state() ==
401 OmniboxPopupModel::KEYWORD
) {
402 model()->ClearKeyword(text());
404 model()->OnUpOrDownKeyPressed(event
.IsShiftDown() ? -1 : 1);
413 void OmniboxViewViews::SetWindowTextAndCaretPos(const base::string16
& text
,
416 bool notify_text_changed
) {
417 const gfx::Range
range(caret_pos
, caret_pos
);
418 SetTextAndSelectedRange(text
, range
);
423 if (notify_text_changed
)
427 bool OmniboxViewViews::IsSelectAll() const {
428 // TODO(oshima): IME support.
429 return text() == GetSelectedText();
432 bool OmniboxViewViews::DeleteAtEndPressed() {
433 return delete_at_end_pressed_
;
436 void OmniboxViewViews::UpdatePopup() {
437 model()->SetInputInProgress(true);
438 if (!model()->has_focus())
441 // Prevent inline autocomplete when the caret isn't at the end of the text.
442 const gfx::Range sel
= GetSelectedRange();
443 model()->StartAutocomplete(!sel
.is_empty(), sel
.GetMax() < text().length());
446 void OmniboxViewViews::ApplyCaretVisibility() {
447 SetCursorEnabled(model()->is_caret_visible());
450 void OmniboxViewViews::OnTemporaryTextMaybeChanged(
451 const base::string16
& display_text
,
452 bool save_original_selection
,
453 bool notify_text_changed
) {
454 if (save_original_selection
)
455 saved_temporary_selection_
= GetSelectedRange();
457 SetWindowTextAndCaretPos(display_text
, display_text
.length(), false,
458 notify_text_changed
);
461 bool OmniboxViewViews::OnInlineAutocompleteTextMaybeChanged(
462 const base::string16
& display_text
,
463 size_t user_text_length
) {
464 if (display_text
== text())
467 if (IsIMEComposing()) {
468 location_bar_view_
->SetImeInlineAutocompletion(
469 display_text
.substr(user_text_length
));
471 gfx::Range
range(display_text
.size(), user_text_length
);
472 SetTextAndSelectedRange(display_text
, range
);
478 void OmniboxViewViews::OnInlineAutocompleteTextCleared() {
479 // Hide the inline autocompletion for IME users.
480 location_bar_view_
->SetImeInlineAutocompletion(base::string16());
483 void OmniboxViewViews::OnRevertTemporaryText() {
484 SelectRange(saved_temporary_selection_
);
485 // We got here because the user hit the Escape key. We explicitly don't call
486 // TextChanged(), since OmniboxPopupModel::ResetToDefaultMatch() has already
487 // been called by now, and it would've called TextChanged() if it was
491 void OmniboxViewViews::OnBeforePossibleChange() {
493 text_before_change_
= text();
494 sel_before_change_
= GetSelectedRange();
495 ime_composing_before_change_
= IsIMEComposing();
498 bool OmniboxViewViews::OnAfterPossibleChange() {
499 // See if the text or selection have changed since OnBeforePossibleChange().
500 const base::string16 new_text
= text();
501 const gfx::Range new_sel
= GetSelectedRange();
502 const bool text_changed
= (new_text
!= text_before_change_
) ||
503 (ime_composing_before_change_
!= IsIMEComposing());
504 const bool selection_differs
=
505 !((sel_before_change_
.is_empty() && new_sel
.is_empty()) ||
506 sel_before_change_
.EqualsIgnoringDirection(new_sel
));
508 // When the user has deleted text, we don't allow inline autocomplete. Make
509 // sure to not flag cases like selecting part of the text and then pasting
510 // (or typing) the prefix of that selection. (We detect these by making
511 // sure the caret, which should be after any insertion, hasn't moved
512 // forward of the old selection start.)
513 const bool just_deleted_text
=
514 (text_before_change_
.length() > new_text
.length()) &&
515 (new_sel
.start() <= sel_before_change_
.GetMin());
517 const bool something_changed
= model()->OnAfterPossibleChange(
518 text_before_change_
, new_text
, new_sel
.start(), new_sel
.end(),
519 selection_differs
, text_changed
, just_deleted_text
, !IsIMEComposing());
521 // If only selection was changed, we don't need to call model()'s
522 // OnChanged() method, which is called in TextChanged().
523 // But we still need to call EmphasizeURLComponents() to make sure the text
524 // attributes are updated correctly.
525 if (something_changed
&& text_changed
)
527 else if (selection_differs
)
528 EmphasizeURLComponents();
529 else if (delete_at_end_pressed_
)
530 model()->OnChanged();
532 return something_changed
;
535 gfx::NativeView
OmniboxViewViews::GetNativeView() const {
536 return GetWidget()->GetNativeView();
539 gfx::NativeView
OmniboxViewViews::GetRelativeWindowForPopup() const {
540 return GetWidget()->GetTopLevelWidget()->GetNativeView();
543 void OmniboxViewViews::SetGrayTextAutocompletion(const base::string16
& input
) {
544 location_bar_view_
->SetGrayTextAutocompletion(input
);
547 base::string16
OmniboxViewViews::GetGrayTextAutocompletion() const {
548 return location_bar_view_
->GetGrayTextAutocompletion();
551 int OmniboxViewViews::GetWidth() const {
552 return location_bar_view_
->width();
555 bool OmniboxViewViews::IsImeShowingPopup() const {
556 #if defined(OS_CHROMEOS)
557 return ime_candidate_window_open_
;
559 const views::InputMethod
* input_method
= this->GetInputMethod();
560 return input_method
&& input_method
->IsCandidatePopupOpen();
564 void OmniboxViewViews::ShowImeIfNeeded() {
565 GetInputMethod()->ShowImeIfNeeded();
568 void OmniboxViewViews::OnMatchOpened(const AutocompleteMatch
& match
,
570 content::WebContents
* web_contents
) const {
571 extensions::MaybeShowExtensionControlledSearchNotification(
572 profile
, web_contents
, match
);
575 int OmniboxViewViews::GetOmniboxTextLength() const {
576 // TODO(oshima): Support IME.
577 return static_cast<int>(text().length());
580 void OmniboxViewViews::EmphasizeURLComponents() {
581 // See whether the contents are a URL with a non-empty host portion, which we
582 // should emphasize. To check for a URL, rather than using the type returned
583 // by Parse(), ask the model, which will check the desired page transition for
584 // this input. This can tell us whether an UNKNOWN input string is going to
585 // be treated as a search or a navigation, and is the same method the Paste
586 // And Go system uses.
587 url::Component scheme
, host
;
588 AutocompleteInput::ParseForEmphasizeComponents(text(), &scheme
, &host
);
589 bool grey_out_url
= text().substr(scheme
.begin
, scheme
.len
) ==
590 base::UTF8ToUTF16(extensions::kExtensionScheme
);
591 bool grey_base
= model()->CurrentTextIsURL() &&
592 (host
.is_nonempty() || grey_out_url
);
593 SetColor(location_bar_view_
->GetColor(
595 grey_base
? LocationBarView::DEEMPHASIZED_TEXT
: LocationBarView::TEXT
));
596 if (grey_base
&& !grey_out_url
) {
598 location_bar_view_
->GetColor(security_level_
, LocationBarView::TEXT
),
599 gfx::Range(host
.begin
, host
.end()));
602 // Emphasize the scheme for security UI display purposes (if necessary).
603 // Note that we check CurrentTextIsURL() because if we're replacing search
604 // URLs with search terms, we may have a non-URL even when the user is not
605 // editing; and in some cases, e.g. for "site:foo.com" searches, the parser
606 // may have incorrectly identified a qualifier as a scheme.
607 SetStyle(gfx::DIAGONAL_STRIKE
, false);
608 if (!model()->user_input_in_progress() && model()->CurrentTextIsURL() &&
609 scheme
.is_nonempty() && (security_level_
!= ToolbarModel::NONE
)) {
610 SkColor security_color
= location_bar_view_
->GetColor(
611 security_level_
, LocationBarView::SECURITY_TEXT
);
612 const bool strike
= (security_level_
== ToolbarModel::SECURITY_ERROR
);
613 const gfx::Range
scheme_range(scheme
.begin
, scheme
.end());
614 ApplyColor(security_color
, scheme_range
);
615 ApplyStyle(gfx::DIAGONAL_STRIKE
, strike
, scheme_range
);
619 bool OmniboxViewViews::OnKeyReleased(const ui::KeyEvent
& event
) {
620 // The omnibox contents may change while the control key is pressed.
621 if (event
.key_code() == ui::VKEY_CONTROL
)
622 model()->OnControlKeyChanged(false);
623 return views::Textfield::OnKeyReleased(event
);
626 bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id
) const {
627 return command_id
== IDS_PASTE_AND_GO
;
630 base::string16
OmniboxViewViews::GetLabelForCommandId(int command_id
) const {
631 DCHECK_EQ(IDS_PASTE_AND_GO
, command_id
);
632 return l10n_util::GetStringUTF16(
633 model()->IsPasteAndSearch(GetClipboardText()) ?
634 IDS_PASTE_AND_SEARCH
: IDS_PASTE_AND_GO
);
637 const char* OmniboxViewViews::GetClassName() const {
638 return kViewClassName
;
641 bool OmniboxViewViews::OnMousePressed(const ui::MouseEvent
& event
) {
642 select_all_on_mouse_release_
=
643 (event
.IsOnlyLeftMouseButton() || event
.IsOnlyRightMouseButton()) &&
644 (!HasFocus() || (model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE
));
645 if (select_all_on_mouse_release_
) {
646 // Restore caret visibility whenever the user clicks in the omnibox in a way
647 // that would give it focus. We must handle this case separately here
648 // because if the omnibox currently has invisible focus, the mouse event
649 // won't trigger either SetFocus() or OmniboxEditModel::OnSetFocus().
650 model()->SetCaretVisibility(true);
652 // When we're going to select all on mouse release, invalidate any saved
653 // selection lest restoring it fights with the "select all" action. It's
654 // possible to later set select_all_on_mouse_release_ back to false, but
655 // that happens for things like dragging, which are cases where having
656 // invalidated this saved selection is still OK.
657 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
659 return views::Textfield::OnMousePressed(event
);
662 bool OmniboxViewViews::OnMouseDragged(const ui::MouseEvent
& event
) {
663 if (ExceededDragThreshold(event
.location() - last_click_location()))
664 select_all_on_mouse_release_
= false;
666 if (HasTextBeingDragged())
669 return views::Textfield::OnMouseDragged(event
);
672 void OmniboxViewViews::OnMouseReleased(const ui::MouseEvent
& event
) {
673 views::Textfield::OnMouseReleased(event
);
674 if (event
.IsOnlyLeftMouseButton() || event
.IsOnlyRightMouseButton()) {
675 // When the user has clicked and released to give us focus, select all
676 // unless we're omitting the URL (in which case refining an existing query
677 // is common enough that we do click-to-place-cursor).
678 if (select_all_on_mouse_release_
&&
679 !controller()->GetToolbarModel()->WouldReplaceURL()) {
680 // Select all in the reverse direction so as not to scroll the caret
681 // into view and shift the contents jarringly.
685 HandleOriginChipMouseRelease();
687 select_all_on_mouse_release_
= false;
690 bool OmniboxViewViews::OnKeyPressed(const ui::KeyEvent
& event
) {
691 // Skip processing of [Alt]+<num-pad digit> Unicode alt key codes.
692 // Otherwise, if num-lock is off, the events are handled as [Up], [Down], etc.
693 if (event
.IsUnicodeKeyCode())
694 return views::Textfield::OnKeyPressed(event
);
696 const bool shift
= event
.IsShiftDown();
697 const bool control
= event
.IsControlDown();
698 const bool alt
= event
.IsAltDown() || event
.IsAltGrDown();
699 switch (event
.key_code()) {
700 case ui::VKEY_RETURN
:
701 model()->AcceptInput(alt
? NEW_FOREGROUND_TAB
: CURRENT_TAB
, false);
703 case ui::VKEY_ESCAPE
:
704 return model()->OnEscapeKeyPressed();
705 case ui::VKEY_CONTROL
:
706 model()->OnControlKeyChanged(true);
708 case ui::VKEY_DELETE
:
709 if (shift
&& model()->popup_model()->IsOpen())
710 model()->popup_model()->TryDeletingCurrentItem();
714 model()->OnUpOrDownKeyPressed(-1);
720 model()->OnUpOrDownKeyPressed(1);
725 if (control
|| alt
|| shift
)
727 model()->OnUpOrDownKeyPressed(-1 * model()->result().size());
730 if (control
|| alt
|| shift
)
732 model()->OnUpOrDownKeyPressed(model()->result().size());
735 if (control
&& !alt
&& !read_only()) {
736 ExecuteCommand(IDS_APP_PASTE
, 0);
740 case ui::VKEY_INSERT
:
741 if (shift
&& !control
&& !read_only()) {
742 ExecuteCommand(IDS_APP_PASTE
, 0);
750 return views::Textfield::OnKeyPressed(event
) || HandleEarlyTabActions(event
);
753 void OmniboxViewViews::OnGestureEvent(ui::GestureEvent
* event
) {
754 if (!HasFocus() && event
->type() == ui::ET_GESTURE_TAP_DOWN
) {
755 select_all_on_gesture_tap_
= true;
757 // If we're trying to select all on tap, invalidate any saved selection lest
758 // restoring it fights with the "select all" action.
759 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
762 if (select_all_on_gesture_tap_
&& event
->type() == ui::ET_GESTURE_TAP
)
765 if (event
->type() == ui::ET_GESTURE_TAP
||
766 event
->type() == ui::ET_GESTURE_TAP_CANCEL
||
767 event
->type() == ui::ET_GESTURE_TWO_FINGER_TAP
||
768 event
->type() == ui::ET_GESTURE_SCROLL_BEGIN
||
769 event
->type() == ui::ET_GESTURE_PINCH_BEGIN
||
770 event
->type() == ui::ET_GESTURE_LONG_PRESS
||
771 event
->type() == ui::ET_GESTURE_LONG_TAP
) {
772 select_all_on_gesture_tap_
= false;
775 views::Textfield::OnGestureEvent(event
);
778 void OmniboxViewViews::AboutToRequestFocusFromTabTraversal(bool reverse
) {
779 views::Textfield::AboutToRequestFocusFromTabTraversal(reverse
);
780 // Tabbing into the omnibox should affect the origin chip in the same way
781 // clicking it should.
782 HandleOriginChipMouseRelease();
785 bool OmniboxViewViews::SkipDefaultKeyEventProcessing(
786 const ui::KeyEvent
& event
) {
787 if (views::FocusManager::IsTabTraversalKeyEvent(event
) &&
788 ((model()->is_keyword_hint() && !event
.IsShiftDown()) ||
789 model()->popup_model()->IsOpen())) {
792 return Textfield::SkipDefaultKeyEventProcessing(event
);
795 void OmniboxViewViews::GetAccessibleState(ui::AXViewState
* state
) {
796 location_bar_view_
->GetAccessibleState(state
);
797 state
->role
= ui::AX_ROLE_TEXT_FIELD
;
800 void OmniboxViewViews::OnPaint(gfx::Canvas
* canvas
) {
801 if (fade_in_animation_
->is_animating()) {
802 canvas
->SaveLayerAlpha(static_cast<uint8
>(
803 fade_in_animation_
->CurrentValueBetween(0, 255)));
804 views::Textfield::OnPaint(canvas
);
807 views::Textfield::OnPaint(canvas
);
811 void OmniboxViewViews::OnFocus() {
812 views::Textfield::OnFocus();
813 // TODO(oshima): Get control key state.
814 model()->OnSetFocus(false);
815 // Don't call controller()->OnSetFocus, this view has already acquired focus.
817 // Restore the selection we saved in OnBlur() if it's still valid.
818 if (saved_selection_for_focus_change_
.IsValid()) {
819 SelectRange(saved_selection_for_focus_change_
);
820 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
824 void OmniboxViewViews::OnBlur() {
825 // Save the user's existing selection to restore it later.
826 saved_selection_for_focus_change_
= GetSelectedRange();
828 views::Textfield::OnBlur();
829 gfx::NativeView native_view
= NULL
;
830 views::Widget
* widget
= GetWidget();
832 aura::client::FocusClient
* client
=
833 aura::client::GetFocusClient(widget
->GetNativeView());
835 native_view
= client
->GetFocusedWindow();
837 model()->OnWillKillFocus(native_view
);
841 // Tell the model to reset itself.
842 model()->OnKillFocus();
844 // Ignore loss of focus if we lost focus because the website settings popup
845 // is open. When the popup is destroyed, focus will return to the Omnibox.
846 if (!WebsiteSettingsPopupView::IsPopupShowing())
849 // Make sure the beginning of the text is visible.
850 SelectRange(gfx::Range(0));
853 bool OmniboxViewViews::IsCommandIdEnabled(int command_id
) const {
854 if (command_id
== IDS_APP_PASTE
)
855 return !read_only() && !GetClipboardText().empty();
856 if (command_id
== IDS_PASTE_AND_GO
)
857 return !read_only() && model()->CanPasteAndGo(GetClipboardText());
858 if (command_id
== IDS_SHOW_URL
)
859 return controller()->GetToolbarModel()->WouldReplaceURL();
860 return command_id
== IDS_MOVE_DOWN
|| command_id
== IDS_MOVE_UP
||
861 Textfield::IsCommandIdEnabled(command_id
) ||
862 command_updater()->IsCommandEnabled(command_id
);
865 base::string16
OmniboxViewViews::GetSelectionClipboardText() const {
866 return SanitizeTextForPaste(Textfield::GetSelectionClipboardText());
869 void OmniboxViewViews::AnimationProgressed(const gfx::Animation
* animation
) {
873 void OmniboxViewViews::AnimationEnded(const gfx::Animation
* animation
) {
874 fade_in_animation_
->Reset();
877 #if defined(OS_CHROMEOS)
878 void OmniboxViewViews::CandidateWindowOpened(
879 chromeos::input_method::InputMethodManager
* manager
) {
880 ime_candidate_window_open_
= true;
883 void OmniboxViewViews::CandidateWindowClosed(
884 chromeos::input_method::InputMethodManager
* manager
) {
885 ime_candidate_window_open_
= false;
889 void OmniboxViewViews::ContentsChanged(views::Textfield
* sender
,
890 const base::string16
& new_contents
) {
893 bool OmniboxViewViews::HandleKeyEvent(views::Textfield
* textfield
,
894 const ui::KeyEvent
& event
) {
895 delete_at_end_pressed_
= false;
897 if (event
.key_code() == ui::VKEY_BACK
) {
898 // No extra handling is needed in keyword search mode, if there is a
899 // non-empty selection, or if the cursor is not leading the text.
900 if (model()->is_keyword_hint() || model()->keyword().empty() ||
901 HasSelection() || GetCursorPosition() != 0)
903 model()->ClearKeyword(text());
907 if (event
.key_code() == ui::VKEY_DELETE
&& !event
.IsAltDown()) {
908 delete_at_end_pressed_
=
909 (!HasSelection() && GetCursorPosition() == text().length());
912 // Handle the right-arrow key for LTR text and the left-arrow key for RTL text
913 // if there is gray text that needs to be committed.
914 if (GetCursorPosition() == text().length()) {
915 base::i18n::TextDirection direction
= GetTextDirection();
916 if ((direction
== base::i18n::LEFT_TO_RIGHT
&&
917 event
.key_code() == ui::VKEY_RIGHT
) ||
918 (direction
== base::i18n::RIGHT_TO_LEFT
&&
919 event
.key_code() == ui::VKEY_LEFT
)) {
920 return model()->CommitSuggestedText();
927 void OmniboxViewViews::OnBeforeUserAction(views::Textfield
* sender
) {
928 OnBeforePossibleChange();
931 void OmniboxViewViews::OnAfterUserAction(views::Textfield
* sender
) {
932 OnAfterPossibleChange();
935 void OmniboxViewViews::OnAfterCutOrCopy(ui::ClipboardType clipboard_type
) {
936 ui::Clipboard
* cb
= ui::Clipboard::GetForCurrentThread();
937 base::string16 selected_text
;
938 cb
->ReadText(clipboard_type
, &selected_text
);
941 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
942 &selected_text
, &url
, &write_url
);
944 UMA_HISTOGRAM_COUNTS(OmniboxEditModel::kCutOrCopyAllTextHistogram
, 1);
947 BookmarkNodeData data
;
948 data
.ReadFromTuple(url
, selected_text
);
949 data
.WriteToClipboard(clipboard_type
);
951 ui::ScopedClipboardWriter
scoped_clipboard_writer(
952 ui::Clipboard::GetForCurrentThread(), clipboard_type
);
953 scoped_clipboard_writer
.WriteText(selected_text
);
957 void OmniboxViewViews::OnWriteDragData(ui::OSExchangeData
* data
) {
960 bool is_all_selected
= IsSelectAll();
961 base::string16 selected_text
= GetSelectedText();
962 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), is_all_selected
,
963 &selected_text
, &url
, &write_url
);
964 data
->SetString(selected_text
);
967 base::string16 title
= selected_text
;
969 model()->GetDataForURLExport(&url
, &title
, &favicon
);
970 button_drag_utils::SetURLAndDragImage(url
, title
, favicon
.AsImageSkia(),
972 data
->SetURL(url
, title
);
976 void OmniboxViewViews::OnGetDragOperationsForTextfield(int* drag_operations
) {
977 base::string16 selected_text
= GetSelectedText();
980 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
981 &selected_text
, &url
, &write_url
);
983 *drag_operations
|= ui::DragDropTypes::DRAG_LINK
;
986 void OmniboxViewViews::AppendDropFormats(
988 std::set
<ui::OSExchangeData::CustomFormat
>* custom_formats
) {
989 *formats
= *formats
| ui::OSExchangeData::URL
;
992 int OmniboxViewViews::OnDrop(const ui::OSExchangeData
& data
) {
993 if (HasTextBeingDragged())
994 return ui::DragDropTypes::DRAG_NONE
;
996 if (data
.HasURL(ui::OSExchangeData::CONVERT_FILENAMES
)) {
998 base::string16 title
;
999 if (data
.GetURLAndTitle(
1000 ui::OSExchangeData::CONVERT_FILENAMES
, &url
, &title
)) {
1001 base::string16
text(
1002 StripJavascriptSchemas(base::UTF8ToUTF16(url
.spec())));
1003 if (model()->CanPasteAndGo(text
)) {
1004 model()->PasteAndGo(text
);
1005 return ui::DragDropTypes::DRAG_COPY
;
1008 } else if (data
.HasString()) {
1009 base::string16 text
;
1010 if (data
.GetString(&text
)) {
1011 base::string16
collapsed_text(base::CollapseWhitespace(text
, true));
1012 if (model()->CanPasteAndGo(collapsed_text
))
1013 model()->PasteAndGo(collapsed_text
);
1014 return ui::DragDropTypes::DRAG_COPY
;
1018 return ui::DragDropTypes::DRAG_NONE
;
1021 void OmniboxViewViews::UpdateContextMenu(ui::SimpleMenuModel
* menu_contents
) {
1022 int paste_position
= menu_contents
->GetIndexOfCommandId(IDS_APP_PASTE
);
1023 DCHECK_GE(paste_position
, 0);
1024 menu_contents
->InsertItemWithStringIdAt(
1025 paste_position
+ 1, IDS_PASTE_AND_GO
, IDS_PASTE_AND_GO
);
1027 menu_contents
->AddSeparator(ui::NORMAL_SEPARATOR
);
1029 if (chrome::IsQueryExtractionEnabled() || chrome::ShouldDisplayOriginChip()) {
1030 int select_all_position
= menu_contents
->GetIndexOfCommandId(
1031 IDS_APP_SELECT_ALL
);
1032 DCHECK_GE(select_all_position
, 0);
1033 menu_contents
->InsertItemWithStringIdAt(
1034 select_all_position
+ 1, IDS_SHOW_URL
, IDS_SHOW_URL
);
1037 // Minor note: We use IDC_ for command id here while the underlying textfield
1038 // is using IDS_ for all its command ids. This is because views cannot depend
1040 menu_contents
->AddItemWithStringId(IDC_EDIT_SEARCH_ENGINES
,
1041 IDS_EDIT_SEARCH_ENGINES
);