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_(SecurityStateModel::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 SecurityStateModel::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 SecurityStateModel::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_
!= SecurityStateModel::NONE
)) {
652 SkColor security_color
= location_bar_view_
->GetColor(
653 security_level_
, LocationBarView::SECURITY_TEXT
);
654 const bool strike
= (security_level_
== SecurityStateModel::SECURITY_ERROR
);
655 const gfx::Range
scheme_range(scheme
.begin
, scheme
.end());
656 ApplyColor(security_color
, scheme_range
);
657 ApplyStyle(gfx::DIAGONAL_STRIKE
, strike
, scheme_range
);
661 bool OmniboxViewViews::OnKeyReleased(const ui::KeyEvent
& event
) {
662 // The omnibox contents may change while the control key is pressed.
663 if (event
.key_code() == ui::VKEY_CONTROL
)
664 model()->OnControlKeyChanged(false);
665 return views::Textfield::OnKeyReleased(event
);
668 bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id
) const {
669 return command_id
== IDS_PASTE_AND_GO
;
672 base::string16
OmniboxViewViews::GetLabelForCommandId(int command_id
) const {
673 DCHECK_EQ(IDS_PASTE_AND_GO
, command_id
);
674 return l10n_util::GetStringUTF16(
675 model()->IsPasteAndSearch(GetClipboardText()) ?
676 IDS_PASTE_AND_SEARCH
: IDS_PASTE_AND_GO
);
679 const char* OmniboxViewViews::GetClassName() const {
680 return kViewClassName
;
683 bool OmniboxViewViews::OnMousePressed(const ui::MouseEvent
& event
) {
684 select_all_on_mouse_release_
=
685 (event
.IsOnlyLeftMouseButton() || event
.IsOnlyRightMouseButton()) &&
686 (!HasFocus() || (model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE
));
687 if (select_all_on_mouse_release_
) {
688 // Restore caret visibility whenever the user clicks in the omnibox in a way
689 // that would give it focus. We must handle this case separately here
690 // because if the omnibox currently has invisible focus, the mouse event
691 // won't trigger either SetFocus() or OmniboxEditModel::OnSetFocus().
692 model()->SetCaretVisibility(true);
694 // When we're going to select all on mouse release, invalidate any saved
695 // selection lest restoring it fights with the "select all" action. It's
696 // possible to later set select_all_on_mouse_release_ back to false, but
697 // that happens for things like dragging, which are cases where having
698 // invalidated this saved selection is still OK.
699 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
701 return views::Textfield::OnMousePressed(event
);
704 bool OmniboxViewViews::OnMouseDragged(const ui::MouseEvent
& event
) {
705 if (ExceededDragThreshold(event
.location() - last_click_location()))
706 select_all_on_mouse_release_
= false;
708 if (HasTextBeingDragged())
711 return views::Textfield::OnMouseDragged(event
);
714 void OmniboxViewViews::OnMouseReleased(const ui::MouseEvent
& event
) {
715 views::Textfield::OnMouseReleased(event
);
716 if (event
.IsOnlyLeftMouseButton() || event
.IsOnlyRightMouseButton()) {
717 // When the user has clicked and released to give us focus, select all
718 // unless we're omitting the URL (in which case refining an existing query
719 // is common enough that we do click-to-place-cursor).
720 if (select_all_on_mouse_release_
&&
721 !controller()->GetToolbarModel()->WouldReplaceURL()) {
722 // Select all in the reverse direction so as not to scroll the caret
723 // into view and shift the contents jarringly.
727 select_all_on_mouse_release_
= false;
730 bool OmniboxViewViews::OnKeyPressed(const ui::KeyEvent
& event
) {
731 // Skip processing of [Alt]+<num-pad digit> Unicode alt key codes.
732 // Otherwise, if num-lock is off, the events are handled as [Up], [Down], etc.
733 if (event
.IsUnicodeKeyCode())
734 return views::Textfield::OnKeyPressed(event
);
736 const bool shift
= event
.IsShiftDown();
737 const bool control
= event
.IsControlDown();
738 const bool alt
= event
.IsAltDown() || event
.IsAltGrDown();
739 switch (event
.key_code()) {
740 case ui::VKEY_RETURN
:
741 model()->AcceptInput(alt
? NEW_FOREGROUND_TAB
: CURRENT_TAB
, false);
743 case ui::VKEY_ESCAPE
:
744 return model()->OnEscapeKeyPressed();
745 case ui::VKEY_CONTROL
:
746 model()->OnControlKeyChanged(true);
748 case ui::VKEY_DELETE
:
749 if (shift
&& model()->popup_model()->IsOpen())
750 model()->popup_model()->TryDeletingCurrentItem();
754 model()->OnUpOrDownKeyPressed(-1);
760 model()->OnUpOrDownKeyPressed(1);
765 if (control
|| alt
|| shift
)
767 model()->OnUpOrDownKeyPressed(-1 * model()->result().size());
770 if (control
|| alt
|| shift
)
772 model()->OnUpOrDownKeyPressed(model()->result().size());
775 if (control
&& !alt
&& !read_only()) {
776 ExecuteCommand(IDS_APP_PASTE
, 0);
780 case ui::VKEY_INSERT
:
781 if (shift
&& !control
&& !read_only()) {
782 ExecuteCommand(IDS_APP_PASTE
, 0);
790 return views::Textfield::OnKeyPressed(event
) || HandleEarlyTabActions(event
);
793 void OmniboxViewViews::OnGestureEvent(ui::GestureEvent
* event
) {
794 if (!HasFocus() && event
->type() == ui::ET_GESTURE_TAP_DOWN
) {
795 select_all_on_gesture_tap_
= true;
797 // If we're trying to select all on tap, invalidate any saved selection lest
798 // restoring it fights with the "select all" action.
799 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
802 views::Textfield::OnGestureEvent(event
);
804 if (select_all_on_gesture_tap_
&& event
->type() == ui::ET_GESTURE_TAP
)
807 if (event
->type() == ui::ET_GESTURE_TAP
||
808 event
->type() == ui::ET_GESTURE_TAP_CANCEL
||
809 event
->type() == ui::ET_GESTURE_TWO_FINGER_TAP
||
810 event
->type() == ui::ET_GESTURE_SCROLL_BEGIN
||
811 event
->type() == ui::ET_GESTURE_PINCH_BEGIN
||
812 event
->type() == ui::ET_GESTURE_LONG_PRESS
||
813 event
->type() == ui::ET_GESTURE_LONG_TAP
) {
814 select_all_on_gesture_tap_
= false;
818 void OmniboxViewViews::AboutToRequestFocusFromTabTraversal(bool reverse
) {
819 views::Textfield::AboutToRequestFocusFromTabTraversal(reverse
);
822 bool OmniboxViewViews::SkipDefaultKeyEventProcessing(
823 const ui::KeyEvent
& event
) {
824 if (views::FocusManager::IsTabTraversalKeyEvent(event
) &&
825 ((model()->is_keyword_hint() && !event
.IsShiftDown()) ||
826 model()->popup_model()->IsOpen())) {
829 if (event
.key_code() == ui::VKEY_ESCAPE
)
830 return model()->WillHandleEscapeKey();
831 return Textfield::SkipDefaultKeyEventProcessing(event
);
834 void OmniboxViewViews::GetAccessibleState(ui::AXViewState
* state
) {
835 state
->role
= ui::AX_ROLE_TEXT_FIELD
;
836 state
->name
= l10n_util::GetStringUTF16(IDS_ACCNAME_LOCATION
);
837 state
->value
= GetText();
839 base::string16::size_type entry_start
;
840 base::string16::size_type entry_end
;
841 GetSelectionBounds(&entry_start
, &entry_end
);
842 state
->selection_start
= entry_start
;
843 state
->selection_end
= entry_end
;
845 if (popup_window_mode_
) {
846 state
->AddStateFlag(ui::AX_STATE_READ_ONLY
);
848 state
->set_value_callback
=
849 base::Bind(&OmniboxViewViews::AccessibilitySetValue
,
850 weak_ptr_factory_
.GetWeakPtr());
854 void OmniboxViewViews::OnFocus() {
855 views::Textfield::OnFocus();
856 // TODO(oshima): Get control key state.
857 model()->OnSetFocus(false);
858 // Don't call controller()->OnSetFocus, this view has already acquired focus.
860 // Restore the selection we saved in OnBlur() if it's still valid.
861 if (saved_selection_for_focus_change_
.IsValid()) {
862 SelectRange(saved_selection_for_focus_change_
);
863 saved_selection_for_focus_change_
= gfx::Range::InvalidRange();
867 void OmniboxViewViews::OnBlur() {
868 // Save the user's existing selection to restore it later.
869 saved_selection_for_focus_change_
= GetSelectedRange();
871 views::Textfield::OnBlur();
872 model()->OnWillKillFocus();
874 // If ZeroSuggest is active, we may have refused to show an update to the
875 // underlying permanent URL that happened while the popup was open, so
876 // revert to ensure that update is shown now. Otherwise, make sure to call
877 // CloseOmniboxPopup() unconditionally, so that if ZeroSuggest is in the midst
878 // of running but hasn't yet opened the popup, it will be halted.
879 if (!model()->user_input_in_progress() && model()->popup_model()->IsOpen())
884 // Tell the model to reset itself.
885 model()->OnKillFocus();
887 // Make sure the beginning of the text is visible.
888 SelectRange(gfx::Range(0));
891 bool OmniboxViewViews::IsCommandIdEnabled(int command_id
) const {
892 if (command_id
== IDS_APP_PASTE
)
893 return !read_only() && !GetClipboardText().empty();
894 if (command_id
== IDS_PASTE_AND_GO
)
895 return !read_only() && model()->CanPasteAndGo(GetClipboardText());
896 if (command_id
== IDS_SHOW_URL
)
897 return controller()->GetToolbarModel()->WouldReplaceURL();
898 return command_id
== IDS_MOVE_DOWN
|| command_id
== IDS_MOVE_UP
||
899 Textfield::IsCommandIdEnabled(command_id
) ||
900 location_bar_view_
->command_updater()->IsCommandEnabled(command_id
);
903 base::string16
OmniboxViewViews::GetSelectionClipboardText() const {
904 return SanitizeTextForPaste(Textfield::GetSelectionClipboardText());
907 void OmniboxViewViews::DoInsertChar(base::char16 ch
) {
908 // If |insert_char_time_| is not null, there's a pending insert char operation
909 // that hasn't been painted yet. Keep the earlier time.
910 if (insert_char_time_
.is_null())
911 insert_char_time_
= base::TimeTicks::Now();
912 Textfield::DoInsertChar(ch
);
915 #if defined(OS_CHROMEOS)
916 void OmniboxViewViews::CandidateWindowOpened(
917 chromeos::input_method::InputMethodManager
* manager
) {
918 ime_candidate_window_open_
= true;
921 void OmniboxViewViews::CandidateWindowClosed(
922 chromeos::input_method::InputMethodManager
* manager
) {
923 ime_candidate_window_open_
= false;
927 void OmniboxViewViews::ContentsChanged(views::Textfield
* sender
,
928 const base::string16
& new_contents
) {
931 bool OmniboxViewViews::HandleKeyEvent(views::Textfield
* textfield
,
932 const ui::KeyEvent
& event
) {
933 delete_at_end_pressed_
= false;
935 if (event
.key_code() == ui::VKEY_BACK
) {
936 // No extra handling is needed in keyword search mode, if there is a
937 // non-empty selection, or if the cursor is not leading the text.
938 if (model()->is_keyword_hint() || model()->keyword().empty() ||
939 HasSelection() || GetCursorPosition() != 0)
941 model()->ClearKeyword();
945 if (event
.key_code() == ui::VKEY_DELETE
&& !event
.IsAltDown()) {
946 delete_at_end_pressed_
=
947 (!HasSelection() && GetCursorPosition() == text().length());
950 // Handle the right-arrow key for LTR text and the left-arrow key for RTL text
951 // if there is gray text that needs to be committed.
952 if (GetCursorPosition() == text().length()) {
953 base::i18n::TextDirection direction
= GetTextDirection();
954 if ((direction
== base::i18n::LEFT_TO_RIGHT
&&
955 event
.key_code() == ui::VKEY_RIGHT
) ||
956 (direction
== base::i18n::RIGHT_TO_LEFT
&&
957 event
.key_code() == ui::VKEY_LEFT
)) {
958 return model()->CommitSuggestedText();
965 void OmniboxViewViews::OnBeforeUserAction(views::Textfield
* sender
) {
966 OnBeforePossibleChange();
969 void OmniboxViewViews::OnAfterUserAction(views::Textfield
* sender
) {
970 OnAfterPossibleChange();
973 void OmniboxViewViews::OnAfterCutOrCopy(ui::ClipboardType clipboard_type
) {
974 ui::Clipboard
* cb
= ui::Clipboard::GetForCurrentThread();
975 base::string16 selected_text
;
976 cb
->ReadText(clipboard_type
, &selected_text
);
979 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
980 &selected_text
, &url
, &write_url
);
982 UMA_HISTOGRAM_COUNTS(OmniboxEditModel::kCutOrCopyAllTextHistogram
, 1);
985 BookmarkNodeData data
;
986 data
.ReadFromTuple(url
, selected_text
);
987 data
.WriteToClipboard(clipboard_type
);
989 ui::ScopedClipboardWriter
scoped_clipboard_writer(clipboard_type
);
990 scoped_clipboard_writer
.WriteText(selected_text
);
994 void OmniboxViewViews::OnWriteDragData(ui::OSExchangeData
* data
) {
997 bool is_all_selected
= IsSelectAll();
998 base::string16 selected_text
= GetSelectedText();
999 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), is_all_selected
,
1000 &selected_text
, &url
, &write_url
);
1001 data
->SetString(selected_text
);
1004 base::string16 title
= selected_text
;
1005 if (is_all_selected
)
1006 model()->GetDataForURLExport(&url
, &title
, &favicon
);
1007 button_drag_utils::SetURLAndDragImage(url
, title
, favicon
.AsImageSkia(),
1008 NULL
, data
, GetWidget());
1009 data
->SetURL(url
, title
);
1013 void OmniboxViewViews::OnGetDragOperationsForTextfield(int* drag_operations
) {
1014 base::string16 selected_text
= GetSelectedText();
1017 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
1018 &selected_text
, &url
, &write_url
);
1020 *drag_operations
|= ui::DragDropTypes::DRAG_LINK
;
1023 void OmniboxViewViews::AppendDropFormats(
1025 std::set
<ui::OSExchangeData::CustomFormat
>* custom_formats
) {
1026 *formats
= *formats
| ui::OSExchangeData::URL
;
1029 int OmniboxViewViews::OnDrop(const ui::OSExchangeData
& data
) {
1030 if (HasTextBeingDragged())
1031 return ui::DragDropTypes::DRAG_NONE
;
1033 if (data
.HasURL(ui::OSExchangeData::CONVERT_FILENAMES
)) {
1035 base::string16 title
;
1036 if (data
.GetURLAndTitle(
1037 ui::OSExchangeData::CONVERT_FILENAMES
, &url
, &title
)) {
1038 base::string16
text(
1039 StripJavascriptSchemas(base::UTF8ToUTF16(url
.spec())));
1040 if (model()->CanPasteAndGo(text
)) {
1041 model()->PasteAndGo(text
);
1042 return ui::DragDropTypes::DRAG_COPY
;
1045 } else if (data
.HasString()) {
1046 base::string16 text
;
1047 if (data
.GetString(&text
)) {
1048 base::string16
collapsed_text(base::CollapseWhitespace(text
, true));
1049 if (model()->CanPasteAndGo(collapsed_text
))
1050 model()->PasteAndGo(collapsed_text
);
1051 return ui::DragDropTypes::DRAG_COPY
;
1055 return ui::DragDropTypes::DRAG_NONE
;
1058 void OmniboxViewViews::UpdateContextMenu(ui::SimpleMenuModel
* menu_contents
) {
1059 int paste_position
= menu_contents
->GetIndexOfCommandId(IDS_APP_PASTE
);
1060 DCHECK_GE(paste_position
, 0);
1061 menu_contents
->InsertItemWithStringIdAt(
1062 paste_position
+ 1, IDS_PASTE_AND_GO
, IDS_PASTE_AND_GO
);
1064 menu_contents
->AddSeparator(ui::NORMAL_SEPARATOR
);
1066 if (search::IsQueryExtractionEnabled()) {
1067 int select_all_position
= menu_contents
->GetIndexOfCommandId(
1068 IDS_APP_SELECT_ALL
);
1069 DCHECK_GE(select_all_position
, 0);
1070 menu_contents
->InsertItemWithStringIdAt(
1071 select_all_position
+ 1, IDS_SHOW_URL
, IDS_SHOW_URL
);
1074 // Minor note: We use IDC_ for command id here while the underlying textfield
1075 // is using IDS_ for all its command ids. This is because views cannot depend
1077 menu_contents
->AddItemWithStringId(IDC_EDIT_SEARCH_ENGINES
,
1078 IDS_EDIT_SEARCH_ENGINES
);