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/clipboard_utils.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/grit/generated_resources.h"
25 #include "components/bookmarks/browser/bookmark_node_data.h"
26 #include "components/omnibox/browser/autocomplete_input.h"
27 #include "components/omnibox/browser/autocomplete_match.h"
28 #include "components/omnibox/browser/omnibox_edit_controller.h"
29 #include "components/omnibox/browser/omnibox_edit_model.h"
30 #include "components/omnibox/browser/omnibox_field_trial.h"
31 #include "components/omnibox/browser/omnibox_popup_model.h"
32 #include "components/search/search.h"
33 #include "content/public/browser/web_contents.h"
34 #include "extensions/common/constants.h"
35 #include "net/base/escape.h"
36 #include "third_party/skia/include/core/SkColor.h"
37 #include "ui/accessibility/ax_view_state.h"
38 #include "ui/base/clipboard/scoped_clipboard_writer.h"
39 #include "ui/base/dragdrop/drag_drop_types.h"
40 #include "ui/base/dragdrop/os_exchange_data.h"
41 #include "ui/base/ime/input_method.h"
42 #include "ui/base/ime/text_input_client.h"
43 #include "ui/base/ime/text_input_type.h"
44 #include "ui/base/l10n/l10n_util.h"
45 #include "ui/base/models/simple_menu_model.h"
46 #include "ui/compositor/layer.h"
47 #include "ui/events/event.h"
48 #include "ui/gfx/canvas.h"
49 #include "ui/gfx/font_list.h"
50 #include "ui/gfx/selection_model.h"
51 #include "ui/strings/grit/ui_strings.h"
52 #include "ui/views/border.h"
53 #include "ui/views/button_drag_utils.h"
54 #include "ui/views/controls/textfield/textfield.h"
55 #include "ui/views/layout/fill_layout.h"
56 #include "ui/views/widget/widget.h"
60 #include "chrome/browser/browser_process.h"
63 using bookmarks::BookmarkNodeData
;
67 // OmniboxState ---------------------------------------------------------------
69 // Stores omnibox state for each tab.
70 struct OmniboxState
: public base::SupportsUserData::Data
{
71 static const char kKey
[];
73 OmniboxState(const OmniboxEditModel::State
& model_state
,
74 const gfx::Range
& selection
,
75 const gfx::Range
& saved_selection_for_focus_change
);
76 ~OmniboxState() override
;
78 const OmniboxEditModel::State model_state
;
80 // We store both the actual selection and any saved selection (for when the
81 // omnibox is not focused). This allows us to properly handle cases like
82 // selecting text, tabbing out of the omnibox, switching tabs away and back,
83 // and tabbing back into the omnibox.
84 const gfx::Range selection
;
85 const gfx::Range saved_selection_for_focus_change
;
89 const char OmniboxState::kKey
[] = "OmniboxState";
91 OmniboxState::OmniboxState(const OmniboxEditModel::State
& model_state
,
92 const gfx::Range
& selection
,
93 const gfx::Range
& saved_selection_for_focus_change
)
94 : model_state(model_state
),
96 saved_selection_for_focus_change(saved_selection_for_focus_change
) {
99 OmniboxState::~OmniboxState() {
103 // Helpers --------------------------------------------------------------------
105 // We'd like to set the text input type to TEXT_INPUT_TYPE_URL, because this
106 // triggers URL-specific layout in software keyboards, e.g. adding top-level "/"
107 // and ".com" keys for English. However, this also causes IMEs to default to
108 // Latin character mode, which makes entering search queries difficult for IME
109 // users. Therefore, we try to guess whether an IME will be used based on the
110 // application language, and set the input type accordingly.
111 ui::TextInputType
DetermineTextInputType() {
113 DCHECK(g_browser_process
);
114 const std::string
& locale
= g_browser_process
->GetApplicationLocale();
115 const std::string
& language
= locale
.substr(0, 2);
116 // Assume CJK + Thai users are using an IME.
117 if (language
== "ja" ||
121 return ui::TEXT_INPUT_TYPE_SEARCH
;
123 return ui::TEXT_INPUT_TYPE_URL
;
129 // OmniboxViewViews -----------------------------------------------------------
132 const char OmniboxViewViews::kViewClassName
[] = "OmniboxViewViews";
134 OmniboxViewViews::OmniboxViewViews(OmniboxEditController
* controller
,
136 CommandUpdater
* command_updater
,
137 bool popup_window_mode
,
138 LocationBarView
* location_bar
,
139 const gfx::FontList
& font_list
)
142 make_scoped_ptr(new ChromeOmniboxClient(controller
, profile
))),
144 popup_window_mode_(popup_window_mode
),
145 security_level_(connection_security::NONE
),
146 saved_selection_for_focus_change_(gfx::Range::InvalidRange()),
147 ime_composing_before_change_(false),
148 delete_at_end_pressed_(false),
149 location_bar_view_(location_bar
),
150 ime_candidate_window_open_(false),
151 select_all_on_mouse_release_(false),
152 select_all_on_gesture_tap_(false),
153 weak_ptr_factory_(this) {
154 SetBorder(views::Border::NullBorder());
155 set_id(VIEW_ID_OMNIBOX
);
156 SetFontList(font_list
);
159 OmniboxViewViews::~OmniboxViewViews() {
160 #if defined(OS_CHROMEOS)
161 chromeos::input_method::InputMethodManager::Get()->
162 RemoveCandidateWindowObserver(this);
165 // Explicitly teardown members which have a reference to us. Just to be safe
166 // we want them to be destroyed before destroying any other internal state.
170 void OmniboxViewViews::Init() {
171 set_controller(this);
172 SetTextInputType(DetermineTextInputType());
174 if (popup_window_mode_
)
177 if (location_bar_view_
) {
178 // Initialize the popup view using the same font.
179 popup_view_
.reset(OmniboxPopupContentsView::Create(
180 GetFontList(), this, model(), location_bar_view_
));
183 #if defined(OS_CHROMEOS)
184 chromeos::input_method::InputMethodManager::Get()->
185 AddCandidateWindowObserver(this);
189 void OmniboxViewViews::SaveStateToTab(content::WebContents
* tab
) {
192 // We don't want to keep the IME status, so force quit the current
193 // session here. It may affect the selection status, so order is
195 if (IsIMEComposing()) {
196 ConfirmCompositionText();
197 GetInputMethod()->CancelComposition(this);
200 // NOTE: GetStateForTabSwitch() may affect GetSelectedRange(), so order is
202 OmniboxEditModel::State state
= model()->GetStateForTabSwitch();
203 tab
->SetUserData(OmniboxState::kKey
, new OmniboxState(
204 state
, GetSelectedRange(), saved_selection_for_focus_change_
));
207 void OmniboxViewViews::OnTabChanged(const content::WebContents
* web_contents
) {
208 UpdateSecurityLevel();
209 const OmniboxState
* state
= static_cast<OmniboxState
*>(
210 web_contents
->GetUserData(&OmniboxState::kKey
));
211 model()->RestoreState(state
? &state
->model_state
: NULL
);
213 // This assumes that the omnibox has already been focused or blurred as
214 // appropriate; otherwise, a subsequent OnFocus() or OnBlur() call could
215 // goof up the selection. See comments at the end of
216 // BrowserView::ActiveTabChanged().
217 SelectRange(state
->selection
);
218 saved_selection_for_focus_change_
= state
->saved_selection_for_focus_change
;
221 // TODO(msw|oshima): Consider saving/restoring edit history.
225 void OmniboxViewViews::ResetTabState(content::WebContents
* web_contents
) {
226 web_contents
->SetUserData(OmniboxState::kKey
, nullptr);
229 void OmniboxViewViews::Update() {
230 const connection_security::SecurityLevel old_security_level
= security_level_
;
231 UpdateSecurityLevel();
232 if (model()->UpdatePermanentText()) {
233 // Something visibly changed. Re-enable URL replacement.
234 controller()->GetToolbarModel()->set_url_replacement_enabled(true);
235 model()->UpdatePermanentText();
237 // Select all the new text if the user had all the old text selected, or if
238 // there was no previous text (for new tab page URL replacement extensions).
239 // This makes one particular case better: the user clicks in the box to
240 // change it right before the permanent URL is changed. Since the new URL
241 // is still fully selected, the user's typing will replace the edit contents
242 // as they'd intended.
243 const bool was_select_all
= IsSelectAll();
244 const bool was_reversed
= GetSelectedRange().is_reversed();
248 // Only select all when we have focus. If we don't have focus, selecting
249 // all is unnecessary since the selection will change on regaining focus,
250 // and can in fact cause artifacts, e.g. if the user is on the NTP and
251 // clicks a link to navigate, causing |was_select_all| to be vacuously true
252 // for the empty omnibox, and we then select all here, leading to the
253 // trailing portion of a long URL being scrolled into view. We could try
254 // and address cases like this, but it seems better to just not muck with
255 // things when the omnibox isn't focused to begin with.
256 if (was_select_all
&& model()->has_focus())
257 SelectAll(was_reversed
);
258 } else if (old_security_level
!= security_level_
) {
259 EmphasizeURLComponents();
263 base::string16
OmniboxViewViews::GetText() const {
264 // TODO(oshima): IME support
268 void OmniboxViewViews::SetUserText(const base::string16
& text
,
269 const base::string16
& display_text
,
271 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
272 OmniboxView::SetUserText(text
, display_text
, update_popup
);
275 void OmniboxViewViews::SetForcedQuery() {
276 const base::string16
current_text(text());
277 const size_t start
= current_text
.find_first_not_of(base::kWhitespaceUTF16
);
278 if (start
== base::string16::npos
|| (current_text
[start
] != '?'))
279 OmniboxView::SetUserText(base::ASCIIToUTF16("?"));
281 SelectRange(gfx::Range(current_text
.size(), start
+ 1));
284 void OmniboxViewViews::GetSelectionBounds(
285 base::string16::size_type
* start
,
286 base::string16::size_type
* end
) const {
287 const gfx::Range range
= GetSelectedRange();
288 *start
= static_cast<size_t>(range
.start());
289 *end
= static_cast<size_t>(range
.end());
292 void OmniboxViewViews::SelectAll(bool reversed
) {
293 views::Textfield::SelectAll(reversed
);
296 void OmniboxViewViews::RevertAll() {
297 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
298 OmniboxView::RevertAll();
301 void OmniboxViewViews::SetFocus() {
303 // Restore caret visibility if focus is explicitly requested. This is
304 // necessary because if we already have invisible focus, the RequestFocus()
305 // call above will short-circuit, preventing us from reaching
306 // OmniboxEditModel::OnSetFocus(), which handles restoring visibility when the
307 // omnibox regains focus after losing focus.
308 model()->SetCaretVisibility(true);
311 int OmniboxViewViews::GetTextWidth() const {
312 // Returns the width necessary to display the current text, including any
313 // necessary space for the cursor or border/margin.
314 return GetRenderText()->GetContentWidth() + GetInsets().width();
317 bool OmniboxViewViews::IsImeComposing() const {
318 return IsIMEComposing();
321 gfx::Size
OmniboxViewViews::GetMinimumSize() const {
322 const int kMinCharacters
= 10;
324 GetFontList().GetExpectedTextWidth(kMinCharacters
) + GetInsets().width(),
325 GetPreferredSize().height());
328 void OmniboxViewViews::OnNativeThemeChanged(const ui::NativeTheme
* theme
) {
329 views::Textfield::OnNativeThemeChanged(theme
);
330 if (location_bar_view_
) {
331 SetBackgroundColor(location_bar_view_
->GetColor(
332 connection_security::NONE
, LocationBarView::BACKGROUND
));
334 EmphasizeURLComponents();
337 void OmniboxViewViews::OnPaint(gfx::Canvas
* canvas
) {
338 Textfield::OnPaint(canvas
);
339 if (!insert_char_time_
.is_null()) {
340 UMA_HISTOGRAM_TIMES("Omnibox.CharTypedToRepaintLatency",
341 base::TimeTicks::Now() - insert_char_time_
);
342 insert_char_time_
= base::TimeTicks();
346 void OmniboxViewViews::ExecuteCommand(int command_id
, int event_flags
) {
347 // In the base class, touch text selection is deactivated when a command is
348 // executed. Since we are not always calling the base class implementation
349 // here, we need to deactivate touch text selection here, too.
350 DestroyTouchSelection();
351 switch (command_id
) {
352 // These commands don't invoke the popup via OnBefore/AfterPossibleChange().
353 case IDS_PASTE_AND_GO
:
354 model()->PasteAndGo(GetClipboardText());
357 controller()->ShowURL();
359 case IDC_EDIT_SEARCH_ENGINES
:
360 location_bar_view_
->command_updater()->ExecuteCommand(command_id
);
364 model()->OnUpOrDownKeyPressed(command_id
== IDS_MOVE_DOWN
? 1 : -1);
367 // These commands do invoke the popup.
372 if (Textfield::IsCommandIdEnabled(command_id
)) {
373 // The Textfield code will invoke OnBefore/AfterPossibleChange() itself
375 Textfield::ExecuteCommand(command_id
, event_flags
);
378 OnBeforePossibleChange();
379 location_bar_view_
->command_updater()->ExecuteCommand(command_id
);
380 OnAfterPossibleChange();
385 void OmniboxViewViews::SetTextAndSelectedRange(const base::string16
& text
,
386 const gfx::Range
& range
) {
391 base::string16
OmniboxViewViews::GetSelectedText() const {
392 // TODO(oshima): Support IME.
393 return views::Textfield::GetSelectedText();
396 void OmniboxViewViews::OnPaste() {
397 const base::string16
text(GetClipboardText());
399 OnBeforePossibleChange();
400 // Record this paste, so we can do different behavior.
402 // Force a Paste operation to trigger the text_changed code in
403 // OnAfterPossibleChange(), even if identical contents are pasted.
404 text_before_change_
.clear();
405 InsertOrReplaceText(text
);
406 OnAfterPossibleChange();
410 bool OmniboxViewViews::HandleEarlyTabActions(const ui::KeyEvent
& event
) {
411 // This must run before accelerator handling invokes a focus change on tab.
412 // Note the parallel with SkipDefaultKeyEventProcessing above.
413 if (!views::FocusManager::IsTabTraversalKeyEvent(event
))
416 if (model()->is_keyword_hint() && !event
.IsShiftDown())
417 return model()->AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_TAB
);
419 if (!model()->popup_model()->IsOpen())
422 if (event
.IsShiftDown() &&
423 (model()->popup_model()->selected_line_state() ==
424 OmniboxPopupModel::KEYWORD
))
425 model()->ClearKeyword();
427 model()->OnUpOrDownKeyPressed(event
.IsShiftDown() ? -1 : 1);
432 void OmniboxViewViews::AccessibilitySetValue(const base::string16
& new_value
) {
433 SetUserText(new_value
, new_value
, true);
436 void OmniboxViewViews::UpdateSecurityLevel() {
437 ChromeToolbarModel
* chrome_toolbar_model
=
438 static_cast<ChromeToolbarModel
*>(controller()->GetToolbarModel());
439 security_level_
= chrome_toolbar_model
->GetSecurityLevel(false);
442 void OmniboxViewViews::SetWindowTextAndCaretPos(const base::string16
& text
,
445 bool notify_text_changed
) {
446 const gfx::Range
range(caret_pos
, caret_pos
);
447 SetTextAndSelectedRange(text
, range
);
452 if (notify_text_changed
)
456 bool OmniboxViewViews::IsSelectAll() const {
457 // TODO(oshima): IME support.
458 return text() == GetSelectedText();
461 bool OmniboxViewViews::DeleteAtEndPressed() {
462 return delete_at_end_pressed_
;
465 void OmniboxViewViews::UpdatePopup() {
466 model()->SetInputInProgress(true);
467 if (!model()->has_focus())
470 // Prevent inline autocomplete when the caret isn't at the end of the text.
471 const gfx::Range sel
= GetSelectedRange();
472 model()->StartAutocomplete(!sel
.is_empty(), sel
.GetMax() < text().length(),
476 void OmniboxViewViews::ApplyCaretVisibility() {
477 SetCursorEnabled(model()->is_caret_visible());
480 void OmniboxViewViews::OnTemporaryTextMaybeChanged(
481 const base::string16
& display_text
,
482 bool save_original_selection
,
483 bool notify_text_changed
) {
484 if (save_original_selection
)
485 saved_temporary_selection_
= GetSelectedRange();
487 SetWindowTextAndCaretPos(display_text
, display_text
.length(), false,
488 notify_text_changed
);
491 bool OmniboxViewViews::OnInlineAutocompleteTextMaybeChanged(
492 const base::string16
& display_text
,
493 size_t user_text_length
) {
494 if (display_text
== text())
497 if (!IsIMEComposing()) {
498 gfx::Range
range(display_text
.size(), user_text_length
);
499 SetTextAndSelectedRange(display_text
, range
);
500 } else if (location_bar_view_
) {
501 location_bar_view_
->SetImeInlineAutocompletion(
502 display_text
.substr(user_text_length
));
508 void OmniboxViewViews::OnInlineAutocompleteTextCleared() {
509 // Hide the inline autocompletion for IME users.
510 if (location_bar_view_
)
511 location_bar_view_
->SetImeInlineAutocompletion(base::string16());
514 void OmniboxViewViews::OnRevertTemporaryText() {
515 SelectRange(saved_temporary_selection_
);
516 // We got here because the user hit the Escape key. We explicitly don't call
517 // TextChanged(), since OmniboxPopupModel::ResetToDefaultMatch() has already
518 // been called by now, and it would've called TextChanged() if it was
522 void OmniboxViewViews::OnBeforePossibleChange() {
524 text_before_change_
= text();
525 sel_before_change_
= GetSelectedRange();
526 ime_composing_before_change_
= IsIMEComposing();
529 bool OmniboxViewViews::OnAfterPossibleChange() {
530 // See if the text or selection have changed since OnBeforePossibleChange().
531 const base::string16 new_text
= text();
532 const gfx::Range new_sel
= GetSelectedRange();
533 const bool text_changed
= (new_text
!= text_before_change_
) ||
534 (ime_composing_before_change_
!= IsIMEComposing());
535 const bool selection_differs
=
536 !((sel_before_change_
.is_empty() && new_sel
.is_empty()) ||
537 sel_before_change_
.EqualsIgnoringDirection(new_sel
));
539 // When the user has deleted text, we don't allow inline autocomplete. Make
540 // sure to not flag cases like selecting part of the text and then pasting
541 // (or typing) the prefix of that selection. (We detect these by making
542 // sure the caret, which should be after any insertion, hasn't moved
543 // forward of the old selection start.)
544 const bool just_deleted_text
=
545 (text_before_change_
.length() > new_text
.length()) &&
546 (new_sel
.start() <= sel_before_change_
.GetMin());
548 const bool something_changed
= model()->OnAfterPossibleChange(
549 text_before_change_
, new_text
, new_sel
.start(), new_sel
.end(),
550 selection_differs
, text_changed
, just_deleted_text
, !IsIMEComposing());
552 // If only selection was changed, we don't need to call model()'s
553 // OnChanged() method, which is called in TextChanged().
554 // But we still need to call EmphasizeURLComponents() to make sure the text
555 // attributes are updated correctly.
556 if (something_changed
&& text_changed
)
558 else if (selection_differs
)
559 EmphasizeURLComponents();
560 else if (delete_at_end_pressed_
)
561 model()->OnChanged();
563 return something_changed
;
566 gfx::NativeView
OmniboxViewViews::GetNativeView() const {
567 return GetWidget()->GetNativeView();
570 gfx::NativeView
OmniboxViewViews::GetRelativeWindowForPopup() const {
571 return GetWidget()->GetTopLevelWidget()->GetNativeView();
574 void OmniboxViewViews::SetGrayTextAutocompletion(const base::string16
& input
) {
575 if (location_bar_view_
)
576 location_bar_view_
->SetGrayTextAutocompletion(input
);
579 base::string16
OmniboxViewViews::GetGrayTextAutocompletion() const {
580 return location_bar_view_
?
581 location_bar_view_
->GetGrayTextAutocompletion() : base::string16();
584 int OmniboxViewViews::GetWidth() const {
585 return location_bar_view_
? location_bar_view_
->width() : 0;
588 bool OmniboxViewViews::IsImeShowingPopup() const {
589 #if defined(OS_CHROMEOS)
590 return ime_candidate_window_open_
;
592 return GetInputMethod() ? GetInputMethod()->IsCandidatePopupOpen() : false;
596 void OmniboxViewViews::ShowImeIfNeeded() {
597 GetInputMethod()->ShowImeIfNeeded();
600 void OmniboxViewViews::OnMatchOpened(const AutocompleteMatch
& match
) {
601 extensions::MaybeShowExtensionControlledSearchNotification(
602 profile_
, location_bar_view_
->GetWebContents(), match
);
605 int OmniboxViewViews::GetOmniboxTextLength() const {
606 // TODO(oshima): Support IME.
607 return static_cast<int>(text().length());
610 void OmniboxViewViews::EmphasizeURLComponents() {
611 if (!location_bar_view_
)
614 // If the current contents is a URL, force left-to-right rendering at the
615 // paragraph level. Right-to-left runs are still rendered RTL, but will not
616 // flip the whole URL around. For example (if "ABC" is Hebrew), this will
617 // render "ABC.com" as "CBA.com", rather than "com.CBA".
618 bool text_is_url
= model()->CurrentTextIsURL();
619 GetRenderText()->SetDirectionalityMode(text_is_url
620 ? gfx::DIRECTIONALITY_FORCE_LTR
621 : gfx::DIRECTIONALITY_FROM_TEXT
);
623 // See whether the contents are a URL with a non-empty host portion, which we
624 // should emphasize. To check for a URL, rather than using the type returned
625 // by Parse(), ask the model, which will check the desired page transition for
626 // this input. This can tell us whether an UNKNOWN input string is going to
627 // be treated as a search or a navigation, and is the same method the Paste
628 // And Go system uses.
629 url::Component scheme
, host
;
630 AutocompleteInput::ParseForEmphasizeComponents(
631 text(), ChromeAutocompleteSchemeClassifier(profile_
), &scheme
, &host
);
632 bool grey_out_url
= text().substr(scheme
.begin
, scheme
.len
) ==
633 base::UTF8ToUTF16(extensions::kExtensionScheme
);
634 bool grey_base
= text_is_url
&& (host
.is_nonempty() || grey_out_url
);
635 SetColor(location_bar_view_
->GetColor(
637 grey_base
? LocationBarView::DEEMPHASIZED_TEXT
: LocationBarView::TEXT
));
638 if (grey_base
&& !grey_out_url
) {
640 location_bar_view_
->GetColor(security_level_
, LocationBarView::TEXT
),
641 gfx::Range(host
.begin
, host
.end()));
644 // Emphasize the scheme for security UI display purposes (if necessary).
645 // Note that we check CurrentTextIsURL() because if we're replacing search
646 // URLs with search terms, we may have a non-URL even when the user is not
647 // editing; and in some cases, e.g. for "site:foo.com" searches, the parser
648 // may have incorrectly identified a qualifier as a scheme.
649 SetStyle(gfx::DIAGONAL_STRIKE
, false);
650 if (!model()->user_input_in_progress() && text_is_url
&&
651 scheme
.is_nonempty() && (security_level_
!= connection_security::NONE
)) {
652 SkColor security_color
= location_bar_view_
->GetColor(
653 security_level_
, LocationBarView::SECURITY_TEXT
);
655 (security_level_
== connection_security::SECURITY_ERROR
);
656 const gfx::Range
scheme_range(scheme
.begin
, scheme
.end());
657 ApplyColor(security_color
, scheme_range
);
658 ApplyStyle(gfx::DIAGONAL_STRIKE
, strike
, scheme_range
);
662 bool OmniboxViewViews::OnKeyReleased(const ui::KeyEvent
& event
) {
663 // The omnibox contents may change while the control key is pressed.
664 if (event
.key_code() == ui::VKEY_CONTROL
)
665 model()->OnControlKeyChanged(false);
666 return views::Textfield::OnKeyReleased(event
);
669 bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id
) const {
670 return command_id
== IDS_PASTE_AND_GO
;
673 base::string16
OmniboxViewViews::GetLabelForCommandId(int command_id
) const {
674 DCHECK_EQ(IDS_PASTE_AND_GO
, command_id
);
675 return l10n_util::GetStringUTF16(
676 model()->IsPasteAndSearch(GetClipboardText()) ?
677 IDS_PASTE_AND_SEARCH
: IDS_PASTE_AND_GO
);
680 const char* OmniboxViewViews::GetClassName() const {
681 return kViewClassName
;
684 bool OmniboxViewViews::OnMousePressed(const ui::MouseEvent
& event
) {
685 select_all_on_mouse_release_
=
686 (event
.IsOnlyLeftMouseButton() || event
.IsOnlyRightMouseButton()) &&
687 (!HasFocus() || (model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE
));
688 if (select_all_on_mouse_release_
) {
689 // Restore caret visibility whenever the user clicks in the omnibox in a way
690 // that would give it focus. We must handle this case separately here
691 // because if the omnibox currently has invisible focus, the mouse event
692 // won't trigger either SetFocus() or OmniboxEditModel::OnSetFocus().
693 model()->SetCaretVisibility(true);
695 // When we're going to select all on mouse release, invalidate any saved
696 // selection lest restoring it fights with the "select all" action. It's
697 // possible to later set select_all_on_mouse_release_ back to false, but
698 // that happens for things like dragging, which are cases where having
699 // invalidated this saved selection is still OK.
700 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
702 return views::Textfield::OnMousePressed(event
);
705 bool OmniboxViewViews::OnMouseDragged(const ui::MouseEvent
& event
) {
706 if (ExceededDragThreshold(event
.location() - last_click_location()))
707 select_all_on_mouse_release_
= false;
709 if (HasTextBeingDragged())
712 return views::Textfield::OnMouseDragged(event
);
715 void OmniboxViewViews::OnMouseReleased(const ui::MouseEvent
& event
) {
716 views::Textfield::OnMouseReleased(event
);
717 if (event
.IsOnlyLeftMouseButton() || event
.IsOnlyRightMouseButton()) {
718 // When the user has clicked and released to give us focus, select all
719 // unless we're omitting the URL (in which case refining an existing query
720 // is common enough that we do click-to-place-cursor).
721 if (select_all_on_mouse_release_
&&
722 !controller()->GetToolbarModel()->WouldReplaceURL()) {
723 // Select all in the reverse direction so as not to scroll the caret
724 // into view and shift the contents jarringly.
728 select_all_on_mouse_release_
= false;
731 bool OmniboxViewViews::OnKeyPressed(const ui::KeyEvent
& event
) {
732 // Skip processing of [Alt]+<num-pad digit> Unicode alt key codes.
733 // Otherwise, if num-lock is off, the events are handled as [Up], [Down], etc.
734 if (event
.IsUnicodeKeyCode())
735 return views::Textfield::OnKeyPressed(event
);
737 const bool shift
= event
.IsShiftDown();
738 const bool control
= event
.IsControlDown();
739 const bool alt
= event
.IsAltDown() || event
.IsAltGrDown();
740 switch (event
.key_code()) {
741 case ui::VKEY_RETURN
:
742 model()->AcceptInput(alt
? NEW_FOREGROUND_TAB
: CURRENT_TAB
, false);
744 case ui::VKEY_ESCAPE
:
745 return model()->OnEscapeKeyPressed();
746 case ui::VKEY_CONTROL
:
747 model()->OnControlKeyChanged(true);
749 case ui::VKEY_DELETE
:
750 if (shift
&& model()->popup_model()->IsOpen())
751 model()->popup_model()->TryDeletingCurrentItem();
755 model()->OnUpOrDownKeyPressed(-1);
761 model()->OnUpOrDownKeyPressed(1);
766 if (control
|| alt
|| shift
)
768 model()->OnUpOrDownKeyPressed(-1 * model()->result().size());
771 if (control
|| alt
|| shift
)
773 model()->OnUpOrDownKeyPressed(model()->result().size());
776 if (control
&& !alt
&& !read_only()) {
777 ExecuteCommand(IDS_APP_PASTE
, 0);
781 case ui::VKEY_INSERT
:
782 if (shift
&& !control
&& !read_only()) {
783 ExecuteCommand(IDS_APP_PASTE
, 0);
791 return views::Textfield::OnKeyPressed(event
) || HandleEarlyTabActions(event
);
794 void OmniboxViewViews::OnGestureEvent(ui::GestureEvent
* event
) {
795 if (!HasFocus() && event
->type() == ui::ET_GESTURE_TAP_DOWN
) {
796 select_all_on_gesture_tap_
= true;
798 // If we're trying to select all on tap, invalidate any saved selection lest
799 // restoring it fights with the "select all" action.
800 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
803 views::Textfield::OnGestureEvent(event
);
805 if (select_all_on_gesture_tap_
&& event
->type() == ui::ET_GESTURE_TAP
)
808 if (event
->type() == ui::ET_GESTURE_TAP
||
809 event
->type() == ui::ET_GESTURE_TAP_CANCEL
||
810 event
->type() == ui::ET_GESTURE_TWO_FINGER_TAP
||
811 event
->type() == ui::ET_GESTURE_SCROLL_BEGIN
||
812 event
->type() == ui::ET_GESTURE_PINCH_BEGIN
||
813 event
->type() == ui::ET_GESTURE_LONG_PRESS
||
814 event
->type() == ui::ET_GESTURE_LONG_TAP
) {
815 select_all_on_gesture_tap_
= false;
819 void OmniboxViewViews::AboutToRequestFocusFromTabTraversal(bool reverse
) {
820 views::Textfield::AboutToRequestFocusFromTabTraversal(reverse
);
823 bool OmniboxViewViews::SkipDefaultKeyEventProcessing(
824 const ui::KeyEvent
& event
) {
825 if (views::FocusManager::IsTabTraversalKeyEvent(event
) &&
826 ((model()->is_keyword_hint() && !event
.IsShiftDown()) ||
827 model()->popup_model()->IsOpen())) {
830 if (event
.key_code() == ui::VKEY_ESCAPE
)
831 return model()->WillHandleEscapeKey();
832 return Textfield::SkipDefaultKeyEventProcessing(event
);
835 void OmniboxViewViews::GetAccessibleState(ui::AXViewState
* state
) {
836 state
->role
= ui::AX_ROLE_TEXT_FIELD
;
837 state
->name
= l10n_util::GetStringUTF16(IDS_ACCNAME_LOCATION
);
838 state
->value
= GetText();
840 base::string16::size_type entry_start
;
841 base::string16::size_type entry_end
;
842 GetSelectionBounds(&entry_start
, &entry_end
);
843 state
->selection_start
= entry_start
;
844 state
->selection_end
= entry_end
;
846 if (popup_window_mode_
) {
847 state
->AddStateFlag(ui::AX_STATE_READ_ONLY
);
849 state
->set_value_callback
=
850 base::Bind(&OmniboxViewViews::AccessibilitySetValue
,
851 weak_ptr_factory_
.GetWeakPtr());
855 void OmniboxViewViews::OnFocus() {
856 views::Textfield::OnFocus();
857 // TODO(oshima): Get control key state.
858 model()->OnSetFocus(false);
859 // Don't call controller()->OnSetFocus, this view has already acquired focus.
861 // Restore the selection we saved in OnBlur() if it's still valid.
862 if (saved_selection_for_focus_change_
.IsValid()) {
863 SelectRange(saved_selection_for_focus_change_
);
864 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
868 void OmniboxViewViews::OnBlur() {
869 // Save the user's existing selection to restore it later.
870 saved_selection_for_focus_change_
= GetSelectedRange();
872 views::Textfield::OnBlur();
873 model()->OnWillKillFocus();
875 // If ZeroSuggest is active, we may have refused to show an update to the
876 // underlying permanent URL that happened while the popup was open, so
877 // revert to ensure that update is shown now. Otherwise, make sure to call
878 // CloseOmniboxPopup() unconditionally, so that if ZeroSuggest is in the midst
879 // of running but hasn't yet opened the popup, it will be halted.
880 if (!model()->user_input_in_progress() && model()->popup_model()->IsOpen())
885 // Tell the model to reset itself.
886 model()->OnKillFocus();
888 // Make sure the beginning of the text is visible.
889 SelectRange(gfx::Range(0));
892 bool OmniboxViewViews::IsCommandIdEnabled(int command_id
) const {
893 if (command_id
== IDS_APP_PASTE
)
894 return !read_only() && !GetClipboardText().empty();
895 if (command_id
== IDS_PASTE_AND_GO
)
896 return !read_only() && model()->CanPasteAndGo(GetClipboardText());
897 if (command_id
== IDS_SHOW_URL
)
898 return controller()->GetToolbarModel()->WouldReplaceURL();
899 return command_id
== IDS_MOVE_DOWN
|| command_id
== IDS_MOVE_UP
||
900 Textfield::IsCommandIdEnabled(command_id
) ||
901 location_bar_view_
->command_updater()->IsCommandEnabled(command_id
);
904 base::string16
OmniboxViewViews::GetSelectionClipboardText() const {
905 return SanitizeTextForPaste(Textfield::GetSelectionClipboardText());
908 void OmniboxViewViews::DoInsertChar(base::char16 ch
) {
909 // If |insert_char_time_| is not null, there's a pending insert char operation
910 // that hasn't been painted yet. Keep the earlier time.
911 if (insert_char_time_
.is_null())
912 insert_char_time_
= base::TimeTicks::Now();
913 Textfield::DoInsertChar(ch
);
916 #if defined(OS_CHROMEOS)
917 void OmniboxViewViews::CandidateWindowOpened(
918 chromeos::input_method::InputMethodManager
* manager
) {
919 ime_candidate_window_open_
= true;
922 void OmniboxViewViews::CandidateWindowClosed(
923 chromeos::input_method::InputMethodManager
* manager
) {
924 ime_candidate_window_open_
= false;
928 void OmniboxViewViews::ContentsChanged(views::Textfield
* sender
,
929 const base::string16
& new_contents
) {
932 bool OmniboxViewViews::HandleKeyEvent(views::Textfield
* textfield
,
933 const ui::KeyEvent
& event
) {
934 delete_at_end_pressed_
= false;
936 if (event
.key_code() == ui::VKEY_BACK
) {
937 // No extra handling is needed in keyword search mode, if there is a
938 // non-empty selection, or if the cursor is not leading the text.
939 if (model()->is_keyword_hint() || model()->keyword().empty() ||
940 HasSelection() || GetCursorPosition() != 0)
942 model()->ClearKeyword();
946 if (event
.key_code() == ui::VKEY_DELETE
&& !event
.IsAltDown()) {
947 delete_at_end_pressed_
=
948 (!HasSelection() && GetCursorPosition() == text().length());
951 // Handle the right-arrow key for LTR text and the left-arrow key for RTL text
952 // if there is gray text that needs to be committed.
953 if (GetCursorPosition() == text().length()) {
954 base::i18n::TextDirection direction
= GetTextDirection();
955 if ((direction
== base::i18n::LEFT_TO_RIGHT
&&
956 event
.key_code() == ui::VKEY_RIGHT
) ||
957 (direction
== base::i18n::RIGHT_TO_LEFT
&&
958 event
.key_code() == ui::VKEY_LEFT
)) {
959 return model()->CommitSuggestedText();
966 void OmniboxViewViews::OnBeforeUserAction(views::Textfield
* sender
) {
967 OnBeforePossibleChange();
970 void OmniboxViewViews::OnAfterUserAction(views::Textfield
* sender
) {
971 OnAfterPossibleChange();
974 void OmniboxViewViews::OnAfterCutOrCopy(ui::ClipboardType clipboard_type
) {
975 ui::Clipboard
* cb
= ui::Clipboard::GetForCurrentThread();
976 base::string16 selected_text
;
977 cb
->ReadText(clipboard_type
, &selected_text
);
980 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
981 &selected_text
, &url
, &write_url
);
983 UMA_HISTOGRAM_COUNTS(OmniboxEditModel::kCutOrCopyAllTextHistogram
, 1);
986 BookmarkNodeData data
;
987 data
.ReadFromTuple(url
, selected_text
);
988 data
.WriteToClipboard(clipboard_type
);
990 ui::ScopedClipboardWriter
scoped_clipboard_writer(clipboard_type
);
991 scoped_clipboard_writer
.WriteText(selected_text
);
995 void OmniboxViewViews::OnWriteDragData(ui::OSExchangeData
* data
) {
998 bool is_all_selected
= IsSelectAll();
999 base::string16 selected_text
= GetSelectedText();
1000 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), is_all_selected
,
1001 &selected_text
, &url
, &write_url
);
1002 data
->SetString(selected_text
);
1005 base::string16 title
= selected_text
;
1006 if (is_all_selected
)
1007 model()->GetDataForURLExport(&url
, &title
, &favicon
);
1008 button_drag_utils::SetURLAndDragImage(url
, title
, favicon
.AsImageSkia(),
1009 NULL
, data
, GetWidget());
1010 data
->SetURL(url
, title
);
1014 void OmniboxViewViews::OnGetDragOperationsForTextfield(int* drag_operations
) {
1015 base::string16 selected_text
= GetSelectedText();
1018 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
1019 &selected_text
, &url
, &write_url
);
1021 *drag_operations
|= ui::DragDropTypes::DRAG_LINK
;
1024 void OmniboxViewViews::AppendDropFormats(
1026 std::set
<ui::OSExchangeData::CustomFormat
>* custom_formats
) {
1027 *formats
= *formats
| ui::OSExchangeData::URL
;
1030 int OmniboxViewViews::OnDrop(const ui::OSExchangeData
& data
) {
1031 if (HasTextBeingDragged())
1032 return ui::DragDropTypes::DRAG_NONE
;
1034 if (data
.HasURL(ui::OSExchangeData::CONVERT_FILENAMES
)) {
1036 base::string16 title
;
1037 if (data
.GetURLAndTitle(
1038 ui::OSExchangeData::CONVERT_FILENAMES
, &url
, &title
)) {
1039 base::string16
text(
1040 StripJavascriptSchemas(base::UTF8ToUTF16(url
.spec())));
1041 if (model()->CanPasteAndGo(text
)) {
1042 model()->PasteAndGo(text
);
1043 return ui::DragDropTypes::DRAG_COPY
;
1046 } else if (data
.HasString()) {
1047 base::string16 text
;
1048 if (data
.GetString(&text
)) {
1049 base::string16
collapsed_text(base::CollapseWhitespace(text
, true));
1050 if (model()->CanPasteAndGo(collapsed_text
))
1051 model()->PasteAndGo(collapsed_text
);
1052 return ui::DragDropTypes::DRAG_COPY
;
1056 return ui::DragDropTypes::DRAG_NONE
;
1059 void OmniboxViewViews::UpdateContextMenu(ui::SimpleMenuModel
* menu_contents
) {
1060 int paste_position
= menu_contents
->GetIndexOfCommandId(IDS_APP_PASTE
);
1061 DCHECK_GE(paste_position
, 0);
1062 menu_contents
->InsertItemWithStringIdAt(
1063 paste_position
+ 1, IDS_PASTE_AND_GO
, IDS_PASTE_AND_GO
);
1065 menu_contents
->AddSeparator(ui::NORMAL_SEPARATOR
);
1067 if (search::IsQueryExtractionEnabled()) {
1068 int select_all_position
= menu_contents
->GetIndexOfCommandId(
1069 IDS_APP_SELECT_ALL
);
1070 DCHECK_GE(select_all_position
, 0);
1071 menu_contents
->InsertItemWithStringIdAt(
1072 select_all_position
+ 1, IDS_SHOW_URL
, IDS_SHOW_URL
);
1075 // Minor note: We use IDC_ for command id here while the underlying textfield
1076 // is using IDS_ for all its command ids. This is because views cannot depend
1078 menu_contents
->AddItemWithStringId(IDC_EDIT_SEARCH_ENGINES
,
1079 IDS_EDIT_SEARCH_ENGINES
);