Revert of Move SecurityLevel into a class of its own (patchset #19 id:420001 of https...
[chromium-blink-merge.git] / chrome / browser / ui / views / omnibox / omnibox_view_views.cc
blobb5a2347971df7e9588de5f4c727576343c47ae45
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/ui/views/omnibox/omnibox_view_views.h"
7 #include <set>
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/omnibox_edit_controller.h"
19 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
20 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
21 #include "chrome/browser/ui/view_ids.h"
22 #include "chrome/browser/ui/views/location_bar/location_bar_view.h"
23 #include "chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h"
24 #include "chrome/browser/ui/views/settings_api_bubble_helper_views.h"
25 #include "chrome/grit/generated_resources.h"
26 #include "components/bookmarks/browser/bookmark_node_data.h"
27 #include "components/omnibox/autocomplete_input.h"
28 #include "components/omnibox/autocomplete_match.h"
29 #include "components/omnibox/omnibox_field_trial.h"
30 #include "content/public/browser/web_contents.h"
31 #include "extensions/common/constants.h"
32 #include "net/base/escape.h"
33 #include "third_party/skia/include/core/SkColor.h"
34 #include "ui/accessibility/ax_view_state.h"
35 #include "ui/base/clipboard/scoped_clipboard_writer.h"
36 #include "ui/base/dragdrop/drag_drop_types.h"
37 #include "ui/base/dragdrop/os_exchange_data.h"
38 #include "ui/base/ime/text_input_client.h"
39 #include "ui/base/ime/text_input_type.h"
40 #include "ui/base/l10n/l10n_util.h"
41 #include "ui/base/models/simple_menu_model.h"
42 #include "ui/compositor/layer.h"
43 #include "ui/events/event.h"
44 #include "ui/gfx/canvas.h"
45 #include "ui/gfx/font_list.h"
46 #include "ui/gfx/selection_model.h"
47 #include "ui/strings/grit/ui_strings.h"
48 #include "ui/views/border.h"
49 #include "ui/views/button_drag_utils.h"
50 #include "ui/views/controls/textfield/textfield.h"
51 #include "ui/views/ime/input_method.h"
52 #include "ui/views/layout/fill_layout.h"
53 #include "ui/views/views_delegate.h"
54 #include "ui/views/widget/widget.h"
55 #include "url/gurl.h"
57 #if defined(OS_WIN)
58 #include "chrome/browser/browser_process.h"
59 #endif
61 using bookmarks::BookmarkNodeData;
63 namespace {
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;
86 // static
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),
93 selection(selection),
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() {
110 #if defined(OS_WIN)
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" ||
116 language == "ko" ||
117 language == "th" ||
118 language == "zh")
119 return ui::TEXT_INPUT_TYPE_SEARCH;
120 #endif
121 return ui::TEXT_INPUT_TYPE_URL;
124 } // namespace
127 // OmniboxViewViews -----------------------------------------------------------
129 // static
130 const char OmniboxViewViews::kViewClassName[] = "OmniboxViewViews";
132 OmniboxViewViews::OmniboxViewViews(OmniboxEditController* controller,
133 Profile* profile,
134 CommandUpdater* command_updater,
135 bool popup_window_mode,
136 LocationBarView* location_bar,
137 const gfx::FontList& font_list)
138 : OmniboxView(profile, controller, command_updater),
139 popup_window_mode_(popup_window_mode),
140 security_level_(ToolbarModel::NONE),
141 saved_selection_for_focus_change_(gfx::Range::InvalidRange()),
142 ime_composing_before_change_(false),
143 delete_at_end_pressed_(false),
144 location_bar_view_(location_bar),
145 ime_candidate_window_open_(false),
146 select_all_on_mouse_release_(false),
147 select_all_on_gesture_tap_(false),
148 weak_ptr_factory_(this) {
149 SetBorder(views::Border::NullBorder());
150 set_id(VIEW_ID_OMNIBOX);
151 SetFontList(font_list);
154 OmniboxViewViews::~OmniboxViewViews() {
155 #if defined(OS_CHROMEOS)
156 chromeos::input_method::InputMethodManager::Get()->
157 RemoveCandidateWindowObserver(this);
158 #endif
160 // Explicitly teardown members which have a reference to us. Just to be safe
161 // we want them to be destroyed before destroying any other internal state.
162 popup_view_.reset();
165 void OmniboxViewViews::Init() {
166 set_controller(this);
167 SetTextInputType(DetermineTextInputType());
169 if (popup_window_mode_)
170 SetReadOnly(true);
172 if (location_bar_view_) {
173 // Initialize the popup view using the same font.
174 popup_view_.reset(OmniboxPopupContentsView::Create(
175 GetFontList(), this, model(), location_bar_view_));
178 #if defined(OS_CHROMEOS)
179 chromeos::input_method::InputMethodManager::Get()->
180 AddCandidateWindowObserver(this);
181 #endif
184 void OmniboxViewViews::SaveStateToTab(content::WebContents* tab) {
185 DCHECK(tab);
187 // We don't want to keep the IME status, so force quit the current
188 // session here. It may affect the selection status, so order is
189 // also important.
190 if (IsIMEComposing()) {
191 GetTextInputClient()->ConfirmCompositionText();
192 GetInputMethod()->CancelComposition(this);
195 // NOTE: GetStateForTabSwitch() may affect GetSelectedRange(), so order is
196 // important.
197 OmniboxEditModel::State state = model()->GetStateForTabSwitch();
198 tab->SetUserData(OmniboxState::kKey, new OmniboxState(
199 state, GetSelectedRange(), saved_selection_for_focus_change_));
202 void OmniboxViewViews::OnTabChanged(const content::WebContents* web_contents) {
203 security_level_ = controller()->GetToolbarModel()->GetSecurityLevel(false);
205 const OmniboxState* state = static_cast<OmniboxState*>(
206 web_contents->GetUserData(&OmniboxState::kKey));
207 model()->RestoreState(state ? &state->model_state : NULL);
208 if (state) {
209 // This assumes that the omnibox has already been focused or blurred as
210 // appropriate; otherwise, a subsequent OnFocus() or OnBlur() call could
211 // goof up the selection. See comments at the end of
212 // BrowserView::ActiveTabChanged().
213 SelectRange(state->selection);
214 saved_selection_for_focus_change_ = state->saved_selection_for_focus_change;
217 // TODO(msw|oshima): Consider saving/restoring edit history.
218 ClearEditHistory();
221 void OmniboxViewViews::ResetTabState(content::WebContents* web_contents) {
222 web_contents->SetUserData(OmniboxState::kKey, nullptr);
225 void OmniboxViewViews::Update() {
226 const ToolbarModel::SecurityLevel old_security_level = security_level_;
227 security_level_ = controller()->GetToolbarModel()->GetSecurityLevel(false);
228 if (model()->UpdatePermanentText()) {
229 // Something visibly changed. Re-enable URL replacement.
230 controller()->GetToolbarModel()->set_url_replacement_enabled(true);
231 model()->UpdatePermanentText();
233 // Select all the new text if the user had all the old text selected, or if
234 // there was no previous text (for new tab page URL replacement extensions).
235 // This makes one particular case better: the user clicks in the box to
236 // change it right before the permanent URL is changed. Since the new URL
237 // is still fully selected, the user's typing will replace the edit contents
238 // as they'd intended.
239 const bool was_select_all = IsSelectAll();
240 const bool was_reversed = GetSelectedRange().is_reversed();
242 RevertAll();
244 // Only select all when we have focus. If we don't have focus, selecting
245 // all is unnecessary since the selection will change on regaining focus,
246 // and can in fact cause artifacts, e.g. if the user is on the NTP and
247 // clicks a link to navigate, causing |was_select_all| to be vacuously true
248 // for the empty omnibox, and we then select all here, leading to the
249 // trailing portion of a long URL being scrolled into view. We could try
250 // and address cases like this, but it seems better to just not muck with
251 // things when the omnibox isn't focused to begin with.
252 if (was_select_all && model()->has_focus())
253 SelectAll(was_reversed);
254 } else if (old_security_level != security_level_) {
255 EmphasizeURLComponents();
259 base::string16 OmniboxViewViews::GetText() const {
260 // TODO(oshima): IME support
261 return text();
264 void OmniboxViewViews::SetUserText(const base::string16& text,
265 const base::string16& display_text,
266 bool update_popup) {
267 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
268 OmniboxView::SetUserText(text, display_text, update_popup);
271 void OmniboxViewViews::SetForcedQuery() {
272 const base::string16 current_text(text());
273 const size_t start = current_text.find_first_not_of(base::kWhitespaceUTF16);
274 if (start == base::string16::npos || (current_text[start] != '?'))
275 OmniboxView::SetUserText(base::ASCIIToUTF16("?"));
276 else
277 SelectRange(gfx::Range(current_text.size(), start + 1));
280 void OmniboxViewViews::GetSelectionBounds(
281 base::string16::size_type* start,
282 base::string16::size_type* end) const {
283 const gfx::Range range = GetSelectedRange();
284 *start = static_cast<size_t>(range.start());
285 *end = static_cast<size_t>(range.end());
288 void OmniboxViewViews::SelectAll(bool reversed) {
289 views::Textfield::SelectAll(reversed);
292 void OmniboxViewViews::RevertAll() {
293 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
294 OmniboxView::RevertAll();
297 void OmniboxViewViews::SetFocus() {
298 RequestFocus();
299 // Restore caret visibility if focus is explicitly requested. This is
300 // necessary because if we already have invisible focus, the RequestFocus()
301 // call above will short-circuit, preventing us from reaching
302 // OmniboxEditModel::OnSetFocus(), which handles restoring visibility when the
303 // omnibox regains focus after losing focus.
304 model()->SetCaretVisibility(true);
307 int OmniboxViewViews::GetTextWidth() const {
308 // Returns the width necessary to display the current text, including any
309 // necessary space for the cursor or border/margin.
310 return GetRenderText()->GetContentWidth() + GetInsets().width();
313 bool OmniboxViewViews::IsImeComposing() const {
314 return IsIMEComposing();
317 gfx::Size OmniboxViewViews::GetMinimumSize() const {
318 const int kMinCharacters = 10;
319 return gfx::Size(
320 GetFontList().GetExpectedTextWidth(kMinCharacters) + GetInsets().width(),
321 GetPreferredSize().height());
324 void OmniboxViewViews::OnNativeThemeChanged(const ui::NativeTheme* theme) {
325 views::Textfield::OnNativeThemeChanged(theme);
326 if (location_bar_view_) {
327 SetBackgroundColor(location_bar_view_->GetColor(
328 ToolbarModel::NONE, LocationBarView::BACKGROUND));
330 EmphasizeURLComponents();
333 void OmniboxViewViews::OnPaint(gfx::Canvas* canvas) {
334 Textfield::OnPaint(canvas);
335 if (!insert_char_time_.is_null()) {
336 UMA_HISTOGRAM_TIMES("Omnibox.CharTypedToRepaintLatency",
337 base::TimeTicks::Now() - insert_char_time_);
338 insert_char_time_ = base::TimeTicks();
342 void OmniboxViewViews::ExecuteCommand(int command_id, int event_flags) {
343 // In the base class, touch text selection is deactivated when a command is
344 // executed. Since we are not always calling the base class implementation
345 // here, we need to deactivate touch text selection here, too.
346 DestroyTouchSelection();
347 switch (command_id) {
348 // These commands don't invoke the popup via OnBefore/AfterPossibleChange().
349 case IDS_PASTE_AND_GO:
350 model()->PasteAndGo(GetClipboardText());
351 return;
352 case IDS_SHOW_URL:
353 controller()->ShowURL();
354 return;
355 case IDC_EDIT_SEARCH_ENGINES:
356 command_updater()->ExecuteCommand(command_id);
357 return;
358 case IDS_MOVE_DOWN:
359 case IDS_MOVE_UP:
360 model()->OnUpOrDownKeyPressed(command_id == IDS_MOVE_DOWN ? 1 : -1);
361 return;
363 // These commands do invoke the popup.
364 case IDS_APP_PASTE:
365 OnPaste();
366 return;
367 default:
368 if (Textfield::IsCommandIdEnabled(command_id)) {
369 // The Textfield code will invoke OnBefore/AfterPossibleChange() itself
370 // as necessary.
371 Textfield::ExecuteCommand(command_id, event_flags);
372 return;
374 OnBeforePossibleChange();
375 command_updater()->ExecuteCommand(command_id);
376 OnAfterPossibleChange();
377 return;
381 void OmniboxViewViews::SetTextAndSelectedRange(const base::string16& text,
382 const gfx::Range& range) {
383 SetText(text);
384 SelectRange(range);
387 base::string16 OmniboxViewViews::GetSelectedText() const {
388 // TODO(oshima): Support IME.
389 return views::Textfield::GetSelectedText();
392 void OmniboxViewViews::OnPaste() {
393 const base::string16 text(GetClipboardText());
394 if (!text.empty()) {
395 OnBeforePossibleChange();
396 // Record this paste, so we can do different behavior.
397 model()->OnPaste();
398 // Force a Paste operation to trigger the text_changed code in
399 // OnAfterPossibleChange(), even if identical contents are pasted.
400 text_before_change_.clear();
401 InsertOrReplaceText(text);
402 OnAfterPossibleChange();
406 bool OmniboxViewViews::HandleEarlyTabActions(const ui::KeyEvent& event) {
407 // This must run before accelerator handling invokes a focus change on tab.
408 // Note the parallel with SkipDefaultKeyEventProcessing above.
409 if (!views::FocusManager::IsTabTraversalKeyEvent(event))
410 return false;
412 if (model()->is_keyword_hint() && !event.IsShiftDown())
413 return model()->AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_TAB);
415 if (!model()->popup_model()->IsOpen())
416 return false;
418 if (event.IsShiftDown() &&
419 (model()->popup_model()->selected_line_state() ==
420 OmniboxPopupModel::KEYWORD))
421 model()->ClearKeyword();
422 else
423 model()->OnUpOrDownKeyPressed(event.IsShiftDown() ? -1 : 1);
425 return true;
428 void OmniboxViewViews::AccessibilitySetValue(const base::string16& new_value) {
429 SetUserText(new_value, new_value, true);
432 void OmniboxViewViews::SetWindowTextAndCaretPos(const base::string16& text,
433 size_t caret_pos,
434 bool update_popup,
435 bool notify_text_changed) {
436 const gfx::Range range(caret_pos, caret_pos);
437 SetTextAndSelectedRange(text, range);
439 if (update_popup)
440 UpdatePopup();
442 if (notify_text_changed)
443 TextChanged();
446 bool OmniboxViewViews::IsSelectAll() const {
447 // TODO(oshima): IME support.
448 return text() == GetSelectedText();
451 bool OmniboxViewViews::DeleteAtEndPressed() {
452 return delete_at_end_pressed_;
455 void OmniboxViewViews::UpdatePopup() {
456 model()->SetInputInProgress(true);
457 if (!model()->has_focus())
458 return;
460 // Prevent inline autocomplete when the caret isn't at the end of the text.
461 const gfx::Range sel = GetSelectedRange();
462 model()->StartAutocomplete(!sel.is_empty(), sel.GetMax() < text().length(),
463 false);
466 void OmniboxViewViews::ApplyCaretVisibility() {
467 SetCursorEnabled(model()->is_caret_visible());
470 void OmniboxViewViews::OnTemporaryTextMaybeChanged(
471 const base::string16& display_text,
472 bool save_original_selection,
473 bool notify_text_changed) {
474 if (save_original_selection)
475 saved_temporary_selection_ = GetSelectedRange();
477 SetWindowTextAndCaretPos(display_text, display_text.length(), false,
478 notify_text_changed);
481 bool OmniboxViewViews::OnInlineAutocompleteTextMaybeChanged(
482 const base::string16& display_text,
483 size_t user_text_length) {
484 if (display_text == text())
485 return false;
487 if (!IsIMEComposing()) {
488 gfx::Range range(display_text.size(), user_text_length);
489 SetTextAndSelectedRange(display_text, range);
490 } else if (location_bar_view_) {
491 location_bar_view_->SetImeInlineAutocompletion(
492 display_text.substr(user_text_length));
494 TextChanged();
495 return true;
498 void OmniboxViewViews::OnInlineAutocompleteTextCleared() {
499 // Hide the inline autocompletion for IME users.
500 if (location_bar_view_)
501 location_bar_view_->SetImeInlineAutocompletion(base::string16());
504 void OmniboxViewViews::OnRevertTemporaryText() {
505 SelectRange(saved_temporary_selection_);
506 // We got here because the user hit the Escape key. We explicitly don't call
507 // TextChanged(), since OmniboxPopupModel::ResetToDefaultMatch() has already
508 // been called by now, and it would've called TextChanged() if it was
509 // warranted.
512 void OmniboxViewViews::OnBeforePossibleChange() {
513 // Record our state.
514 text_before_change_ = text();
515 sel_before_change_ = GetSelectedRange();
516 ime_composing_before_change_ = IsIMEComposing();
519 bool OmniboxViewViews::OnAfterPossibleChange() {
520 // See if the text or selection have changed since OnBeforePossibleChange().
521 const base::string16 new_text = text();
522 const gfx::Range new_sel = GetSelectedRange();
523 const bool text_changed = (new_text != text_before_change_) ||
524 (ime_composing_before_change_ != IsIMEComposing());
525 const bool selection_differs =
526 !((sel_before_change_.is_empty() && new_sel.is_empty()) ||
527 sel_before_change_.EqualsIgnoringDirection(new_sel));
529 // When the user has deleted text, we don't allow inline autocomplete. Make
530 // sure to not flag cases like selecting part of the text and then pasting
531 // (or typing) the prefix of that selection. (We detect these by making
532 // sure the caret, which should be after any insertion, hasn't moved
533 // forward of the old selection start.)
534 const bool just_deleted_text =
535 (text_before_change_.length() > new_text.length()) &&
536 (new_sel.start() <= sel_before_change_.GetMin());
538 const bool something_changed = model()->OnAfterPossibleChange(
539 text_before_change_, new_text, new_sel.start(), new_sel.end(),
540 selection_differs, text_changed, just_deleted_text, !IsIMEComposing());
542 // If only selection was changed, we don't need to call model()'s
543 // OnChanged() method, which is called in TextChanged().
544 // But we still need to call EmphasizeURLComponents() to make sure the text
545 // attributes are updated correctly.
546 if (something_changed && text_changed)
547 TextChanged();
548 else if (selection_differs)
549 EmphasizeURLComponents();
550 else if (delete_at_end_pressed_)
551 model()->OnChanged();
553 return something_changed;
556 gfx::NativeView OmniboxViewViews::GetNativeView() const {
557 return GetWidget()->GetNativeView();
560 gfx::NativeView OmniboxViewViews::GetRelativeWindowForPopup() const {
561 return GetWidget()->GetTopLevelWidget()->GetNativeView();
564 void OmniboxViewViews::SetGrayTextAutocompletion(const base::string16& input) {
565 if (location_bar_view_)
566 location_bar_view_->SetGrayTextAutocompletion(input);
569 base::string16 OmniboxViewViews::GetGrayTextAutocompletion() const {
570 return location_bar_view_ ?
571 location_bar_view_->GetGrayTextAutocompletion() : base::string16();
574 int OmniboxViewViews::GetWidth() const {
575 return location_bar_view_ ? location_bar_view_->width() : 0;
578 bool OmniboxViewViews::IsImeShowingPopup() const {
579 #if defined(OS_CHROMEOS)
580 return ime_candidate_window_open_;
581 #else
582 const views::InputMethod* input_method = this->GetInputMethod();
583 return input_method && input_method->IsCandidatePopupOpen();
584 #endif
587 void OmniboxViewViews::ShowImeIfNeeded() {
588 GetInputMethod()->ShowImeIfNeeded();
591 void OmniboxViewViews::OnMatchOpened(const AutocompleteMatch& match,
592 content::WebContents* web_contents) {
593 extensions::MaybeShowExtensionControlledSearchNotification(
594 profile(), web_contents, match);
597 int OmniboxViewViews::GetOmniboxTextLength() const {
598 // TODO(oshima): Support IME.
599 return static_cast<int>(text().length());
602 void OmniboxViewViews::EmphasizeURLComponents() {
603 if (!location_bar_view_)
604 return;
605 // See whether the contents are a URL with a non-empty host portion, which we
606 // should emphasize. To check for a URL, rather than using the type returned
607 // by Parse(), ask the model, which will check the desired page transition for
608 // this input. This can tell us whether an UNKNOWN input string is going to
609 // be treated as a search or a navigation, and is the same method the Paste
610 // And Go system uses.
611 url::Component scheme, host;
612 AutocompleteInput::ParseForEmphasizeComponents(
613 text(), ChromeAutocompleteSchemeClassifier(profile()), &scheme, &host);
614 bool grey_out_url = text().substr(scheme.begin, scheme.len) ==
615 base::UTF8ToUTF16(extensions::kExtensionScheme);
616 bool grey_base = model()->CurrentTextIsURL() &&
617 (host.is_nonempty() || grey_out_url);
618 SetColor(location_bar_view_->GetColor(
619 security_level_,
620 grey_base ? LocationBarView::DEEMPHASIZED_TEXT : LocationBarView::TEXT));
621 if (grey_base && !grey_out_url) {
622 ApplyColor(
623 location_bar_view_->GetColor(security_level_, LocationBarView::TEXT),
624 gfx::Range(host.begin, host.end()));
627 // Emphasize the scheme for security UI display purposes (if necessary).
628 // Note that we check CurrentTextIsURL() because if we're replacing search
629 // URLs with search terms, we may have a non-URL even when the user is not
630 // editing; and in some cases, e.g. for "site:foo.com" searches, the parser
631 // may have incorrectly identified a qualifier as a scheme.
632 SetStyle(gfx::DIAGONAL_STRIKE, false);
633 if (!model()->user_input_in_progress() && model()->CurrentTextIsURL() &&
634 scheme.is_nonempty() && (security_level_ != ToolbarModel::NONE)) {
635 SkColor security_color = location_bar_view_->GetColor(
636 security_level_, LocationBarView::SECURITY_TEXT);
637 const bool strike = (security_level_ == ToolbarModel::SECURITY_ERROR);
638 const gfx::Range scheme_range(scheme.begin, scheme.end());
639 ApplyColor(security_color, scheme_range);
640 ApplyStyle(gfx::DIAGONAL_STRIKE, strike, scheme_range);
644 bool OmniboxViewViews::OnKeyReleased(const ui::KeyEvent& event) {
645 // The omnibox contents may change while the control key is pressed.
646 if (event.key_code() == ui::VKEY_CONTROL)
647 model()->OnControlKeyChanged(false);
648 return views::Textfield::OnKeyReleased(event);
651 bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id) const {
652 return command_id == IDS_PASTE_AND_GO;
655 base::string16 OmniboxViewViews::GetLabelForCommandId(int command_id) const {
656 DCHECK_EQ(IDS_PASTE_AND_GO, command_id);
657 return l10n_util::GetStringUTF16(
658 model()->IsPasteAndSearch(GetClipboardText()) ?
659 IDS_PASTE_AND_SEARCH : IDS_PASTE_AND_GO);
662 const char* OmniboxViewViews::GetClassName() const {
663 return kViewClassName;
666 bool OmniboxViewViews::OnMousePressed(const ui::MouseEvent& event) {
667 select_all_on_mouse_release_ =
668 (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) &&
669 (!HasFocus() || (model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE));
670 if (select_all_on_mouse_release_) {
671 // Restore caret visibility whenever the user clicks in the omnibox in a way
672 // that would give it focus. We must handle this case separately here
673 // because if the omnibox currently has invisible focus, the mouse event
674 // won't trigger either SetFocus() or OmniboxEditModel::OnSetFocus().
675 model()->SetCaretVisibility(true);
677 // When we're going to select all on mouse release, invalidate any saved
678 // selection lest restoring it fights with the "select all" action. It's
679 // possible to later set select_all_on_mouse_release_ back to false, but
680 // that happens for things like dragging, which are cases where having
681 // invalidated this saved selection is still OK.
682 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
684 return views::Textfield::OnMousePressed(event);
687 bool OmniboxViewViews::OnMouseDragged(const ui::MouseEvent& event) {
688 if (ExceededDragThreshold(event.location() - last_click_location()))
689 select_all_on_mouse_release_ = false;
691 if (HasTextBeingDragged())
692 CloseOmniboxPopup();
694 return views::Textfield::OnMouseDragged(event);
697 void OmniboxViewViews::OnMouseReleased(const ui::MouseEvent& event) {
698 views::Textfield::OnMouseReleased(event);
699 if (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) {
700 // When the user has clicked and released to give us focus, select all
701 // unless we're omitting the URL (in which case refining an existing query
702 // is common enough that we do click-to-place-cursor).
703 if (select_all_on_mouse_release_ &&
704 !controller()->GetToolbarModel()->WouldReplaceURL()) {
705 // Select all in the reverse direction so as not to scroll the caret
706 // into view and shift the contents jarringly.
707 SelectAll(true);
710 select_all_on_mouse_release_ = false;
713 bool OmniboxViewViews::OnKeyPressed(const ui::KeyEvent& event) {
714 // Skip processing of [Alt]+<num-pad digit> Unicode alt key codes.
715 // Otherwise, if num-lock is off, the events are handled as [Up], [Down], etc.
716 if (event.IsUnicodeKeyCode())
717 return views::Textfield::OnKeyPressed(event);
719 const bool shift = event.IsShiftDown();
720 const bool control = event.IsControlDown();
721 const bool alt = event.IsAltDown() || event.IsAltGrDown();
722 switch (event.key_code()) {
723 case ui::VKEY_RETURN:
724 model()->AcceptInput(alt ? NEW_FOREGROUND_TAB : CURRENT_TAB, false);
725 return true;
726 case ui::VKEY_ESCAPE:
727 return model()->OnEscapeKeyPressed();
728 case ui::VKEY_CONTROL:
729 model()->OnControlKeyChanged(true);
730 break;
731 case ui::VKEY_DELETE:
732 if (shift && model()->popup_model()->IsOpen())
733 model()->popup_model()->TryDeletingCurrentItem();
734 break;
735 case ui::VKEY_UP:
736 if (!read_only()) {
737 model()->OnUpOrDownKeyPressed(-1);
738 return true;
740 break;
741 case ui::VKEY_DOWN:
742 if (!read_only()) {
743 model()->OnUpOrDownKeyPressed(1);
744 return true;
746 break;
747 case ui::VKEY_PRIOR:
748 if (control || alt || shift)
749 return false;
750 model()->OnUpOrDownKeyPressed(-1 * model()->result().size());
751 return true;
752 case ui::VKEY_NEXT:
753 if (control || alt || shift)
754 return false;
755 model()->OnUpOrDownKeyPressed(model()->result().size());
756 return true;
757 case ui::VKEY_V:
758 if (control && !alt && !read_only()) {
759 ExecuteCommand(IDS_APP_PASTE, 0);
760 return true;
762 break;
763 case ui::VKEY_INSERT:
764 if (shift && !control && !read_only()) {
765 ExecuteCommand(IDS_APP_PASTE, 0);
766 return true;
768 break;
769 default:
770 break;
773 return views::Textfield::OnKeyPressed(event) || HandleEarlyTabActions(event);
776 void OmniboxViewViews::OnGestureEvent(ui::GestureEvent* event) {
777 if (!HasFocus() && event->type() == ui::ET_GESTURE_TAP_DOWN) {
778 select_all_on_gesture_tap_ = true;
780 // If we're trying to select all on tap, invalidate any saved selection lest
781 // restoring it fights with the "select all" action.
782 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
785 views::Textfield::OnGestureEvent(event);
787 if (select_all_on_gesture_tap_ && event->type() == ui::ET_GESTURE_TAP)
788 SelectAll(true);
790 if (event->type() == ui::ET_GESTURE_TAP ||
791 event->type() == ui::ET_GESTURE_TAP_CANCEL ||
792 event->type() == ui::ET_GESTURE_TWO_FINGER_TAP ||
793 event->type() == ui::ET_GESTURE_SCROLL_BEGIN ||
794 event->type() == ui::ET_GESTURE_PINCH_BEGIN ||
795 event->type() == ui::ET_GESTURE_LONG_PRESS ||
796 event->type() == ui::ET_GESTURE_LONG_TAP) {
797 select_all_on_gesture_tap_ = false;
801 void OmniboxViewViews::AboutToRequestFocusFromTabTraversal(bool reverse) {
802 views::Textfield::AboutToRequestFocusFromTabTraversal(reverse);
805 bool OmniboxViewViews::SkipDefaultKeyEventProcessing(
806 const ui::KeyEvent& event) {
807 if (views::FocusManager::IsTabTraversalKeyEvent(event) &&
808 ((model()->is_keyword_hint() && !event.IsShiftDown()) ||
809 model()->popup_model()->IsOpen())) {
810 return true;
812 if (event.key_code() == ui::VKEY_ESCAPE)
813 return model()->WillHandleEscapeKey();
814 return Textfield::SkipDefaultKeyEventProcessing(event);
817 void OmniboxViewViews::GetAccessibleState(ui::AXViewState* state) {
818 state->role = ui::AX_ROLE_TEXT_FIELD;
819 state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_LOCATION);
820 state->value = GetText();
822 base::string16::size_type entry_start;
823 base::string16::size_type entry_end;
824 GetSelectionBounds(&entry_start, &entry_end);
825 state->selection_start = entry_start;
826 state->selection_end = entry_end;
828 if (popup_window_mode_) {
829 state->AddStateFlag(ui::AX_STATE_READ_ONLY);
830 } else {
831 state->set_value_callback =
832 base::Bind(&OmniboxViewViews::AccessibilitySetValue,
833 weak_ptr_factory_.GetWeakPtr());
837 void OmniboxViewViews::OnFocus() {
838 views::Textfield::OnFocus();
839 // TODO(oshima): Get control key state.
840 model()->OnSetFocus(false);
841 // Don't call controller()->OnSetFocus, this view has already acquired focus.
843 // Restore the selection we saved in OnBlur() if it's still valid.
844 if (saved_selection_for_focus_change_.IsValid()) {
845 SelectRange(saved_selection_for_focus_change_);
846 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
850 void OmniboxViewViews::OnBlur() {
851 // Save the user's existing selection to restore it later.
852 saved_selection_for_focus_change_ = GetSelectedRange();
854 views::Textfield::OnBlur();
855 model()->OnWillKillFocus();
857 // If ZeroSuggest is active, we may have refused to show an update to the
858 // underlying permanent URL that happened while the popup was open, so
859 // revert to ensure that update is shown now. Otherwise, make sure to call
860 // CloseOmniboxPopup() unconditionally, so that if ZeroSuggest is in the midst
861 // of running but hasn't yet opened the popup, it will be halted.
862 if (!model()->user_input_in_progress() && model()->popup_model()->IsOpen())
863 RevertAll();
864 else
865 CloseOmniboxPopup();
867 // Tell the model to reset itself.
868 model()->OnKillFocus();
870 // Make sure the beginning of the text is visible.
871 SelectRange(gfx::Range(0));
874 bool OmniboxViewViews::IsCommandIdEnabled(int command_id) const {
875 if (command_id == IDS_APP_PASTE)
876 return !read_only() && !GetClipboardText().empty();
877 if (command_id == IDS_PASTE_AND_GO)
878 return !read_only() && model()->CanPasteAndGo(GetClipboardText());
879 if (command_id == IDS_SHOW_URL)
880 return controller()->GetToolbarModel()->WouldReplaceURL();
881 return command_id == IDS_MOVE_DOWN || command_id == IDS_MOVE_UP ||
882 Textfield::IsCommandIdEnabled(command_id) ||
883 command_updater()->IsCommandEnabled(command_id);
886 base::string16 OmniboxViewViews::GetSelectionClipboardText() const {
887 return SanitizeTextForPaste(Textfield::GetSelectionClipboardText());
890 void OmniboxViewViews::DoInsertChar(base::char16 ch) {
891 // If |insert_char_time_| is not null, there's a pending insert char operation
892 // that hasn't been painted yet. Keep the earlier time.
893 if (insert_char_time_.is_null())
894 insert_char_time_ = base::TimeTicks::Now();
895 Textfield::DoInsertChar(ch);
898 #if defined(OS_CHROMEOS)
899 void OmniboxViewViews::CandidateWindowOpened(
900 chromeos::input_method::InputMethodManager* manager) {
901 ime_candidate_window_open_ = true;
904 void OmniboxViewViews::CandidateWindowClosed(
905 chromeos::input_method::InputMethodManager* manager) {
906 ime_candidate_window_open_ = false;
908 #endif
910 void OmniboxViewViews::ContentsChanged(views::Textfield* sender,
911 const base::string16& new_contents) {
914 bool OmniboxViewViews::HandleKeyEvent(views::Textfield* textfield,
915 const ui::KeyEvent& event) {
916 delete_at_end_pressed_ = false;
918 if (event.key_code() == ui::VKEY_BACK) {
919 // No extra handling is needed in keyword search mode, if there is a
920 // non-empty selection, or if the cursor is not leading the text.
921 if (model()->is_keyword_hint() || model()->keyword().empty() ||
922 HasSelection() || GetCursorPosition() != 0)
923 return false;
924 model()->ClearKeyword();
925 return true;
928 if (event.key_code() == ui::VKEY_DELETE && !event.IsAltDown()) {
929 delete_at_end_pressed_ =
930 (!HasSelection() && GetCursorPosition() == text().length());
933 // Handle the right-arrow key for LTR text and the left-arrow key for RTL text
934 // if there is gray text that needs to be committed.
935 if (GetCursorPosition() == text().length()) {
936 base::i18n::TextDirection direction = GetTextDirection();
937 if ((direction == base::i18n::LEFT_TO_RIGHT &&
938 event.key_code() == ui::VKEY_RIGHT) ||
939 (direction == base::i18n::RIGHT_TO_LEFT &&
940 event.key_code() == ui::VKEY_LEFT)) {
941 return model()->CommitSuggestedText();
945 return false;
948 void OmniboxViewViews::OnBeforeUserAction(views::Textfield* sender) {
949 OnBeforePossibleChange();
952 void OmniboxViewViews::OnAfterUserAction(views::Textfield* sender) {
953 OnAfterPossibleChange();
956 void OmniboxViewViews::OnAfterCutOrCopy(ui::ClipboardType clipboard_type) {
957 ui::Clipboard* cb = ui::Clipboard::GetForCurrentThread();
958 base::string16 selected_text;
959 cb->ReadText(clipboard_type, &selected_text);
960 GURL url;
961 bool write_url;
962 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
963 &selected_text, &url, &write_url);
964 if (IsSelectAll())
965 UMA_HISTOGRAM_COUNTS(OmniboxEditModel::kCutOrCopyAllTextHistogram, 1);
967 if (write_url) {
968 BookmarkNodeData data;
969 data.ReadFromTuple(url, selected_text);
970 data.WriteToClipboard(clipboard_type);
971 } else {
972 ui::ScopedClipboardWriter scoped_clipboard_writer(clipboard_type);
973 scoped_clipboard_writer.WriteText(selected_text);
977 void OmniboxViewViews::OnWriteDragData(ui::OSExchangeData* data) {
978 GURL url;
979 bool write_url;
980 bool is_all_selected = IsSelectAll();
981 base::string16 selected_text = GetSelectedText();
982 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), is_all_selected,
983 &selected_text, &url, &write_url);
984 data->SetString(selected_text);
985 if (write_url) {
986 gfx::Image favicon;
987 base::string16 title = selected_text;
988 if (is_all_selected)
989 model()->GetDataForURLExport(&url, &title, &favicon);
990 button_drag_utils::SetURLAndDragImage(url, title, favicon.AsImageSkia(),
991 NULL, data, GetWidget());
992 data->SetURL(url, title);
996 void OmniboxViewViews::OnGetDragOperationsForTextfield(int* drag_operations) {
997 base::string16 selected_text = GetSelectedText();
998 GURL url;
999 bool write_url;
1000 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
1001 &selected_text, &url, &write_url);
1002 if (write_url)
1003 *drag_operations |= ui::DragDropTypes::DRAG_LINK;
1006 void OmniboxViewViews::AppendDropFormats(
1007 int* formats,
1008 std::set<ui::OSExchangeData::CustomFormat>* custom_formats) {
1009 *formats = *formats | ui::OSExchangeData::URL;
1012 int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) {
1013 if (HasTextBeingDragged())
1014 return ui::DragDropTypes::DRAG_NONE;
1016 if (data.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)) {
1017 GURL url;
1018 base::string16 title;
1019 if (data.GetURLAndTitle(
1020 ui::OSExchangeData::CONVERT_FILENAMES, &url, &title)) {
1021 base::string16 text(
1022 StripJavascriptSchemas(base::UTF8ToUTF16(url.spec())));
1023 if (model()->CanPasteAndGo(text)) {
1024 model()->PasteAndGo(text);
1025 return ui::DragDropTypes::DRAG_COPY;
1028 } else if (data.HasString()) {
1029 base::string16 text;
1030 if (data.GetString(&text)) {
1031 base::string16 collapsed_text(base::CollapseWhitespace(text, true));
1032 if (model()->CanPasteAndGo(collapsed_text))
1033 model()->PasteAndGo(collapsed_text);
1034 return ui::DragDropTypes::DRAG_COPY;
1038 return ui::DragDropTypes::DRAG_NONE;
1041 void OmniboxViewViews::UpdateContextMenu(ui::SimpleMenuModel* menu_contents) {
1042 int paste_position = menu_contents->GetIndexOfCommandId(IDS_APP_PASTE);
1043 DCHECK_GE(paste_position, 0);
1044 menu_contents->InsertItemWithStringIdAt(
1045 paste_position + 1, IDS_PASTE_AND_GO, IDS_PASTE_AND_GO);
1047 menu_contents->AddSeparator(ui::NORMAL_SEPARATOR);
1049 if (chrome::IsQueryExtractionEnabled()) {
1050 int select_all_position = menu_contents->GetIndexOfCommandId(
1051 IDS_APP_SELECT_ALL);
1052 DCHECK_GE(select_all_position, 0);
1053 menu_contents->InsertItemWithStringIdAt(
1054 select_all_position + 1, IDS_SHOW_URL, IDS_SHOW_URL);
1057 // Minor note: We use IDC_ for command id here while the underlying textfield
1058 // is using IDS_ for all its command ids. This is because views cannot depend
1059 // on IDC_ for now.
1060 menu_contents->AddItemWithStringId(IDC_EDIT_SEARCH_ENGINES,
1061 IDS_EDIT_SEARCH_ENGINES);