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"
9 #include "base/command_line.h"
10 #include "base/logging.h"
11 #include "base/metrics/histogram.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "chrome/app/chrome_command_ids.h"
15 #include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
16 #include "chrome/browser/command_updater.h"
17 #include "chrome/browser/search/search.h"
18 #include "chrome/browser/ui/omnibox/chrome_omnibox_client.h"
19 #include "chrome/browser/ui/omnibox/omnibox_edit_controller.h"
20 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
21 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
22 #include "chrome/browser/ui/view_ids.h"
23 #include "chrome/browser/ui/views/location_bar/location_bar_view.h"
24 #include "chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h"
25 #include "chrome/browser/ui/views/settings_api_bubble_helper_views.h"
26 #include "chrome/grit/generated_resources.h"
27 #include "components/bookmarks/browser/bookmark_node_data.h"
28 #include "components/omnibox/browser/autocomplete_input.h"
29 #include "components/omnibox/browser/autocomplete_match.h"
30 #include "components/omnibox/browser/omnibox_field_trial.h"
31 #include "content/public/browser/web_contents.h"
32 #include "extensions/common/constants.h"
33 #include "net/base/escape.h"
34 #include "third_party/skia/include/core/SkColor.h"
35 #include "ui/accessibility/ax_view_state.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/input_method.h"
40 #include "ui/base/ime/text_input_client.h"
41 #include "ui/base/ime/text_input_type.h"
42 #include "ui/base/l10n/l10n_util.h"
43 #include "ui/base/models/simple_menu_model.h"
44 #include "ui/compositor/layer.h"
45 #include "ui/events/event.h"
46 #include "ui/gfx/canvas.h"
47 #include "ui/gfx/font_list.h"
48 #include "ui/gfx/selection_model.h"
49 #include "ui/strings/grit/ui_strings.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/layout/fill_layout.h"
54 #include "ui/views/widget/widget.h"
58 #include "chrome/browser/browser_process.h"
61 using bookmarks::BookmarkNodeData
;
65 // OmniboxState ---------------------------------------------------------------
67 // Stores omnibox state for each tab.
68 struct OmniboxState
: public base::SupportsUserData::Data
{
69 static const char kKey
[];
71 OmniboxState(const OmniboxEditModel::State
& model_state
,
72 const gfx::Range
& selection
,
73 const gfx::Range
& saved_selection_for_focus_change
);
74 ~OmniboxState() override
;
76 const OmniboxEditModel::State model_state
;
78 // We store both the actual selection and any saved selection (for when the
79 // omnibox is not focused). This allows us to properly handle cases like
80 // selecting text, tabbing out of the omnibox, switching tabs away and back,
81 // and tabbing back into the omnibox.
82 const gfx::Range selection
;
83 const gfx::Range saved_selection_for_focus_change
;
87 const char OmniboxState::kKey
[] = "OmniboxState";
89 OmniboxState::OmniboxState(const OmniboxEditModel::State
& model_state
,
90 const gfx::Range
& selection
,
91 const gfx::Range
& saved_selection_for_focus_change
)
92 : model_state(model_state
),
94 saved_selection_for_focus_change(saved_selection_for_focus_change
) {
97 OmniboxState::~OmniboxState() {
101 // Helpers --------------------------------------------------------------------
103 // We'd like to set the text input type to TEXT_INPUT_TYPE_URL, because this
104 // triggers URL-specific layout in software keyboards, e.g. adding top-level "/"
105 // and ".com" keys for English. However, this also causes IMEs to default to
106 // Latin character mode, which makes entering search queries difficult for IME
107 // users. Therefore, we try to guess whether an IME will be used based on the
108 // application language, and set the input type accordingly.
109 ui::TextInputType
DetermineTextInputType() {
111 DCHECK(g_browser_process
);
112 const std::string
& locale
= g_browser_process
->GetApplicationLocale();
113 const std::string
& language
= locale
.substr(0, 2);
114 // Assume CJK + Thai users are using an IME.
115 if (language
== "ja" ||
119 return ui::TEXT_INPUT_TYPE_SEARCH
;
121 return ui::TEXT_INPUT_TYPE_URL
;
127 // OmniboxViewViews -----------------------------------------------------------
130 const char OmniboxViewViews::kViewClassName
[] = "OmniboxViewViews";
132 OmniboxViewViews::OmniboxViewViews(OmniboxEditController
* controller
,
134 CommandUpdater
* command_updater
,
135 bool popup_window_mode
,
136 LocationBarView
* location_bar
,
137 const gfx::FontList
& font_list
)
138 : OmniboxView(profile
,
140 make_scoped_ptr(new ChromeOmniboxClient(controller
, profile
)),
142 popup_window_mode_(popup_window_mode
),
143 security_level_(connection_security::NONE
),
144 saved_selection_for_focus_change_(gfx::Range::InvalidRange()),
145 ime_composing_before_change_(false),
146 delete_at_end_pressed_(false),
147 location_bar_view_(location_bar
),
148 ime_candidate_window_open_(false),
149 select_all_on_mouse_release_(false),
150 select_all_on_gesture_tap_(false),
151 weak_ptr_factory_(this) {
152 SetBorder(views::Border::NullBorder());
153 set_id(VIEW_ID_OMNIBOX
);
154 SetFontList(font_list
);
157 OmniboxViewViews::~OmniboxViewViews() {
158 #if defined(OS_CHROMEOS)
159 chromeos::input_method::InputMethodManager::Get()->
160 RemoveCandidateWindowObserver(this);
163 // Explicitly teardown members which have a reference to us. Just to be safe
164 // we want them to be destroyed before destroying any other internal state.
168 void OmniboxViewViews::Init() {
169 set_controller(this);
170 SetTextInputType(DetermineTextInputType());
172 if (popup_window_mode_
)
175 if (location_bar_view_
) {
176 // Initialize the popup view using the same font.
177 popup_view_
.reset(OmniboxPopupContentsView::Create(
178 GetFontList(), this, model(), location_bar_view_
));
181 #if defined(OS_CHROMEOS)
182 chromeos::input_method::InputMethodManager::Get()->
183 AddCandidateWindowObserver(this);
187 void OmniboxViewViews::SaveStateToTab(content::WebContents
* tab
) {
190 // We don't want to keep the IME status, so force quit the current
191 // session here. It may affect the selection status, so order is
193 if (IsIMEComposing()) {
194 ConfirmCompositionText();
195 GetInputMethod()->CancelComposition(this);
198 // NOTE: GetStateForTabSwitch() may affect GetSelectedRange(), so order is
200 OmniboxEditModel::State state
= model()->GetStateForTabSwitch();
201 tab
->SetUserData(OmniboxState::kKey
, new OmniboxState(
202 state
, GetSelectedRange(), saved_selection_for_focus_change_
));
205 void OmniboxViewViews::OnTabChanged(const content::WebContents
* web_contents
) {
206 security_level_
= controller()->GetToolbarModel()->GetSecurityLevel(false);
208 const OmniboxState
* state
= static_cast<OmniboxState
*>(
209 web_contents
->GetUserData(&OmniboxState::kKey
));
210 model()->RestoreState(state
? &state
->model_state
: NULL
);
212 // This assumes that the omnibox has already been focused or blurred as
213 // appropriate; otherwise, a subsequent OnFocus() or OnBlur() call could
214 // goof up the selection. See comments at the end of
215 // BrowserView::ActiveTabChanged().
216 SelectRange(state
->selection
);
217 saved_selection_for_focus_change_
= state
->saved_selection_for_focus_change
;
220 // TODO(msw|oshima): Consider saving/restoring edit history.
224 void OmniboxViewViews::ResetTabState(content::WebContents
* web_contents
) {
225 web_contents
->SetUserData(OmniboxState::kKey
, nullptr);
228 void OmniboxViewViews::Update() {
229 const connection_security::SecurityLevel old_security_level
= security_level_
;
230 security_level_
= controller()->GetToolbarModel()->GetSecurityLevel(false);
231 if (model()->UpdatePermanentText()) {
232 // Something visibly changed. Re-enable URL replacement.
233 controller()->GetToolbarModel()->set_url_replacement_enabled(true);
234 model()->UpdatePermanentText();
236 // Select all the new text if the user had all the old text selected, or if
237 // there was no previous text (for new tab page URL replacement extensions).
238 // This makes one particular case better: the user clicks in the box to
239 // change it right before the permanent URL is changed. Since the new URL
240 // is still fully selected, the user's typing will replace the edit contents
241 // as they'd intended.
242 const bool was_select_all
= IsSelectAll();
243 const bool was_reversed
= GetSelectedRange().is_reversed();
247 // Only select all when we have focus. If we don't have focus, selecting
248 // all is unnecessary since the selection will change on regaining focus,
249 // and can in fact cause artifacts, e.g. if the user is on the NTP and
250 // clicks a link to navigate, causing |was_select_all| to be vacuously true
251 // for the empty omnibox, and we then select all here, leading to the
252 // trailing portion of a long URL being scrolled into view. We could try
253 // and address cases like this, but it seems better to just not muck with
254 // things when the omnibox isn't focused to begin with.
255 if (was_select_all
&& model()->has_focus())
256 SelectAll(was_reversed
);
257 } else if (old_security_level
!= security_level_
) {
258 EmphasizeURLComponents();
262 base::string16
OmniboxViewViews::GetText() const {
263 // TODO(oshima): IME support
267 void OmniboxViewViews::SetUserText(const base::string16
& text
,
268 const base::string16
& display_text
,
270 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
271 OmniboxView::SetUserText(text
, display_text
, update_popup
);
274 void OmniboxViewViews::SetForcedQuery() {
275 const base::string16
current_text(text());
276 const size_t start
= current_text
.find_first_not_of(base::kWhitespaceUTF16
);
277 if (start
== base::string16::npos
|| (current_text
[start
] != '?'))
278 OmniboxView::SetUserText(base::ASCIIToUTF16("?"));
280 SelectRange(gfx::Range(current_text
.size(), start
+ 1));
283 void OmniboxViewViews::GetSelectionBounds(
284 base::string16::size_type
* start
,
285 base::string16::size_type
* end
) const {
286 const gfx::Range range
= GetSelectedRange();
287 *start
= static_cast<size_t>(range
.start());
288 *end
= static_cast<size_t>(range
.end());
291 void OmniboxViewViews::SelectAll(bool reversed
) {
292 views::Textfield::SelectAll(reversed
);
295 void OmniboxViewViews::RevertAll() {
296 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
297 OmniboxView::RevertAll();
300 void OmniboxViewViews::SetFocus() {
302 // Restore caret visibility if focus is explicitly requested. This is
303 // necessary because if we already have invisible focus, the RequestFocus()
304 // call above will short-circuit, preventing us from reaching
305 // OmniboxEditModel::OnSetFocus(), which handles restoring visibility when the
306 // omnibox regains focus after losing focus.
307 model()->SetCaretVisibility(true);
310 int OmniboxViewViews::GetTextWidth() const {
311 // Returns the width necessary to display the current text, including any
312 // necessary space for the cursor or border/margin.
313 return GetRenderText()->GetContentWidth() + GetInsets().width();
316 bool OmniboxViewViews::IsImeComposing() const {
317 return IsIMEComposing();
320 gfx::Size
OmniboxViewViews::GetMinimumSize() const {
321 const int kMinCharacters
= 10;
323 GetFontList().GetExpectedTextWidth(kMinCharacters
) + GetInsets().width(),
324 GetPreferredSize().height());
327 void OmniboxViewViews::OnNativeThemeChanged(const ui::NativeTheme
* theme
) {
328 views::Textfield::OnNativeThemeChanged(theme
);
329 if (location_bar_view_
) {
330 SetBackgroundColor(location_bar_view_
->GetColor(
331 connection_security::NONE
, LocationBarView::BACKGROUND
));
333 EmphasizeURLComponents();
336 void OmniboxViewViews::OnPaint(gfx::Canvas
* canvas
) {
337 Textfield::OnPaint(canvas
);
338 if (!insert_char_time_
.is_null()) {
339 UMA_HISTOGRAM_TIMES("Omnibox.CharTypedToRepaintLatency",
340 base::TimeTicks::Now() - insert_char_time_
);
341 insert_char_time_
= base::TimeTicks();
345 void OmniboxViewViews::ExecuteCommand(int command_id
, int event_flags
) {
346 // In the base class, touch text selection is deactivated when a command is
347 // executed. Since we are not always calling the base class implementation
348 // here, we need to deactivate touch text selection here, too.
349 DestroyTouchSelection();
350 switch (command_id
) {
351 // These commands don't invoke the popup via OnBefore/AfterPossibleChange().
352 case IDS_PASTE_AND_GO
:
353 model()->PasteAndGo(GetClipboardText());
356 controller()->ShowURL();
358 case IDC_EDIT_SEARCH_ENGINES
:
359 command_updater()->ExecuteCommand(command_id
);
363 model()->OnUpOrDownKeyPressed(command_id
== IDS_MOVE_DOWN
? 1 : -1);
366 // These commands do invoke the popup.
371 if (Textfield::IsCommandIdEnabled(command_id
)) {
372 // The Textfield code will invoke OnBefore/AfterPossibleChange() itself
374 Textfield::ExecuteCommand(command_id
, event_flags
);
377 OnBeforePossibleChange();
378 command_updater()->ExecuteCommand(command_id
);
379 OnAfterPossibleChange();
384 void OmniboxViewViews::SetTextAndSelectedRange(const base::string16
& text
,
385 const gfx::Range
& range
) {
390 base::string16
OmniboxViewViews::GetSelectedText() const {
391 // TODO(oshima): Support IME.
392 return views::Textfield::GetSelectedText();
395 void OmniboxViewViews::OnPaste() {
396 const base::string16
text(GetClipboardText());
398 OnBeforePossibleChange();
399 // Record this paste, so we can do different behavior.
401 // Force a Paste operation to trigger the text_changed code in
402 // OnAfterPossibleChange(), even if identical contents are pasted.
403 text_before_change_
.clear();
404 InsertOrReplaceText(text
);
405 OnAfterPossibleChange();
409 bool OmniboxViewViews::HandleEarlyTabActions(const ui::KeyEvent
& event
) {
410 // This must run before accelerator handling invokes a focus change on tab.
411 // Note the parallel with SkipDefaultKeyEventProcessing above.
412 if (!views::FocusManager::IsTabTraversalKeyEvent(event
))
415 if (model()->is_keyword_hint() && !event
.IsShiftDown())
416 return model()->AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_TAB
);
418 if (!model()->popup_model()->IsOpen())
421 if (event
.IsShiftDown() &&
422 (model()->popup_model()->selected_line_state() ==
423 OmniboxPopupModel::KEYWORD
))
424 model()->ClearKeyword();
426 model()->OnUpOrDownKeyPressed(event
.IsShiftDown() ? -1 : 1);
431 void OmniboxViewViews::AccessibilitySetValue(const base::string16
& new_value
) {
432 SetUserText(new_value
, new_value
, true);
435 void OmniboxViewViews::SetWindowTextAndCaretPos(const base::string16
& text
,
438 bool notify_text_changed
) {
439 const gfx::Range
range(caret_pos
, caret_pos
);
440 SetTextAndSelectedRange(text
, range
);
445 if (notify_text_changed
)
449 bool OmniboxViewViews::IsSelectAll() const {
450 // TODO(oshima): IME support.
451 return text() == GetSelectedText();
454 bool OmniboxViewViews::DeleteAtEndPressed() {
455 return delete_at_end_pressed_
;
458 void OmniboxViewViews::UpdatePopup() {
459 model()->SetInputInProgress(true);
460 if (!model()->has_focus())
463 // Prevent inline autocomplete when the caret isn't at the end of the text.
464 const gfx::Range sel
= GetSelectedRange();
465 model()->StartAutocomplete(!sel
.is_empty(), sel
.GetMax() < text().length(),
469 void OmniboxViewViews::ApplyCaretVisibility() {
470 SetCursorEnabled(model()->is_caret_visible());
473 void OmniboxViewViews::OnTemporaryTextMaybeChanged(
474 const base::string16
& display_text
,
475 bool save_original_selection
,
476 bool notify_text_changed
) {
477 if (save_original_selection
)
478 saved_temporary_selection_
= GetSelectedRange();
480 SetWindowTextAndCaretPos(display_text
, display_text
.length(), false,
481 notify_text_changed
);
484 bool OmniboxViewViews::OnInlineAutocompleteTextMaybeChanged(
485 const base::string16
& display_text
,
486 size_t user_text_length
) {
487 if (display_text
== text())
490 if (!IsIMEComposing()) {
491 gfx::Range
range(display_text
.size(), user_text_length
);
492 SetTextAndSelectedRange(display_text
, range
);
493 } else if (location_bar_view_
) {
494 location_bar_view_
->SetImeInlineAutocompletion(
495 display_text
.substr(user_text_length
));
501 void OmniboxViewViews::OnInlineAutocompleteTextCleared() {
502 // Hide the inline autocompletion for IME users.
503 if (location_bar_view_
)
504 location_bar_view_
->SetImeInlineAutocompletion(base::string16());
507 void OmniboxViewViews::OnRevertTemporaryText() {
508 SelectRange(saved_temporary_selection_
);
509 // We got here because the user hit the Escape key. We explicitly don't call
510 // TextChanged(), since OmniboxPopupModel::ResetToDefaultMatch() has already
511 // been called by now, and it would've called TextChanged() if it was
515 void OmniboxViewViews::OnBeforePossibleChange() {
517 text_before_change_
= text();
518 sel_before_change_
= GetSelectedRange();
519 ime_composing_before_change_
= IsIMEComposing();
522 bool OmniboxViewViews::OnAfterPossibleChange() {
523 // See if the text or selection have changed since OnBeforePossibleChange().
524 const base::string16 new_text
= text();
525 const gfx::Range new_sel
= GetSelectedRange();
526 const bool text_changed
= (new_text
!= text_before_change_
) ||
527 (ime_composing_before_change_
!= IsIMEComposing());
528 const bool selection_differs
=
529 !((sel_before_change_
.is_empty() && new_sel
.is_empty()) ||
530 sel_before_change_
.EqualsIgnoringDirection(new_sel
));
532 // When the user has deleted text, we don't allow inline autocomplete. Make
533 // sure to not flag cases like selecting part of the text and then pasting
534 // (or typing) the prefix of that selection. (We detect these by making
535 // sure the caret, which should be after any insertion, hasn't moved
536 // forward of the old selection start.)
537 const bool just_deleted_text
=
538 (text_before_change_
.length() > new_text
.length()) &&
539 (new_sel
.start() <= sel_before_change_
.GetMin());
541 const bool something_changed
= model()->OnAfterPossibleChange(
542 text_before_change_
, new_text
, new_sel
.start(), new_sel
.end(),
543 selection_differs
, text_changed
, just_deleted_text
, !IsIMEComposing());
545 // If only selection was changed, we don't need to call model()'s
546 // OnChanged() method, which is called in TextChanged().
547 // But we still need to call EmphasizeURLComponents() to make sure the text
548 // attributes are updated correctly.
549 if (something_changed
&& text_changed
)
551 else if (selection_differs
)
552 EmphasizeURLComponents();
553 else if (delete_at_end_pressed_
)
554 model()->OnChanged();
556 return something_changed
;
559 gfx::NativeView
OmniboxViewViews::GetNativeView() const {
560 return GetWidget()->GetNativeView();
563 gfx::NativeView
OmniboxViewViews::GetRelativeWindowForPopup() const {
564 return GetWidget()->GetTopLevelWidget()->GetNativeView();
567 void OmniboxViewViews::SetGrayTextAutocompletion(const base::string16
& input
) {
568 if (location_bar_view_
)
569 location_bar_view_
->SetGrayTextAutocompletion(input
);
572 base::string16
OmniboxViewViews::GetGrayTextAutocompletion() const {
573 return location_bar_view_
?
574 location_bar_view_
->GetGrayTextAutocompletion() : base::string16();
577 int OmniboxViewViews::GetWidth() const {
578 return location_bar_view_
? location_bar_view_
->width() : 0;
581 bool OmniboxViewViews::IsImeShowingPopup() const {
582 #if defined(OS_CHROMEOS)
583 return ime_candidate_window_open_
;
585 return GetInputMethod() ? GetInputMethod()->IsCandidatePopupOpen() : false;
589 void OmniboxViewViews::ShowImeIfNeeded() {
590 GetInputMethod()->ShowImeIfNeeded();
593 void OmniboxViewViews::OnMatchOpened(const AutocompleteMatch
& match
) {
594 extensions::MaybeShowExtensionControlledSearchNotification(
595 profile(), location_bar_view_
->GetWebContents(), match
);
598 int OmniboxViewViews::GetOmniboxTextLength() const {
599 // TODO(oshima): Support IME.
600 return static_cast<int>(text().length());
603 void OmniboxViewViews::EmphasizeURLComponents() {
604 if (!location_bar_view_
)
607 // If the current contents is a URL, force left-to-right rendering at the
608 // paragraph level. Right-to-left runs are still rendered RTL, but will not
609 // flip the whole URL around. For example (if "ABC" is Hebrew), this will
610 // render "ABC.com" as "CBA.com", rather than "com.CBA".
611 bool text_is_url
= model()->CurrentTextIsURL();
612 GetRenderText()->SetDirectionalityMode(text_is_url
613 ? gfx::DIRECTIONALITY_FORCE_LTR
614 : gfx::DIRECTIONALITY_FROM_TEXT
);
616 // See whether the contents are a URL with a non-empty host portion, which we
617 // should emphasize. To check for a URL, rather than using the type returned
618 // by Parse(), ask the model, which will check the desired page transition for
619 // this input. This can tell us whether an UNKNOWN input string is going to
620 // be treated as a search or a navigation, and is the same method the Paste
621 // And Go system uses.
622 url::Component scheme
, host
;
623 AutocompleteInput::ParseForEmphasizeComponents(
624 text(), ChromeAutocompleteSchemeClassifier(profile()), &scheme
, &host
);
625 bool grey_out_url
= text().substr(scheme
.begin
, scheme
.len
) ==
626 base::UTF8ToUTF16(extensions::kExtensionScheme
);
627 bool grey_base
= text_is_url
&& (host
.is_nonempty() || grey_out_url
);
628 SetColor(location_bar_view_
->GetColor(
630 grey_base
? LocationBarView::DEEMPHASIZED_TEXT
: LocationBarView::TEXT
));
631 if (grey_base
&& !grey_out_url
) {
633 location_bar_view_
->GetColor(security_level_
, LocationBarView::TEXT
),
634 gfx::Range(host
.begin
, host
.end()));
637 // Emphasize the scheme for security UI display purposes (if necessary).
638 // Note that we check CurrentTextIsURL() because if we're replacing search
639 // URLs with search terms, we may have a non-URL even when the user is not
640 // editing; and in some cases, e.g. for "site:foo.com" searches, the parser
641 // may have incorrectly identified a qualifier as a scheme.
642 SetStyle(gfx::DIAGONAL_STRIKE
, false);
643 if (!model()->user_input_in_progress() && text_is_url
&&
644 scheme
.is_nonempty() && (security_level_
!= connection_security::NONE
)) {
645 SkColor security_color
= location_bar_view_
->GetColor(
646 security_level_
, LocationBarView::SECURITY_TEXT
);
648 (security_level_
== connection_security::SECURITY_ERROR
);
649 const gfx::Range
scheme_range(scheme
.begin
, scheme
.end());
650 ApplyColor(security_color
, scheme_range
);
651 ApplyStyle(gfx::DIAGONAL_STRIKE
, strike
, scheme_range
);
655 bool OmniboxViewViews::OnKeyReleased(const ui::KeyEvent
& event
) {
656 // The omnibox contents may change while the control key is pressed.
657 if (event
.key_code() == ui::VKEY_CONTROL
)
658 model()->OnControlKeyChanged(false);
659 return views::Textfield::OnKeyReleased(event
);
662 bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id
) const {
663 return command_id
== IDS_PASTE_AND_GO
;
666 base::string16
OmniboxViewViews::GetLabelForCommandId(int command_id
) const {
667 DCHECK_EQ(IDS_PASTE_AND_GO
, command_id
);
668 return l10n_util::GetStringUTF16(
669 model()->IsPasteAndSearch(GetClipboardText()) ?
670 IDS_PASTE_AND_SEARCH
: IDS_PASTE_AND_GO
);
673 const char* OmniboxViewViews::GetClassName() const {
674 return kViewClassName
;
677 bool OmniboxViewViews::OnMousePressed(const ui::MouseEvent
& event
) {
678 select_all_on_mouse_release_
=
679 (event
.IsOnlyLeftMouseButton() || event
.IsOnlyRightMouseButton()) &&
680 (!HasFocus() || (model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE
));
681 if (select_all_on_mouse_release_
) {
682 // Restore caret visibility whenever the user clicks in the omnibox in a way
683 // that would give it focus. We must handle this case separately here
684 // because if the omnibox currently has invisible focus, the mouse event
685 // won't trigger either SetFocus() or OmniboxEditModel::OnSetFocus().
686 model()->SetCaretVisibility(true);
688 // When we're going to select all on mouse release, invalidate any saved
689 // selection lest restoring it fights with the "select all" action. It's
690 // possible to later set select_all_on_mouse_release_ back to false, but
691 // that happens for things like dragging, which are cases where having
692 // invalidated this saved selection is still OK.
693 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
695 return views::Textfield::OnMousePressed(event
);
698 bool OmniboxViewViews::OnMouseDragged(const ui::MouseEvent
& event
) {
699 if (ExceededDragThreshold(event
.location() - last_click_location()))
700 select_all_on_mouse_release_
= false;
702 if (HasTextBeingDragged())
705 return views::Textfield::OnMouseDragged(event
);
708 void OmniboxViewViews::OnMouseReleased(const ui::MouseEvent
& event
) {
709 views::Textfield::OnMouseReleased(event
);
710 if (event
.IsOnlyLeftMouseButton() || event
.IsOnlyRightMouseButton()) {
711 // When the user has clicked and released to give us focus, select all
712 // unless we're omitting the URL (in which case refining an existing query
713 // is common enough that we do click-to-place-cursor).
714 if (select_all_on_mouse_release_
&&
715 !controller()->GetToolbarModel()->WouldReplaceURL()) {
716 // Select all in the reverse direction so as not to scroll the caret
717 // into view and shift the contents jarringly.
721 select_all_on_mouse_release_
= false;
724 bool OmniboxViewViews::OnKeyPressed(const ui::KeyEvent
& event
) {
725 // Skip processing of [Alt]+<num-pad digit> Unicode alt key codes.
726 // Otherwise, if num-lock is off, the events are handled as [Up], [Down], etc.
727 if (event
.IsUnicodeKeyCode())
728 return views::Textfield::OnKeyPressed(event
);
730 const bool shift
= event
.IsShiftDown();
731 const bool control
= event
.IsControlDown();
732 const bool alt
= event
.IsAltDown() || event
.IsAltGrDown();
733 switch (event
.key_code()) {
734 case ui::VKEY_RETURN
:
735 model()->AcceptInput(alt
? NEW_FOREGROUND_TAB
: CURRENT_TAB
, false);
737 case ui::VKEY_ESCAPE
:
738 return model()->OnEscapeKeyPressed();
739 case ui::VKEY_CONTROL
:
740 model()->OnControlKeyChanged(true);
742 case ui::VKEY_DELETE
:
743 if (shift
&& model()->popup_model()->IsOpen())
744 model()->popup_model()->TryDeletingCurrentItem();
748 model()->OnUpOrDownKeyPressed(-1);
754 model()->OnUpOrDownKeyPressed(1);
759 if (control
|| alt
|| shift
)
761 model()->OnUpOrDownKeyPressed(-1 * model()->result().size());
764 if (control
|| alt
|| shift
)
766 model()->OnUpOrDownKeyPressed(model()->result().size());
769 if (control
&& !alt
&& !read_only()) {
770 ExecuteCommand(IDS_APP_PASTE
, 0);
774 case ui::VKEY_INSERT
:
775 if (shift
&& !control
&& !read_only()) {
776 ExecuteCommand(IDS_APP_PASTE
, 0);
784 return views::Textfield::OnKeyPressed(event
) || HandleEarlyTabActions(event
);
787 void OmniboxViewViews::OnGestureEvent(ui::GestureEvent
* event
) {
788 if (!HasFocus() && event
->type() == ui::ET_GESTURE_TAP_DOWN
) {
789 select_all_on_gesture_tap_
= true;
791 // If we're trying to select all on tap, invalidate any saved selection lest
792 // restoring it fights with the "select all" action.
793 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
796 views::Textfield::OnGestureEvent(event
);
798 if (select_all_on_gesture_tap_
&& event
->type() == ui::ET_GESTURE_TAP
)
801 if (event
->type() == ui::ET_GESTURE_TAP
||
802 event
->type() == ui::ET_GESTURE_TAP_CANCEL
||
803 event
->type() == ui::ET_GESTURE_TWO_FINGER_TAP
||
804 event
->type() == ui::ET_GESTURE_SCROLL_BEGIN
||
805 event
->type() == ui::ET_GESTURE_PINCH_BEGIN
||
806 event
->type() == ui::ET_GESTURE_LONG_PRESS
||
807 event
->type() == ui::ET_GESTURE_LONG_TAP
) {
808 select_all_on_gesture_tap_
= false;
812 void OmniboxViewViews::AboutToRequestFocusFromTabTraversal(bool reverse
) {
813 views::Textfield::AboutToRequestFocusFromTabTraversal(reverse
);
816 bool OmniboxViewViews::SkipDefaultKeyEventProcessing(
817 const ui::KeyEvent
& event
) {
818 if (views::FocusManager::IsTabTraversalKeyEvent(event
) &&
819 ((model()->is_keyword_hint() && !event
.IsShiftDown()) ||
820 model()->popup_model()->IsOpen())) {
823 if (event
.key_code() == ui::VKEY_ESCAPE
)
824 return model()->WillHandleEscapeKey();
825 return Textfield::SkipDefaultKeyEventProcessing(event
);
828 void OmniboxViewViews::GetAccessibleState(ui::AXViewState
* state
) {
829 state
->role
= ui::AX_ROLE_TEXT_FIELD
;
830 state
->name
= l10n_util::GetStringUTF16(IDS_ACCNAME_LOCATION
);
831 state
->value
= GetText();
833 base::string16::size_type entry_start
;
834 base::string16::size_type entry_end
;
835 GetSelectionBounds(&entry_start
, &entry_end
);
836 state
->selection_start
= entry_start
;
837 state
->selection_end
= entry_end
;
839 if (popup_window_mode_
) {
840 state
->AddStateFlag(ui::AX_STATE_READ_ONLY
);
842 state
->set_value_callback
=
843 base::Bind(&OmniboxViewViews::AccessibilitySetValue
,
844 weak_ptr_factory_
.GetWeakPtr());
848 void OmniboxViewViews::OnFocus() {
849 views::Textfield::OnFocus();
850 // TODO(oshima): Get control key state.
851 model()->OnSetFocus(false);
852 // Don't call controller()->OnSetFocus, this view has already acquired focus.
854 // Restore the selection we saved in OnBlur() if it's still valid.
855 if (saved_selection_for_focus_change_
.IsValid()) {
856 SelectRange(saved_selection_for_focus_change_
);
857 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
861 void OmniboxViewViews::OnBlur() {
862 // Save the user's existing selection to restore it later.
863 saved_selection_for_focus_change_
= GetSelectedRange();
865 views::Textfield::OnBlur();
866 model()->OnWillKillFocus();
868 // If ZeroSuggest is active, we may have refused to show an update to the
869 // underlying permanent URL that happened while the popup was open, so
870 // revert to ensure that update is shown now. Otherwise, make sure to call
871 // CloseOmniboxPopup() unconditionally, so that if ZeroSuggest is in the midst
872 // of running but hasn't yet opened the popup, it will be halted.
873 if (!model()->user_input_in_progress() && model()->popup_model()->IsOpen())
878 // Tell the model to reset itself.
879 model()->OnKillFocus();
881 // Make sure the beginning of the text is visible.
882 SelectRange(gfx::Range(0));
885 bool OmniboxViewViews::IsCommandIdEnabled(int command_id
) const {
886 if (command_id
== IDS_APP_PASTE
)
887 return !read_only() && !GetClipboardText().empty();
888 if (command_id
== IDS_PASTE_AND_GO
)
889 return !read_only() && model()->CanPasteAndGo(GetClipboardText());
890 if (command_id
== IDS_SHOW_URL
)
891 return controller()->GetToolbarModel()->WouldReplaceURL();
892 return command_id
== IDS_MOVE_DOWN
|| command_id
== IDS_MOVE_UP
||
893 Textfield::IsCommandIdEnabled(command_id
) ||
894 command_updater()->IsCommandEnabled(command_id
);
897 base::string16
OmniboxViewViews::GetSelectionClipboardText() const {
898 return SanitizeTextForPaste(Textfield::GetSelectionClipboardText());
901 void OmniboxViewViews::DoInsertChar(base::char16 ch
) {
902 // If |insert_char_time_| is not null, there's a pending insert char operation
903 // that hasn't been painted yet. Keep the earlier time.
904 if (insert_char_time_
.is_null())
905 insert_char_time_
= base::TimeTicks::Now();
906 Textfield::DoInsertChar(ch
);
909 #if defined(OS_CHROMEOS)
910 void OmniboxViewViews::CandidateWindowOpened(
911 chromeos::input_method::InputMethodManager
* manager
) {
912 ime_candidate_window_open_
= true;
915 void OmniboxViewViews::CandidateWindowClosed(
916 chromeos::input_method::InputMethodManager
* manager
) {
917 ime_candidate_window_open_
= false;
921 void OmniboxViewViews::ContentsChanged(views::Textfield
* sender
,
922 const base::string16
& new_contents
) {
925 bool OmniboxViewViews::HandleKeyEvent(views::Textfield
* textfield
,
926 const ui::KeyEvent
& event
) {
927 delete_at_end_pressed_
= false;
929 if (event
.key_code() == ui::VKEY_BACK
) {
930 // No extra handling is needed in keyword search mode, if there is a
931 // non-empty selection, or if the cursor is not leading the text.
932 if (model()->is_keyword_hint() || model()->keyword().empty() ||
933 HasSelection() || GetCursorPosition() != 0)
935 model()->ClearKeyword();
939 if (event
.key_code() == ui::VKEY_DELETE
&& !event
.IsAltDown()) {
940 delete_at_end_pressed_
=
941 (!HasSelection() && GetCursorPosition() == text().length());
944 // Handle the right-arrow key for LTR text and the left-arrow key for RTL text
945 // if there is gray text that needs to be committed.
946 if (GetCursorPosition() == text().length()) {
947 base::i18n::TextDirection direction
= GetTextDirection();
948 if ((direction
== base::i18n::LEFT_TO_RIGHT
&&
949 event
.key_code() == ui::VKEY_RIGHT
) ||
950 (direction
== base::i18n::RIGHT_TO_LEFT
&&
951 event
.key_code() == ui::VKEY_LEFT
)) {
952 return model()->CommitSuggestedText();
959 void OmniboxViewViews::OnBeforeUserAction(views::Textfield
* sender
) {
960 OnBeforePossibleChange();
963 void OmniboxViewViews::OnAfterUserAction(views::Textfield
* sender
) {
964 OnAfterPossibleChange();
967 void OmniboxViewViews::OnAfterCutOrCopy(ui::ClipboardType clipboard_type
) {
968 ui::Clipboard
* cb
= ui::Clipboard::GetForCurrentThread();
969 base::string16 selected_text
;
970 cb
->ReadText(clipboard_type
, &selected_text
);
973 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
974 &selected_text
, &url
, &write_url
);
976 UMA_HISTOGRAM_COUNTS(OmniboxEditModel::kCutOrCopyAllTextHistogram
, 1);
979 BookmarkNodeData data
;
980 data
.ReadFromTuple(url
, selected_text
);
981 data
.WriteToClipboard(clipboard_type
);
983 ui::ScopedClipboardWriter
scoped_clipboard_writer(clipboard_type
);
984 scoped_clipboard_writer
.WriteText(selected_text
);
988 void OmniboxViewViews::OnWriteDragData(ui::OSExchangeData
* data
) {
991 bool is_all_selected
= IsSelectAll();
992 base::string16 selected_text
= GetSelectedText();
993 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), is_all_selected
,
994 &selected_text
, &url
, &write_url
);
995 data
->SetString(selected_text
);
998 base::string16 title
= selected_text
;
1000 model()->GetDataForURLExport(&url
, &title
, &favicon
);
1001 button_drag_utils::SetURLAndDragImage(url
, title
, favicon
.AsImageSkia(),
1002 NULL
, data
, GetWidget());
1003 data
->SetURL(url
, title
);
1007 void OmniboxViewViews::OnGetDragOperationsForTextfield(int* drag_operations
) {
1008 base::string16 selected_text
= GetSelectedText();
1011 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
1012 &selected_text
, &url
, &write_url
);
1014 *drag_operations
|= ui::DragDropTypes::DRAG_LINK
;
1017 void OmniboxViewViews::AppendDropFormats(
1019 std::set
<ui::OSExchangeData::CustomFormat
>* custom_formats
) {
1020 *formats
= *formats
| ui::OSExchangeData::URL
;
1023 int OmniboxViewViews::OnDrop(const ui::OSExchangeData
& data
) {
1024 if (HasTextBeingDragged())
1025 return ui::DragDropTypes::DRAG_NONE
;
1027 if (data
.HasURL(ui::OSExchangeData::CONVERT_FILENAMES
)) {
1029 base::string16 title
;
1030 if (data
.GetURLAndTitle(
1031 ui::OSExchangeData::CONVERT_FILENAMES
, &url
, &title
)) {
1032 base::string16
text(
1033 StripJavascriptSchemas(base::UTF8ToUTF16(url
.spec())));
1034 if (model()->CanPasteAndGo(text
)) {
1035 model()->PasteAndGo(text
);
1036 return ui::DragDropTypes::DRAG_COPY
;
1039 } else if (data
.HasString()) {
1040 base::string16 text
;
1041 if (data
.GetString(&text
)) {
1042 base::string16
collapsed_text(base::CollapseWhitespace(text
, true));
1043 if (model()->CanPasteAndGo(collapsed_text
))
1044 model()->PasteAndGo(collapsed_text
);
1045 return ui::DragDropTypes::DRAG_COPY
;
1049 return ui::DragDropTypes::DRAG_NONE
;
1052 void OmniboxViewViews::UpdateContextMenu(ui::SimpleMenuModel
* menu_contents
) {
1053 int paste_position
= menu_contents
->GetIndexOfCommandId(IDS_APP_PASTE
);
1054 DCHECK_GE(paste_position
, 0);
1055 menu_contents
->InsertItemWithStringIdAt(
1056 paste_position
+ 1, IDS_PASTE_AND_GO
, IDS_PASTE_AND_GO
);
1058 menu_contents
->AddSeparator(ui::NORMAL_SEPARATOR
);
1060 if (chrome::IsQueryExtractionEnabled()) {
1061 int select_all_position
= menu_contents
->GetIndexOfCommandId(
1062 IDS_APP_SELECT_ALL
);
1063 DCHECK_GE(select_all_position
, 0);
1064 menu_contents
->InsertItemWithStringIdAt(
1065 select_all_position
+ 1, IDS_SHOW_URL
, IDS_SHOW_URL
);
1068 // Minor note: We use IDC_ for command id here while the underlying textfield
1069 // is using IDS_ for all its command ids. This is because views cannot depend
1071 menu_contents
->AddItemWithStringId(IDC_EDIT_SEARCH_ENGINES
,
1072 IDS_EDIT_SEARCH_ENGINES
);