1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/ui/views/omnibox/omnibox_view_views.h"
7 #include "base/command_line.h"
8 #include "base/logging.h"
9 #include "base/metrics/histogram.h"
10 #include "base/strings/string_util.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "chrome/app/chrome_command_ids.h"
13 #include "chrome/browser/autocomplete/autocomplete_input.h"
14 #include "chrome/browser/autocomplete/autocomplete_match.h"
15 #include "chrome/browser/bookmarks/bookmark_node_data.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/browser/ui/views/website_settings/website_settings_popup_view.h"
26 #include "chrome/common/chrome_switches.h"
27 #include "content/public/browser/web_contents.h"
28 #include "extensions/common/constants.h"
29 #include "grit/app_locale_settings.h"
30 #include "grit/generated_resources.h"
31 #include "grit/ui_strings.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/base/resource/resource_bundle.h"
43 #include "ui/events/event.h"
44 #include "ui/gfx/animation/slide_animation.h"
45 #include "ui/gfx/canvas.h"
46 #include "ui/gfx/font_list.h"
47 #include "ui/gfx/selection_model.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"
58 #include "chrome/browser/browser_process.h"
62 #include "ui/aura/client/focus_client.h"
63 #include "ui/aura/window_event_dispatcher.h"
64 #include "ui/compositor/layer.h"
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 virtual ~OmniboxState();
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() {}
101 // We'd like to set the text input type to TEXT_INPUT_TYPE_URL, because this
102 // triggers URL-specific layout in software keyboards, e.g. adding top-level "/"
103 // and ".com" keys for English. However, this also causes IMEs to default to
104 // Latin character mode, which makes entering search queries difficult for IME
105 // users. Therefore, we try to guess whether an IME will be used based on the
106 // application language, and set the input type accordingly.
107 ui::TextInputType DetermineTextInputType() {
109 DCHECK(g_browser_process);
110 const std::string& locale = g_browser_process->GetApplicationLocale();
111 const std::string& language = locale.substr(0, 2);
112 // Assume CJK + Thai users are using an IME.
113 if (language == "ja" ||
117 return ui::TEXT_INPUT_TYPE_SEARCH;
119 return ui::TEXT_INPUT_TYPE_URL;
122 bool IsOmniboxAutoCompletionForImeEnabled() {
123 return !CommandLine::ForCurrentProcess()->HasSwitch(
124 switches::kDisableOmniboxAutoCompletionForIme);
130 const char OmniboxViewViews::kViewClassName[] = "OmniboxViewViews";
132 OmniboxViewViews::OmniboxViewViews(OmniboxEditController* controller,
134 CommandUpdater* command_updater,
135 bool popup_window_mode,
136 LocationBarView* location_bar,
137 const gfx::FontList& font_list)
138 : OmniboxView(profile, 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 SetBorder(views::Border::NullBorder());
149 set_id(VIEW_ID_OMNIBOX);
150 SetFontList(font_list);
153 OmniboxViewViews::~OmniboxViewViews() {
154 #if defined(OS_CHROMEOS)
155 chromeos::input_method::InputMethodManager::Get()->
156 RemoveCandidateWindowObserver(this);
159 // Explicitly teardown members which have a reference to us. Just to be safe
160 // we want them to be destroyed before destroying any other internal state.
164 ////////////////////////////////////////////////////////////////////////////////
165 // OmniboxViewViews public:
167 void OmniboxViewViews::Init() {
168 set_controller(this);
169 SetTextInputType(DetermineTextInputType());
170 SetBackgroundColor(location_bar_view_->GetColor(
171 ToolbarModel::NONE, LocationBarView::BACKGROUND));
173 if (popup_window_mode_)
176 // Initialize the popup view using the same font.
177 popup_view_.reset(OmniboxPopupContentsView::Create(
178 GetFontList(), this, model(), location_bar_view_));
180 #if defined(OS_CHROMEOS)
181 chromeos::input_method::InputMethodManager::Get()->
182 AddCandidateWindowObserver(this);
185 fade_in_animation_.reset(new gfx::SlideAnimation(this));
186 fade_in_animation_->SetTweenType(gfx::Tween::LINEAR);
187 fade_in_animation_->SetSlideDuration(300);
190 void OmniboxViewViews::FadeIn() {
191 fade_in_animation_->Show();
194 ////////////////////////////////////////////////////////////////////////////////
195 // OmniboxViewViews, views::Textfield implementation:
197 const char* OmniboxViewViews::GetClassName() const {
198 return kViewClassName;
201 void OmniboxViewViews::OnPaint(gfx::Canvas* canvas) {
202 if (fade_in_animation_->is_animating()) {
203 canvas->SaveLayerAlpha(static_cast<uint8>(
204 fade_in_animation_->CurrentValueBetween(0, 255)));
205 views::Textfield::OnPaint(canvas);
208 views::Textfield::OnPaint(canvas);
212 bool OmniboxViewViews::OnMousePressed(const ui::MouseEvent& event) {
213 select_all_on_mouse_release_ =
214 (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) &&
215 (!HasFocus() || (model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE));
216 if (select_all_on_mouse_release_) {
217 // Restore caret visibility whenever the user clicks in the omnibox in a way
218 // that would give it focus. We must handle this case separately here
219 // because if the omnibox currently has invisible focus, the mouse event
220 // won't trigger either SetFocus() or OmniboxEditModel::OnSetFocus().
221 model()->SetCaretVisibility(true);
223 // When we're going to select all on mouse release, invalidate any saved
224 // selection lest restoring it fights with the "select all" action. It's
225 // possible to later set select_all_on_mouse_release_ back to false, but
226 // that happens for things like dragging, which are cases where having
227 // invalidated this saved selection is still OK.
228 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
230 return views::Textfield::OnMousePressed(event);
233 bool OmniboxViewViews::OnMouseDragged(const ui::MouseEvent& event) {
234 if (ExceededDragThreshold(event.location() - last_click_location()))
235 select_all_on_mouse_release_ = false;
236 return views::Textfield::OnMouseDragged(event);
239 void OmniboxViewViews::OnMouseReleased(const ui::MouseEvent& event) {
240 views::Textfield::OnMouseReleased(event);
241 if (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) {
242 // When the user has clicked and released to give us focus, select all
243 // unless we're omitting the URL (in which case refining an existing query
244 // is common enough that we do click-to-place-cursor).
245 if (select_all_on_mouse_release_ &&
246 !controller()->GetToolbarModel()->WouldReplaceURL()) {
247 // Select all in the reverse direction so as not to scroll the caret
248 // into view and shift the contents jarringly.
252 HandleOriginChipMouseRelease();
254 select_all_on_mouse_release_ = false;
257 bool OmniboxViewViews::OnKeyPressed(const ui::KeyEvent& event) {
258 // Skip processing of [Alt]+<num-pad digit> Unicode alt key codes.
259 // Otherwise, if num-lock is off, the events are handled as [Up], [Down], etc.
260 if (event.IsUnicodeKeyCode())
261 return views::Textfield::OnKeyPressed(event);
263 const bool shift = event.IsShiftDown();
264 const bool control = event.IsControlDown();
265 const bool alt = event.IsAltDown() || event.IsAltGrDown();
266 switch (event.key_code()) {
267 case ui::VKEY_RETURN:
268 model()->AcceptInput(alt ? NEW_FOREGROUND_TAB : CURRENT_TAB, false);
270 case ui::VKEY_ESCAPE:
271 return model()->OnEscapeKeyPressed();
272 case ui::VKEY_CONTROL:
273 model()->OnControlKeyChanged(true);
275 case ui::VKEY_DELETE:
276 if (shift && model()->popup_model()->IsOpen())
277 model()->popup_model()->TryDeletingCurrentItem();
281 model()->OnUpOrDownKeyPressed(-1);
287 model()->OnUpOrDownKeyPressed(1);
292 if (control || alt || shift)
294 model()->OnUpOrDownKeyPressed(-1 * model()->result().size());
297 if (control || alt || shift)
299 model()->OnUpOrDownKeyPressed(model()->result().size());
302 if (control && !alt && !read_only()) {
303 ExecuteCommand(IDS_APP_PASTE, 0);
307 case ui::VKEY_INSERT:
308 if (shift && !control && !read_only()) {
309 ExecuteCommand(IDS_APP_PASTE, 0);
317 return views::Textfield::OnKeyPressed(event) || HandleEarlyTabActions(event);
320 bool OmniboxViewViews::OnKeyReleased(const ui::KeyEvent& event) {
321 // The omnibox contents may change while the control key is pressed.
322 if (event.key_code() == ui::VKEY_CONTROL)
323 model()->OnControlKeyChanged(false);
324 return views::Textfield::OnKeyReleased(event);
327 void OmniboxViewViews::OnGestureEvent(ui::GestureEvent* event) {
328 if (!HasFocus() && event->type() == ui::ET_GESTURE_TAP_DOWN) {
329 select_all_on_gesture_tap_ = true;
331 // If we're trying to select all on tap, invalidate any saved selection lest
332 // restoring it fights with the "select all" action.
333 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
336 if (select_all_on_gesture_tap_ && event->type() == ui::ET_GESTURE_TAP)
339 if (event->type() == ui::ET_GESTURE_TAP ||
340 event->type() == ui::ET_GESTURE_TAP_CANCEL ||
341 event->type() == ui::ET_GESTURE_TWO_FINGER_TAP ||
342 event->type() == ui::ET_GESTURE_SCROLL_BEGIN ||
343 event->type() == ui::ET_GESTURE_PINCH_BEGIN ||
344 event->type() == ui::ET_GESTURE_LONG_PRESS ||
345 event->type() == ui::ET_GESTURE_LONG_TAP) {
346 select_all_on_gesture_tap_ = false;
349 views::Textfield::OnGestureEvent(event);
352 void OmniboxViewViews::AboutToRequestFocusFromTabTraversal(bool reverse) {
353 // Tabbing into the omnibox should affect the origin chip in the same way
354 // clicking it should.
355 HandleOriginChipMouseRelease();
358 bool OmniboxViewViews::SkipDefaultKeyEventProcessing(
359 const ui::KeyEvent& event) {
360 if (views::FocusManager::IsTabTraversalKeyEvent(event) &&
361 ((model()->is_keyword_hint() && !event.IsShiftDown()) ||
362 model()->popup_model()->IsOpen())) {
365 return Textfield::SkipDefaultKeyEventProcessing(event);
368 void OmniboxViewViews::GetAccessibleState(ui::AXViewState* state) {
369 location_bar_view_->GetAccessibleState(state);
370 state->role = ui::AX_ROLE_TEXT_FIELD;
373 bool OmniboxViewViews::HandleEarlyTabActions(const ui::KeyEvent& event) {
374 // This must run before acclerator handling invokes a focus change on tab.
375 // Note the parallel with SkipDefaultKeyEventProcessing above.
376 if (views::FocusManager::IsTabTraversalKeyEvent(event)) {
377 if (model()->is_keyword_hint() && !event.IsShiftDown()) {
378 model()->AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_TAB);
381 if (model()->popup_model()->IsOpen()) {
382 if (event.IsShiftDown() &&
383 model()->popup_model()->selected_line_state() ==
384 OmniboxPopupModel::KEYWORD) {
385 model()->ClearKeyword(text());
387 model()->OnUpOrDownKeyPressed(event.IsShiftDown() ? -1 : 1);
396 void OmniboxViewViews::OnFocus() {
397 views::Textfield::OnFocus();
398 // TODO(oshima): Get control key state.
399 model()->OnSetFocus(false);
400 // Don't call controller()->OnSetFocus, this view has already acquired focus.
402 // Restore the selection we saved in OnBlur() if it's still valid.
403 if (saved_selection_for_focus_change_.IsValid()) {
404 SelectRange(saved_selection_for_focus_change_);
405 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
409 void OmniboxViewViews::OnBlur() {
410 // Save the user's existing selection to restore it later.
411 saved_selection_for_focus_change_ = GetSelectedRange();
413 views::Textfield::OnBlur();
414 gfx::NativeView native_view = NULL;
415 #if defined(USE_AURA)
416 views::Widget* widget = GetWidget();
418 aura::client::FocusClient* client =
419 aura::client::GetFocusClient(widget->GetNativeView());
421 native_view = client->GetFocusedWindow();
424 model()->OnWillKillFocus(native_view);
428 // Tell the model to reset itself.
429 model()->OnKillFocus();
431 // Ignore loss of focus if we lost focus because the website settings popup
432 // is open. When the popup is destroyed, focus will return to the Omnibox.
433 if (!WebsiteSettingsPopupView::IsPopupShowing())
436 // Make sure the beginning of the text is visible.
437 SelectRange(gfx::Range(0));
440 base::string16 OmniboxViewViews::GetSelectionClipboardText() const {
441 return SanitizeTextForPaste(Textfield::GetSelectionClipboardText());
444 ////////////////////////////////////////////////////////////////////////////////
445 // OmniboxViewViews, OmniboxView implementation:
447 void OmniboxViewViews::SaveStateToTab(content::WebContents* tab) {
450 // We don't want to keep the IME status, so force quit the current
451 // session here. It may affect the selection status, so order is
453 if (IsIMEComposing()) {
454 GetTextInputClient()->ConfirmCompositionText();
455 GetInputMethod()->CancelComposition(this);
458 // NOTE: GetStateForTabSwitch() may affect GetSelectedRange(), so order is
460 OmniboxEditModel::State state = model()->GetStateForTabSwitch();
461 tab->SetUserData(OmniboxState::kKey, new OmniboxState(
462 state, GetSelectedRange(), saved_selection_for_focus_change_));
465 void OmniboxViewViews::OnTabChanged(const content::WebContents* web_contents) {
466 security_level_ = controller()->GetToolbarModel()->GetSecurityLevel(false);
468 const OmniboxState* state = static_cast<OmniboxState*>(
469 web_contents->GetUserData(&OmniboxState::kKey));
470 model()->RestoreState(state ? &state->model_state : NULL);
472 // This assumes that the omnibox has already been focused or blurred as
473 // appropriate; otherwise, a subsequent OnFocus() or OnBlur() call could
474 // goof up the selection. See comments at the end of
475 // BrowserView::ActiveTabChanged().
476 SelectRange(state->selection);
477 saved_selection_for_focus_change_ = state->saved_selection_for_focus_change;
480 // TODO(msw|oshima): Consider saving/restoring edit history.
484 void OmniboxViewViews::Update() {
485 if (chrome::ShouldDisplayOriginChip() || chrome::ShouldDisplayOriginChipV2())
486 set_placeholder_text(GetHintText());
488 const ToolbarModel::SecurityLevel old_security_level = security_level_;
489 security_level_ = controller()->GetToolbarModel()->GetSecurityLevel(false);
490 if (model()->UpdatePermanentText()) {
491 // Something visibly changed. Re-enable URL replacement.
492 controller()->GetToolbarModel()->set_url_replacement_enabled(true);
493 model()->UpdatePermanentText();
495 // Select all the new text if the user had all the old text selected, or if
496 // there was no previous text (for new tab page URL replacement extensions).
497 // This makes one particular case better: the user clicks in the box to
498 // change it right before the permanent URL is changed. Since the new URL
499 // is still fully selected, the user's typing will replace the edit contents
500 // as they'd intended.
501 const bool was_select_all = IsSelectAll();
502 const bool was_reversed = GetSelectedRange().is_reversed();
506 // Only select all when we have focus. If we don't have focus, selecting
507 // all is unnecessary since the selection will change on regaining focus,
508 // and can in fact cause artifacts, e.g. if the user is on the NTP and
509 // clicks a link to navigate, causing |was_select_all| to be vacuously true
510 // for the empty omnibox, and we then select all here, leading to the
511 // trailing portion of a long URL being scrolled into view. We could try
512 // and address cases like this, but it seems better to just not muck with
513 // things when the omnibox isn't focused to begin with.
514 if (was_select_all && model()->has_focus())
515 SelectAll(was_reversed);
516 } else if (old_security_level != security_level_) {
517 EmphasizeURLComponents();
521 base::string16 OmniboxViewViews::GetText() const {
522 // TODO(oshima): IME support
526 void OmniboxViewViews::SetUserText(const base::string16& text,
527 const base::string16& display_text,
529 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
530 OmniboxView::SetUserText(text, display_text, update_popup);
533 void OmniboxViewViews::SetWindowTextAndCaretPos(const base::string16& text,
536 bool notify_text_changed) {
537 const gfx::Range range(caret_pos, caret_pos);
538 SetTextAndSelectedRange(text, range);
543 if (notify_text_changed)
547 void OmniboxViewViews::SetForcedQuery() {
548 const base::string16 current_text(text());
549 const size_t start = current_text.find_first_not_of(base::kWhitespaceUTF16);
550 if (start == base::string16::npos || (current_text[start] != '?'))
551 OmniboxView::SetUserText(base::ASCIIToUTF16("?"));
553 SelectRange(gfx::Range(current_text.size(), start + 1));
556 bool OmniboxViewViews::IsSelectAll() const {
557 // TODO(oshima): IME support.
558 return text() == GetSelectedText();
561 bool OmniboxViewViews::DeleteAtEndPressed() {
562 return delete_at_end_pressed_;
565 void OmniboxViewViews::GetSelectionBounds(
566 base::string16::size_type* start,
567 base::string16::size_type* end) const {
568 const gfx::Range range = GetSelectedRange();
569 *start = static_cast<size_t>(range.start());
570 *end = static_cast<size_t>(range.end());
573 void OmniboxViewViews::SelectAll(bool reversed) {
574 views::Textfield::SelectAll(reversed);
577 void OmniboxViewViews::RevertAll() {
578 saved_selection_for_focus_change_ = gfx::Range::InvalidRange();
579 OmniboxView::RevertAll();
582 void OmniboxViewViews::UpdatePopup() {
583 model()->SetInputInProgress(true);
584 if (!model()->has_focus())
587 // Prevent inline autocomplete when the caret isn't at the end of the text,
588 // and during IME composition editing unless
589 // |kEnableOmniboxAutoCompletionForIme| is enabled.
590 const gfx::Range sel = GetSelectedRange();
591 model()->StartAutocomplete(
593 sel.GetMax() < text().length() ||
594 (IsIMEComposing() && !IsOmniboxAutoCompletionForImeEnabled()));
597 void OmniboxViewViews::SetFocus() {
599 // Restore caret visibility if focus is explicitly requested. This is
600 // necessary because if we already have invisible focus, the RequestFocus()
601 // call above will short-circuit, preventing us from reaching
602 // OmniboxEditModel::OnSetFocus(), which handles restoring visibility when the
603 // omnibox regains focus after losing focus.
604 model()->SetCaretVisibility(true);
607 void OmniboxViewViews::ApplyCaretVisibility() {
608 SetCursorEnabled(model()->is_caret_visible());
611 void OmniboxViewViews::OnTemporaryTextMaybeChanged(
612 const base::string16& display_text,
613 bool save_original_selection,
614 bool notify_text_changed) {
615 if (save_original_selection)
616 saved_temporary_selection_ = GetSelectedRange();
618 SetWindowTextAndCaretPos(display_text, display_text.length(), false,
619 notify_text_changed);
622 bool OmniboxViewViews::OnInlineAutocompleteTextMaybeChanged(
623 const base::string16& display_text,
624 size_t user_text_length) {
625 if (display_text == text())
628 if (IsIMEComposing()) {
629 location_bar_view_->SetImeInlineAutocompletion(
630 display_text.substr(user_text_length));
632 gfx::Range range(display_text.size(), user_text_length);
633 SetTextAndSelectedRange(display_text, range);
639 void OmniboxViewViews::OnInlineAutocompleteTextCleared() {
640 // Hide the inline autocompletion for IME users.
641 location_bar_view_->SetImeInlineAutocompletion(base::string16());
644 void OmniboxViewViews::OnRevertTemporaryText() {
645 SelectRange(saved_temporary_selection_);
646 // We got here because the user hit the Escape key. We explicitly don't call
647 // TextChanged(), since OmniboxPopupModel::ResetToDefaultMatch() has already
648 // been called by now, and it would've called TextChanged() if it was
652 void OmniboxViewViews::OnBeforePossibleChange() {
654 text_before_change_ = text();
655 sel_before_change_ = GetSelectedRange();
656 ime_composing_before_change_ = IsIMEComposing();
659 bool OmniboxViewViews::OnAfterPossibleChange() {
660 // See if the text or selection have changed since OnBeforePossibleChange().
661 const base::string16 new_text = text();
662 const gfx::Range new_sel = GetSelectedRange();
663 const bool text_changed = (new_text != text_before_change_) ||
664 (ime_composing_before_change_ != IsIMEComposing());
665 const bool selection_differs =
666 !((sel_before_change_.is_empty() && new_sel.is_empty()) ||
667 sel_before_change_.EqualsIgnoringDirection(new_sel));
669 // When the user has deleted text, we don't allow inline autocomplete. Make
670 // sure to not flag cases like selecting part of the text and then pasting
671 // (or typing) the prefix of that selection. (We detect these by making
672 // sure the caret, which should be after any insertion, hasn't moved
673 // forward of the old selection start.)
674 const bool just_deleted_text =
675 (text_before_change_.length() > new_text.length()) &&
676 (new_sel.start() <= sel_before_change_.GetMin());
678 const bool something_changed = model()->OnAfterPossibleChange(
679 text_before_change_, new_text, new_sel.start(), new_sel.end(),
680 selection_differs, text_changed, just_deleted_text, !IsIMEComposing());
682 // If only selection was changed, we don't need to call model()'s
683 // OnChanged() method, which is called in TextChanged().
684 // But we still need to call EmphasizeURLComponents() to make sure the text
685 // attributes are updated correctly.
686 if (something_changed && text_changed)
688 else if (selection_differs)
689 EmphasizeURLComponents();
690 else if (delete_at_end_pressed_)
691 model()->OnChanged();
693 return something_changed;
696 gfx::NativeView OmniboxViewViews::GetNativeView() const {
697 return GetWidget()->GetNativeView();
700 gfx::NativeView OmniboxViewViews::GetRelativeWindowForPopup() const {
701 return GetWidget()->GetTopLevelWidget()->GetNativeView();
704 void OmniboxViewViews::SetGrayTextAutocompletion(const base::string16& input) {
705 #if defined(OS_WIN) || defined(USE_AURA)
706 location_bar_view_->SetGrayTextAutocompletion(input);
710 base::string16 OmniboxViewViews::GetGrayTextAutocompletion() const {
711 #if defined(OS_WIN) || defined(USE_AURA)
712 return location_bar_view_->GetGrayTextAutocompletion();
714 return base::string16();
718 int OmniboxViewViews::GetTextWidth() const {
719 // Returns the width necessary to display the current text, including any
720 // necessary space for the cursor or border/margin.
721 return GetRenderText()->GetContentWidth() + GetInsets().width();
724 int OmniboxViewViews::GetWidth() const {
725 return location_bar_view_->width();
728 bool OmniboxViewViews::IsImeComposing() const {
729 return IsIMEComposing();
732 bool OmniboxViewViews::IsImeShowingPopup() const {
733 #if defined(OS_CHROMEOS)
734 return ime_candidate_window_open_;
736 const views::InputMethod* input_method = this->GetInputMethod();
737 return input_method && input_method->IsCandidatePopupOpen();
741 void OmniboxViewViews::ShowImeIfNeeded() {
742 GetInputMethod()->ShowImeIfNeeded();
745 void OmniboxViewViews::OnMatchOpened(const AutocompleteMatch& match,
747 content::WebContents* web_contents) const {
748 extensions::MaybeShowExtensionControlledSearchNotification(
749 profile, web_contents, match);
752 bool OmniboxViewViews::IsCommandIdEnabled(int command_id) const {
753 if (command_id == IDS_APP_PASTE)
754 return !read_only() && !GetClipboardText().empty();
755 if (command_id == IDS_PASTE_AND_GO)
756 return !read_only() && model()->CanPasteAndGo(GetClipboardText());
757 if (command_id == IDS_SHOW_URL)
758 return controller()->GetToolbarModel()->WouldReplaceURL();
759 return command_id == IDS_MOVE_DOWN || command_id == IDS_MOVE_UP ||
760 Textfield::IsCommandIdEnabled(command_id) ||
761 command_updater()->IsCommandEnabled(command_id);
764 bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id) const {
765 return command_id == IDS_PASTE_AND_GO;
768 base::string16 OmniboxViewViews::GetLabelForCommandId(int command_id) const {
769 DCHECK_EQ(IDS_PASTE_AND_GO, command_id);
770 return l10n_util::GetStringUTF16(
771 model()->IsPasteAndSearch(GetClipboardText()) ?
772 IDS_PASTE_AND_SEARCH : IDS_PASTE_AND_GO);
775 void OmniboxViewViews::ExecuteCommand(int command_id, int event_flags) {
776 switch (command_id) {
777 // These commands don't invoke the popup via OnBefore/AfterPossibleChange().
778 case IDS_PASTE_AND_GO:
779 model()->PasteAndGo(GetClipboardText());
782 controller()->ShowURL();
784 case IDC_EDIT_SEARCH_ENGINES:
785 command_updater()->ExecuteCommand(command_id);
789 model()->OnUpOrDownKeyPressed(command_id == IDS_MOVE_DOWN ? 1 : -1);
793 OnBeforePossibleChange();
794 if (command_id == IDS_APP_PASTE)
796 else if (Textfield::IsCommandIdEnabled(command_id))
797 Textfield::ExecuteCommand(command_id, event_flags);
799 command_updater()->ExecuteCommand(command_id);
800 OnAfterPossibleChange();
805 ////////////////////////////////////////////////////////////////////////////////
806 // OmniboxViewViews, gfx::AnimationDelegate implementation:
808 void OmniboxViewViews::AnimationProgressed(const gfx::Animation* animation) {
812 void OmniboxViewViews::AnimationEnded(const gfx::Animation* animation) {
813 fade_in_animation_->Reset();
816 ////////////////////////////////////////////////////////////////////////////////
817 // OmniboxViewViews, views::TextfieldController implementation:
819 void OmniboxViewViews::ContentsChanged(views::Textfield* sender,
820 const base::string16& new_contents) {
823 bool OmniboxViewViews::HandleKeyEvent(views::Textfield* textfield,
824 const ui::KeyEvent& event) {
825 delete_at_end_pressed_ = false;
827 if (event.key_code() == ui::VKEY_BACK) {
828 // No extra handling is needed in keyword search mode, if there is a
829 // non-empty selection, or if the cursor is not leading the text.
830 if (model()->is_keyword_hint() || model()->keyword().empty() ||
831 HasSelection() || GetCursorPosition() != 0)
833 model()->ClearKeyword(text());
837 if (event.key_code() == ui::VKEY_DELETE && !event.IsAltDown()) {
838 delete_at_end_pressed_ =
839 (!HasSelection() && GetCursorPosition() == text().length());
842 // Handle the right-arrow key for LTR text and the left-arrow key for RTL text
843 // if there is gray text that needs to be committed.
844 if (GetCursorPosition() == text().length()) {
845 base::i18n::TextDirection direction = GetTextDirection();
846 if ((direction == base::i18n::LEFT_TO_RIGHT &&
847 event.key_code() == ui::VKEY_RIGHT) ||
848 (direction == base::i18n::RIGHT_TO_LEFT &&
849 event.key_code() == ui::VKEY_LEFT)) {
850 return model()->CommitSuggestedText();
857 void OmniboxViewViews::OnBeforeUserAction(views::Textfield* sender) {
858 OnBeforePossibleChange();
861 void OmniboxViewViews::OnAfterUserAction(views::Textfield* sender) {
862 OnAfterPossibleChange();
865 void OmniboxViewViews::OnAfterCutOrCopy(ui::ClipboardType clipboard_type) {
866 ui::Clipboard* cb = ui::Clipboard::GetForCurrentThread();
867 base::string16 selected_text;
868 cb->ReadText(clipboard_type, &selected_text);
871 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
872 &selected_text, &url, &write_url);
874 UMA_HISTOGRAM_COUNTS(OmniboxEditModel::kCutOrCopyAllTextHistogram, 1);
877 BookmarkNodeData data;
878 data.ReadFromTuple(url, selected_text);
879 data.WriteToClipboard(clipboard_type);
881 ui::ScopedClipboardWriter scoped_clipboard_writer(
882 ui::Clipboard::GetForCurrentThread(), clipboard_type);
883 scoped_clipboard_writer.WriteText(selected_text);
887 void OmniboxViewViews::OnGetDragOperationsForTextfield(int* drag_operations) {
888 base::string16 selected_text = GetSelectedText();
891 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(),
892 &selected_text, &url, &write_url);
894 *drag_operations |= ui::DragDropTypes::DRAG_LINK;
897 void OmniboxViewViews::OnWriteDragData(ui::OSExchangeData* data) {
900 bool is_all_selected = IsSelectAll();
901 base::string16 selected_text = GetSelectedText();
902 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), is_all_selected,
903 &selected_text, &url, &write_url);
904 data->SetString(selected_text);
907 base::string16 title = selected_text;
909 model()->GetDataForURLExport(&url, &title, &favicon);
910 button_drag_utils::SetURLAndDragImage(url, title, favicon.AsImageSkia(),
912 data->SetURL(url, title);
916 void OmniboxViewViews::AppendDropFormats(
918 std::set<ui::OSExchangeData::CustomFormat>* custom_formats) {
919 *formats = *formats | ui::OSExchangeData::URL;
922 int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) {
923 if (HasTextBeingDragged())
924 return ui::DragDropTypes::DRAG_NONE;
926 if (data.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)) {
928 base::string16 title;
929 if (data.GetURLAndTitle(
930 ui::OSExchangeData::CONVERT_FILENAMES, &url, &title)) {
932 StripJavascriptSchemas(base::UTF8ToUTF16(url.spec())));
933 if (model()->CanPasteAndGo(text)) {
934 model()->PasteAndGo(text);
935 return ui::DragDropTypes::DRAG_COPY;
938 } else if (data.HasString()) {
940 if (data.GetString(&text)) {
941 base::string16 collapsed_text(base::CollapseWhitespace(text, true));
942 if (model()->CanPasteAndGo(collapsed_text))
943 model()->PasteAndGo(collapsed_text);
944 return ui::DragDropTypes::DRAG_COPY;
948 return ui::DragDropTypes::DRAG_NONE;
951 void OmniboxViewViews::UpdateContextMenu(ui::SimpleMenuModel* menu_contents) {
952 int paste_position = menu_contents->GetIndexOfCommandId(IDS_APP_PASTE);
953 DCHECK_GE(paste_position, 0);
954 menu_contents->InsertItemWithStringIdAt(
955 paste_position + 1, IDS_PASTE_AND_GO, IDS_PASTE_AND_GO);
957 menu_contents->AddSeparator(ui::NORMAL_SEPARATOR);
959 if (chrome::IsQueryExtractionEnabled() || chrome::ShouldDisplayOriginChip() ||
960 chrome::ShouldDisplayOriginChipV2()) {
961 int select_all_position = menu_contents->GetIndexOfCommandId(
963 DCHECK_GE(select_all_position, 0);
964 menu_contents->InsertItemWithStringIdAt(
965 select_all_position + 1, IDS_SHOW_URL, IDS_SHOW_URL);
968 // Minor note: We use IDC_ for command id here while the underlying textfield
969 // is using IDS_ for all its command ids. This is because views cannot depend
971 menu_contents->AddItemWithStringId(IDC_EDIT_SEARCH_ENGINES,
972 IDS_EDIT_SEARCH_ENGINES);
975 #if defined(OS_CHROMEOS)
976 void OmniboxViewViews::CandidateWindowOpened(
977 chromeos::input_method::InputMethodManager* manager) {
978 ime_candidate_window_open_ = true;
981 void OmniboxViewViews::CandidateWindowClosed(
982 chromeos::input_method::InputMethodManager* manager) {
983 ime_candidate_window_open_ = false;
987 ////////////////////////////////////////////////////////////////////////////////
988 // OmniboxViewViews, private:
990 int OmniboxViewViews::GetOmniboxTextLength() const {
991 // TODO(oshima): Support IME.
992 return static_cast<int>(text().length());
995 void OmniboxViewViews::EmphasizeURLComponents() {
996 // See whether the contents are a URL with a non-empty host portion, which we
997 // should emphasize. To check for a URL, rather than using the type returned
998 // by Parse(), ask the model, which will check the desired page transition for
999 // this input. This can tell us whether an UNKNOWN input string is going to
1000 // be treated as a search or a navigation, and is the same method the Paste
1001 // And Go system uses.
1002 url_parse::Component scheme, host;
1003 AutocompleteInput::ParseForEmphasizeComponents(text(), &scheme, &host);
1004 bool grey_out_url = text().substr(scheme.begin, scheme.len) ==
1005 base::UTF8ToUTF16(extensions::kExtensionScheme);
1006 bool grey_base = model()->CurrentTextIsURL() &&
1007 (host.is_nonempty() || grey_out_url);
1008 SetColor(location_bar_view_->GetColor(
1010 grey_base ? LocationBarView::DEEMPHASIZED_TEXT : LocationBarView::TEXT));
1011 if (grey_base && !grey_out_url) {
1013 location_bar_view_->GetColor(security_level_, LocationBarView::TEXT),
1014 gfx::Range(host.begin, host.end()));
1017 // Emphasize the scheme for security UI display purposes (if necessary).
1018 // Note that we check CurrentTextIsURL() because if we're replacing search
1019 // URLs with search terms, we may have a non-URL even when the user is not
1020 // editing; and in some cases, e.g. for "site:foo.com" searches, the parser
1021 // may have incorrectly identified a qualifier as a scheme.
1022 SetStyle(gfx::DIAGONAL_STRIKE, false);
1023 if (!model()->user_input_in_progress() && model()->CurrentTextIsURL() &&
1024 scheme.is_nonempty() && (security_level_ != ToolbarModel::NONE)) {
1025 SkColor security_color = location_bar_view_->GetColor(
1026 security_level_, LocationBarView::SECURITY_TEXT);
1027 const bool strike = (security_level_ == ToolbarModel::SECURITY_ERROR);
1028 const gfx::Range scheme_range(scheme.begin, scheme.end());
1029 ApplyColor(security_color, scheme_range);
1030 ApplyStyle(gfx::DIAGONAL_STRIKE, strike, scheme_range);
1034 void OmniboxViewViews::SetTextAndSelectedRange(const base::string16& text,
1035 const gfx::Range& range) {
1040 base::string16 OmniboxViewViews::GetSelectedText() const {
1041 // TODO(oshima): Support IME.
1042 return views::Textfield::GetSelectedText();
1045 void OmniboxViewViews::OnPaste() {
1046 const base::string16 text(GetClipboardText());
1047 if (!text.empty()) {
1048 // Record this paste, so we can do different behavior.
1050 // Force a Paste operation to trigger the text_changed code in
1051 // OnAfterPossibleChange(), even if identical contents are pasted.
1052 text_before_change_.clear();
1053 InsertOrReplaceText(text);