omnibox_view_views.cc revision 5f1c94371a64b3196d4be9466099bb892df9b88e
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. 4 5#include "chrome/browser/ui/views/omnibox/omnibox_view_views.h" 6 7#include <set> 8 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/omnibox/omnibox_field_trial.h" 18#include "chrome/browser/search/search.h" 19#include "chrome/browser/ui/omnibox/omnibox_edit_controller.h" 20#include "chrome/browser/ui/omnibox/omnibox_edit_model.h" 21#include "chrome/browser/ui/omnibox/omnibox_popup_model.h" 22#include "chrome/browser/ui/view_ids.h" 23#include "chrome/browser/ui/views/location_bar/location_bar_view.h" 24#include "chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h" 25#include "chrome/browser/ui/views/settings_api_bubble_helper_views.h" 26#include "chrome/browser/ui/views/website_settings/website_settings_popup_view.h" 27#include "components/bookmarks/browser/bookmark_node_data.h" 28#include "components/omnibox/autocomplete_input.h" 29#include "components/omnibox/autocomplete_match.h" 30#include "content/public/browser/web_contents.h" 31#include "extensions/common/constants.h" 32#include "grit/app_locale_settings.h" 33#include "grit/generated_resources.h" 34#include "grit/ui_strings.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/aura/client/focus_client.h" 39#include "ui/aura/window_event_dispatcher.h" 40#include "ui/base/clipboard/scoped_clipboard_writer.h" 41#include "ui/base/dragdrop/drag_drop_types.h" 42#include "ui/base/dragdrop/os_exchange_data.h" 43#include "ui/base/ime/text_input_client.h" 44#include "ui/base/ime/text_input_type.h" 45#include "ui/base/l10n/l10n_util.h" 46#include "ui/base/models/simple_menu_model.h" 47#include "ui/base/resource/resource_bundle.h" 48#include "ui/compositor/layer.h" 49#include "ui/events/event.h" 50#include "ui/gfx/canvas.h" 51#include "ui/gfx/font_list.h" 52#include "ui/gfx/selection_model.h" 53#include "ui/views/border.h" 54#include "ui/views/button_drag_utils.h" 55#include "ui/views/controls/textfield/textfield.h" 56#include "ui/views/ime/input_method.h" 57#include "ui/views/layout/fill_layout.h" 58#include "ui/views/views_delegate.h" 59#include "ui/views/widget/widget.h" 60#include "url/gurl.h" 61 62#if defined(OS_WIN) 63#include "chrome/browser/browser_process.h" 64#endif 65 66using bookmarks::BookmarkNodeData; 67 68namespace { 69 70// OmniboxState --------------------------------------------------------------- 71 72// Stores omnibox state for each tab. 73struct OmniboxState : public base::SupportsUserData::Data { 74 static const char kKey[]; 75 76 OmniboxState(const OmniboxEditModel::State& model_state, 77 const gfx::Range& selection, 78 const gfx::Range& saved_selection_for_focus_change); 79 virtual ~OmniboxState(); 80 81 const OmniboxEditModel::State model_state; 82 83 // We store both the actual selection and any saved selection (for when the 84 // omnibox is not focused). This allows us to properly handle cases like 85 // selecting text, tabbing out of the omnibox, switching tabs away and back, 86 // and tabbing back into the omnibox. 87 const gfx::Range selection; 88 const gfx::Range saved_selection_for_focus_change; 89}; 90 91// static 92const char OmniboxState::kKey[] = "OmniboxState"; 93 94OmniboxState::OmniboxState(const OmniboxEditModel::State& model_state, 95 const gfx::Range& selection, 96 const gfx::Range& saved_selection_for_focus_change) 97 : model_state(model_state), 98 selection(selection), 99 saved_selection_for_focus_change(saved_selection_for_focus_change) { 100} 101 102OmniboxState::~OmniboxState() { 103} 104 105 106// Helpers -------------------------------------------------------------------- 107 108// We'd like to set the text input type to TEXT_INPUT_TYPE_URL, because this 109// triggers URL-specific layout in software keyboards, e.g. adding top-level "/" 110// and ".com" keys for English. However, this also causes IMEs to default to 111// Latin character mode, which makes entering search queries difficult for IME 112// users. Therefore, we try to guess whether an IME will be used based on the 113// application language, and set the input type accordingly. 114ui::TextInputType DetermineTextInputType() { 115#if defined(OS_WIN) 116 DCHECK(g_browser_process); 117 const std::string& locale = g_browser_process->GetApplicationLocale(); 118 const std::string& language = locale.substr(0, 2); 119 // Assume CJK + Thai users are using an IME. 120 if (language == "ja" || 121 language == "ko" || 122 language == "th" || 123 language == "zh") 124 return ui::TEXT_INPUT_TYPE_SEARCH; 125#endif 126 return ui::TEXT_INPUT_TYPE_URL; 127} 128 129} // namespace 130 131 132// OmniboxViewViews ----------------------------------------------------------- 133 134// static 135const char OmniboxViewViews::kViewClassName[] = "OmniboxViewViews"; 136 137OmniboxViewViews::OmniboxViewViews(OmniboxEditController* controller, 138 Profile* profile, 139 CommandUpdater* command_updater, 140 bool popup_window_mode, 141 LocationBarView* location_bar, 142 const gfx::FontList& font_list) 143 : OmniboxView(profile, controller, command_updater), 144 popup_window_mode_(popup_window_mode), 145 security_level_(ToolbarModel::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); 157} 158 159OmniboxViewViews::~OmniboxViewViews() { 160#if defined(OS_CHROMEOS) 161 chromeos::input_method::InputMethodManager::Get()-> 162 RemoveCandidateWindowObserver(this); 163#endif 164 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. 167 popup_view_.reset(); 168} 169 170void OmniboxViewViews::Init() { 171 set_controller(this); 172 SetTextInputType(DetermineTextInputType()); 173 174 if (popup_window_mode_) 175 SetReadOnly(true); 176 177 // Initialize the popup view using the same font. 178 popup_view_.reset(OmniboxPopupContentsView::Create( 179 GetFontList(), this, model(), location_bar_view_)); 180 181#if defined(OS_CHROMEOS) 182 chromeos::input_method::InputMethodManager::Get()-> 183 AddCandidateWindowObserver(this); 184#endif 185} 186 187void OmniboxViewViews::SaveStateToTab(content::WebContents* tab) { 188 DCHECK(tab); 189 190 // We don't want to keep the IME status, so force quit the current 191 // session here. It may affect the selection status, so order is 192 // also important. 193 if (IsIMEComposing()) { 194 GetTextInputClient()->ConfirmCompositionText(); 195 GetInputMethod()->CancelComposition(this); 196 } 197 198 // NOTE: GetStateForTabSwitch() may affect GetSelectedRange(), so order is 199 // important. 200 OmniboxEditModel::State state = model()->GetStateForTabSwitch(); 201 tab->SetUserData(OmniboxState::kKey, new OmniboxState( 202 state, GetSelectedRange(), saved_selection_for_focus_change_)); 203} 204 205void OmniboxViewViews::OnTabChanged(const content::WebContents* web_contents) { 206 security_level_ = controller()->GetToolbarModel()->GetSecurityLevel(false); 207 208 const OmniboxState* state = static_cast<OmniboxState*>( 209 web_contents->GetUserData(&OmniboxState::kKey)); 210 model()->RestoreState(state ? &state->model_state : NULL); 211 if (state) { 212 // This assumes that the omnibox has already been focused or blurred as 213 // appropriate; otherwise, a subsequent OnFocus() or OnBlur() call could 214 // goof up the selection. See comments at the end of 215 // BrowserView::ActiveTabChanged(). 216 SelectRange(state->selection); 217 saved_selection_for_focus_change_ = state->saved_selection_for_focus_change; 218 } 219 220 // TODO(msw|oshima): Consider saving/restoring edit history. 221 ClearEditHistory(); 222} 223 224void OmniboxViewViews::Update() { 225 UpdatePlaceholderText(); 226 227 const ToolbarModel::SecurityLevel old_security_level = security_level_; 228 security_level_ = controller()->GetToolbarModel()->GetSecurityLevel(false); 229 if (model()->UpdatePermanentText()) { 230 // Something visibly changed. Re-enable URL replacement. 231 controller()->GetToolbarModel()->set_url_replacement_enabled(true); 232 controller()->GetToolbarModel()->set_origin_chip_enabled(true); 233 model()->UpdatePermanentText(); 234 235 // Select all the new text if the user had all the old text selected, or if 236 // there was no previous text (for new tab page URL replacement extensions). 237 // This makes one particular case better: the user clicks in the box to 238 // change it right before the permanent URL is changed. Since the new URL 239 // is still fully selected, the user's typing will replace the edit contents 240 // as they'd intended. 241 const bool was_select_all = IsSelectAll(); 242 const bool was_reversed = GetSelectedRange().is_reversed(); 243 244 RevertAll(); 245 246 // Only select all when we have focus. If we don't have focus, selecting 247 // all is unnecessary since the selection will change on regaining focus, 248 // and can in fact cause artifacts, e.g. if the user is on the NTP and 249 // clicks a link to navigate, causing |was_select_all| to be vacuously true 250 // for the empty omnibox, and we then select all here, leading to the 251 // trailing portion of a long URL being scrolled into view. We could try 252 // and address cases like this, but it seems better to just not muck with 253 // things when the omnibox isn't focused to begin with. 254 if (was_select_all && model()->has_focus()) 255 SelectAll(was_reversed); 256 } else if (old_security_level != security_level_) { 257 EmphasizeURLComponents(); 258 } 259} 260 261void OmniboxViewViews::UpdatePlaceholderText() { 262 if (chrome::ShouldDisplayOriginChip() || 263 OmniboxFieldTrial::DisplayHintTextWhenPossible()) 264 set_placeholder_text(GetHintText()); 265} 266 267base::string16 OmniboxViewViews::GetText() const { 268 // TODO(oshima): IME support 269 return text(); 270} 271 272void OmniboxViewViews::SetUserText(const base::string16& text, 273 const base::string16& display_text, 274 bool update_popup) { 275 saved_selection_for_focus_change_ = gfx::Range::InvalidRange(); 276 OmniboxView::SetUserText(text, display_text, update_popup); 277} 278 279void OmniboxViewViews::SetForcedQuery() { 280 const base::string16 current_text(text()); 281 const size_t start = current_text.find_first_not_of(base::kWhitespaceUTF16); 282 if (start == base::string16::npos || (current_text[start] != '?')) 283 OmniboxView::SetUserText(base::ASCIIToUTF16("?")); 284 else 285 SelectRange(gfx::Range(current_text.size(), start + 1)); 286} 287 288void OmniboxViewViews::GetSelectionBounds( 289 base::string16::size_type* start, 290 base::string16::size_type* end) const { 291 const gfx::Range range = GetSelectedRange(); 292 *start = static_cast<size_t>(range.start()); 293 *end = static_cast<size_t>(range.end()); 294} 295 296void OmniboxViewViews::SelectAll(bool reversed) { 297 views::Textfield::SelectAll(reversed); 298} 299 300void OmniboxViewViews::RevertAll() { 301 saved_selection_for_focus_change_ = gfx::Range::InvalidRange(); 302 OmniboxView::RevertAll(); 303} 304 305void OmniboxViewViews::SetFocus() { 306 RequestFocus(); 307 // Restore caret visibility if focus is explicitly requested. This is 308 // necessary because if we already have invisible focus, the RequestFocus() 309 // call above will short-circuit, preventing us from reaching 310 // OmniboxEditModel::OnSetFocus(), which handles restoring visibility when the 311 // omnibox regains focus after losing focus. 312 model()->SetCaretVisibility(true); 313} 314 315int OmniboxViewViews::GetTextWidth() const { 316 // Returns the width necessary to display the current text, including any 317 // necessary space for the cursor or border/margin. 318 return GetRenderText()->GetContentWidth() + GetInsets().width(); 319} 320 321bool OmniboxViewViews::IsImeComposing() const { 322 return IsIMEComposing(); 323} 324 325gfx::Size OmniboxViewViews::GetMinimumSize() const { 326 const int kMinCharacters = 10; 327 return gfx::Size( 328 GetFontList().GetExpectedTextWidth(kMinCharacters) + GetInsets().width(), 329 GetPreferredSize().height()); 330} 331 332void OmniboxViewViews::OnNativeThemeChanged(const ui::NativeTheme* theme) { 333 views::Textfield::OnNativeThemeChanged(theme); 334 SetBackgroundColor(location_bar_view_->GetColor( 335 ToolbarModel::NONE, LocationBarView::BACKGROUND)); 336 EmphasizeURLComponents(); 337} 338 339void OmniboxViewViews::ExecuteCommand(int command_id, int event_flags) { 340 // In the base class, touch text selection is deactivated when a command is 341 // executed. Since we are not always calling the base class implementation 342 // here, we need to deactivate touch text selection here, too. 343 DestroyTouchSelection(); 344 switch (command_id) { 345 // These commands don't invoke the popup via OnBefore/AfterPossibleChange(). 346 case IDS_PASTE_AND_GO: 347 model()->PasteAndGo(GetClipboardText()); 348 break; 349 case IDS_SHOW_URL: 350 controller()->ShowURL(); 351 break; 352 case IDC_EDIT_SEARCH_ENGINES: 353 command_updater()->ExecuteCommand(command_id); 354 break; 355 case IDS_MOVE_DOWN: 356 case IDS_MOVE_UP: 357 model()->OnUpOrDownKeyPressed(command_id == IDS_MOVE_DOWN ? 1 : -1); 358 break; 359 360 default: 361 OnBeforePossibleChange(); 362 if (command_id == IDS_APP_PASTE) 363 OnPaste(); 364 else if (Textfield::IsCommandIdEnabled(command_id)) 365 Textfield::ExecuteCommand(command_id, event_flags); 366 else 367 command_updater()->ExecuteCommand(command_id); 368 OnAfterPossibleChange(); 369 break; 370 } 371} 372 373void OmniboxViewViews::SetTextAndSelectedRange(const base::string16& text, 374 const gfx::Range& range) { 375 SetText(text); 376 SelectRange(range); 377} 378 379base::string16 OmniboxViewViews::GetSelectedText() const { 380 // TODO(oshima): Support IME. 381 return views::Textfield::GetSelectedText(); 382} 383 384void OmniboxViewViews::OnPaste() { 385 const base::string16 text(GetClipboardText()); 386 if (!text.empty()) { 387 // Record this paste, so we can do different behavior. 388 model()->OnPaste(); 389 // Force a Paste operation to trigger the text_changed code in 390 // OnAfterPossibleChange(), even if identical contents are pasted. 391 text_before_change_.clear(); 392 InsertOrReplaceText(text); 393 } 394} 395 396bool OmniboxViewViews::HandleEarlyTabActions(const ui::KeyEvent& event) { 397 // This must run before acclerator handling invokes a focus change on tab. 398 // Note the parallel with SkipDefaultKeyEventProcessing above. 399 if (!views::FocusManager::IsTabTraversalKeyEvent(event)) 400 return false; 401 402 if (model()->is_keyword_hint() && !event.IsShiftDown()) { 403 model()->AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_TAB); 404 return true; 405 } 406 407 if (!model()->popup_model()->IsOpen()) 408 return false; 409 410 if (event.IsShiftDown() && 411 (model()->popup_model()->selected_line_state() == 412 OmniboxPopupModel::KEYWORD)) 413 model()->ClearKeyword(text()); 414 else 415 model()->OnUpOrDownKeyPressed(event.IsShiftDown() ? -1 : 1); 416 417 return true; 418} 419 420void OmniboxViewViews::AccessibilitySetValue(const base::string16& new_value) { 421 SetUserText(new_value, new_value, true); 422} 423 424void OmniboxViewViews::SetWindowTextAndCaretPos(const base::string16& text, 425 size_t caret_pos, 426 bool update_popup, 427 bool notify_text_changed) { 428 const gfx::Range range(caret_pos, caret_pos); 429 SetTextAndSelectedRange(text, range); 430 431 if (update_popup) 432 UpdatePopup(); 433 434 if (notify_text_changed) 435 TextChanged(); 436} 437 438bool OmniboxViewViews::IsSelectAll() const { 439 // TODO(oshima): IME support. 440 return text() == GetSelectedText(); 441} 442 443bool OmniboxViewViews::DeleteAtEndPressed() { 444 return delete_at_end_pressed_; 445} 446 447void OmniboxViewViews::UpdatePopup() { 448 model()->SetInputInProgress(true); 449 if (!model()->has_focus()) 450 return; 451 452 // Prevent inline autocomplete when the caret isn't at the end of the text. 453 const gfx::Range sel = GetSelectedRange(); 454 model()->StartAutocomplete(!sel.is_empty(), sel.GetMax() < text().length()); 455} 456 457void OmniboxViewViews::ApplyCaretVisibility() { 458 SetCursorEnabled(model()->is_caret_visible()); 459} 460 461void OmniboxViewViews::OnTemporaryTextMaybeChanged( 462 const base::string16& display_text, 463 bool save_original_selection, 464 bool notify_text_changed) { 465 if (save_original_selection) 466 saved_temporary_selection_ = GetSelectedRange(); 467 468 SetWindowTextAndCaretPos(display_text, display_text.length(), false, 469 notify_text_changed); 470} 471 472bool OmniboxViewViews::OnInlineAutocompleteTextMaybeChanged( 473 const base::string16& display_text, 474 size_t user_text_length) { 475 if (display_text == text()) 476 return false; 477 478 if (IsIMEComposing()) { 479 location_bar_view_->SetImeInlineAutocompletion( 480 display_text.substr(user_text_length)); 481 } else { 482 gfx::Range range(display_text.size(), user_text_length); 483 SetTextAndSelectedRange(display_text, range); 484 } 485 TextChanged(); 486 return true; 487} 488 489void OmniboxViewViews::OnInlineAutocompleteTextCleared() { 490 // Hide the inline autocompletion for IME users. 491 location_bar_view_->SetImeInlineAutocompletion(base::string16()); 492} 493 494void OmniboxViewViews::OnRevertTemporaryText() { 495 SelectRange(saved_temporary_selection_); 496 // We got here because the user hit the Escape key. We explicitly don't call 497 // TextChanged(), since OmniboxPopupModel::ResetToDefaultMatch() has already 498 // been called by now, and it would've called TextChanged() if it was 499 // warranted. 500} 501 502void OmniboxViewViews::OnBeforePossibleChange() { 503 // Record our state. 504 text_before_change_ = text(); 505 sel_before_change_ = GetSelectedRange(); 506 ime_composing_before_change_ = IsIMEComposing(); 507} 508 509bool OmniboxViewViews::OnAfterPossibleChange() { 510 // See if the text or selection have changed since OnBeforePossibleChange(). 511 const base::string16 new_text = text(); 512 const gfx::Range new_sel = GetSelectedRange(); 513 const bool text_changed = (new_text != text_before_change_) || 514 (ime_composing_before_change_ != IsIMEComposing()); 515 const bool selection_differs = 516 !((sel_before_change_.is_empty() && new_sel.is_empty()) || 517 sel_before_change_.EqualsIgnoringDirection(new_sel)); 518 519 // When the user has deleted text, we don't allow inline autocomplete. Make 520 // sure to not flag cases like selecting part of the text and then pasting 521 // (or typing) the prefix of that selection. (We detect these by making 522 // sure the caret, which should be after any insertion, hasn't moved 523 // forward of the old selection start.) 524 const bool just_deleted_text = 525 (text_before_change_.length() > new_text.length()) && 526 (new_sel.start() <= sel_before_change_.GetMin()); 527 528 const bool something_changed = model()->OnAfterPossibleChange( 529 text_before_change_, new_text, new_sel.start(), new_sel.end(), 530 selection_differs, text_changed, just_deleted_text, !IsIMEComposing()); 531 532 // If only selection was changed, we don't need to call model()'s 533 // OnChanged() method, which is called in TextChanged(). 534 // But we still need to call EmphasizeURLComponents() to make sure the text 535 // attributes are updated correctly. 536 if (something_changed && text_changed) 537 TextChanged(); 538 else if (selection_differs) 539 EmphasizeURLComponents(); 540 else if (delete_at_end_pressed_) 541 model()->OnChanged(); 542 543 return something_changed; 544} 545 546gfx::NativeView OmniboxViewViews::GetNativeView() const { 547 return GetWidget()->GetNativeView(); 548} 549 550gfx::NativeView OmniboxViewViews::GetRelativeWindowForPopup() const { 551 return GetWidget()->GetTopLevelWidget()->GetNativeView(); 552} 553 554void OmniboxViewViews::SetGrayTextAutocompletion(const base::string16& input) { 555 location_bar_view_->SetGrayTextAutocompletion(input); 556} 557 558base::string16 OmniboxViewViews::GetGrayTextAutocompletion() const { 559 return location_bar_view_->GetGrayTextAutocompletion(); 560} 561 562int OmniboxViewViews::GetWidth() const { 563 return location_bar_view_->width(); 564} 565 566bool OmniboxViewViews::IsImeShowingPopup() const { 567#if defined(OS_CHROMEOS) 568 return ime_candidate_window_open_; 569#else 570 const views::InputMethod* input_method = this->GetInputMethod(); 571 return input_method && input_method->IsCandidatePopupOpen(); 572#endif 573} 574 575void OmniboxViewViews::ShowImeIfNeeded() { 576 GetInputMethod()->ShowImeIfNeeded(); 577} 578 579void OmniboxViewViews::OnMatchOpened(const AutocompleteMatch& match, 580 content::WebContents* web_contents) { 581 extensions::MaybeShowExtensionControlledSearchNotification( 582 profile(), web_contents, match); 583} 584 585int OmniboxViewViews::GetOmniboxTextLength() const { 586 // TODO(oshima): Support IME. 587 return static_cast<int>(text().length()); 588} 589 590void OmniboxViewViews::EmphasizeURLComponents() { 591 // See whether the contents are a URL with a non-empty host portion, which we 592 // should emphasize. To check for a URL, rather than using the type returned 593 // by Parse(), ask the model, which will check the desired page transition for 594 // this input. This can tell us whether an UNKNOWN input string is going to 595 // be treated as a search or a navigation, and is the same method the Paste 596 // And Go system uses. 597 url::Component scheme, host; 598 AutocompleteInput::ParseForEmphasizeComponents( 599 text(), ChromeAutocompleteSchemeClassifier(profile()), &scheme, &host); 600 bool grey_out_url = text().substr(scheme.begin, scheme.len) == 601 base::UTF8ToUTF16(extensions::kExtensionScheme); 602 bool grey_base = model()->CurrentTextIsURL() && 603 (host.is_nonempty() || grey_out_url); 604 SetColor(location_bar_view_->GetColor( 605 security_level_, 606 grey_base ? LocationBarView::DEEMPHASIZED_TEXT : LocationBarView::TEXT)); 607 if (grey_base && !grey_out_url) { 608 ApplyColor( 609 location_bar_view_->GetColor(security_level_, LocationBarView::TEXT), 610 gfx::Range(host.begin, host.end())); 611 } 612 613 // Emphasize the scheme for security UI display purposes (if necessary). 614 // Note that we check CurrentTextIsURL() because if we're replacing search 615 // URLs with search terms, we may have a non-URL even when the user is not 616 // editing; and in some cases, e.g. for "site:foo.com" searches, the parser 617 // may have incorrectly identified a qualifier as a scheme. 618 SetStyle(gfx::DIAGONAL_STRIKE, false); 619 if (!model()->user_input_in_progress() && model()->CurrentTextIsURL() && 620 scheme.is_nonempty() && (security_level_ != ToolbarModel::NONE)) { 621 SkColor security_color = location_bar_view_->GetColor( 622 security_level_, LocationBarView::SECURITY_TEXT); 623 const bool strike = (security_level_ == ToolbarModel::SECURITY_ERROR); 624 const gfx::Range scheme_range(scheme.begin, scheme.end()); 625 ApplyColor(security_color, scheme_range); 626 ApplyStyle(gfx::DIAGONAL_STRIKE, strike, scheme_range); 627 } 628} 629 630bool OmniboxViewViews::OnKeyReleased(const ui::KeyEvent& event) { 631 // The omnibox contents may change while the control key is pressed. 632 if (event.key_code() == ui::VKEY_CONTROL) 633 model()->OnControlKeyChanged(false); 634 return views::Textfield::OnKeyReleased(event); 635} 636 637bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id) const { 638 return command_id == IDS_PASTE_AND_GO; 639} 640 641base::string16 OmniboxViewViews::GetLabelForCommandId(int command_id) const { 642 DCHECK_EQ(IDS_PASTE_AND_GO, command_id); 643 return l10n_util::GetStringUTF16( 644 model()->IsPasteAndSearch(GetClipboardText()) ? 645 IDS_PASTE_AND_SEARCH : IDS_PASTE_AND_GO); 646} 647 648const char* OmniboxViewViews::GetClassName() const { 649 return kViewClassName; 650} 651 652bool OmniboxViewViews::OnMousePressed(const ui::MouseEvent& event) { 653 select_all_on_mouse_release_ = 654 (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) && 655 (!HasFocus() || (model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE)); 656 if (select_all_on_mouse_release_) { 657 // Restore caret visibility whenever the user clicks in the omnibox in a way 658 // that would give it focus. We must handle this case separately here 659 // because if the omnibox currently has invisible focus, the mouse event 660 // won't trigger either SetFocus() or OmniboxEditModel::OnSetFocus(). 661 model()->SetCaretVisibility(true); 662 663 // When we're going to select all on mouse release, invalidate any saved 664 // selection lest restoring it fights with the "select all" action. It's 665 // possible to later set select_all_on_mouse_release_ back to false, but 666 // that happens for things like dragging, which are cases where having 667 // invalidated this saved selection is still OK. 668 saved_selection_for_focus_change_ = gfx::Range::InvalidRange(); 669 } 670 return views::Textfield::OnMousePressed(event); 671} 672 673bool OmniboxViewViews::OnMouseDragged(const ui::MouseEvent& event) { 674 if (ExceededDragThreshold(event.location() - last_click_location())) 675 select_all_on_mouse_release_ = false; 676 677 if (HasTextBeingDragged()) 678 CloseOmniboxPopup(); 679 680 return views::Textfield::OnMouseDragged(event); 681} 682 683void OmniboxViewViews::OnMouseReleased(const ui::MouseEvent& event) { 684 views::Textfield::OnMouseReleased(event); 685 if (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) { 686 // When the user has clicked and released to give us focus, select all 687 // unless we're omitting the URL (in which case refining an existing query 688 // is common enough that we do click-to-place-cursor). 689 if (select_all_on_mouse_release_ && 690 !controller()->GetToolbarModel()->WouldReplaceURL()) { 691 // Select all in the reverse direction so as not to scroll the caret 692 // into view and shift the contents jarringly. 693 SelectAll(true); 694 } 695 696 HandleOriginChipMouseRelease(); 697 } 698 select_all_on_mouse_release_ = false; 699} 700 701bool OmniboxViewViews::OnKeyPressed(const ui::KeyEvent& event) { 702 // Skip processing of [Alt]+<num-pad digit> Unicode alt key codes. 703 // Otherwise, if num-lock is off, the events are handled as [Up], [Down], etc. 704 if (event.IsUnicodeKeyCode()) 705 return views::Textfield::OnKeyPressed(event); 706 707 const bool shift = event.IsShiftDown(); 708 const bool control = event.IsControlDown(); 709 const bool alt = event.IsAltDown() || event.IsAltGrDown(); 710 switch (event.key_code()) { 711 case ui::VKEY_RETURN: 712 model()->AcceptInput(alt ? NEW_FOREGROUND_TAB : CURRENT_TAB, false); 713 return true; 714 case ui::VKEY_ESCAPE: 715 return model()->OnEscapeKeyPressed(); 716 case ui::VKEY_CONTROL: 717 model()->OnControlKeyChanged(true); 718 break; 719 case ui::VKEY_DELETE: 720 if (shift && model()->popup_model()->IsOpen()) 721 model()->popup_model()->TryDeletingCurrentItem(); 722 break; 723 case ui::VKEY_UP: 724 if (!read_only()) { 725 model()->OnUpOrDownKeyPressed(-1); 726 return true; 727 } 728 break; 729 case ui::VKEY_DOWN: 730 if (!read_only()) { 731 model()->OnUpOrDownKeyPressed(1); 732 return true; 733 } 734 break; 735 case ui::VKEY_PRIOR: 736 if (control || alt || shift) 737 return false; 738 model()->OnUpOrDownKeyPressed(-1 * model()->result().size()); 739 return true; 740 case ui::VKEY_NEXT: 741 if (control || alt || shift) 742 return false; 743 model()->OnUpOrDownKeyPressed(model()->result().size()); 744 return true; 745 case ui::VKEY_V: 746 if (control && !alt && !read_only()) { 747 ExecuteCommand(IDS_APP_PASTE, 0); 748 return true; 749 } 750 break; 751 case ui::VKEY_INSERT: 752 if (shift && !control && !read_only()) { 753 ExecuteCommand(IDS_APP_PASTE, 0); 754 return true; 755 } 756 break; 757 default: 758 break; 759 } 760 761 return views::Textfield::OnKeyPressed(event) || HandleEarlyTabActions(event); 762} 763 764void OmniboxViewViews::OnGestureEvent(ui::GestureEvent* event) { 765 if (!HasFocus() && event->type() == ui::ET_GESTURE_TAP_DOWN) { 766 select_all_on_gesture_tap_ = true; 767 768 // If we're trying to select all on tap, invalidate any saved selection lest 769 // restoring it fights with the "select all" action. 770 saved_selection_for_focus_change_ = gfx::Range::InvalidRange(); 771 } 772 773 views::Textfield::OnGestureEvent(event); 774 775 if (select_all_on_gesture_tap_ && event->type() == ui::ET_GESTURE_TAP) 776 SelectAll(true); 777 778 if (event->type() == ui::ET_GESTURE_TAP || 779 event->type() == ui::ET_GESTURE_TAP_CANCEL || 780 event->type() == ui::ET_GESTURE_TWO_FINGER_TAP || 781 event->type() == ui::ET_GESTURE_SCROLL_BEGIN || 782 event->type() == ui::ET_GESTURE_PINCH_BEGIN || 783 event->type() == ui::ET_GESTURE_LONG_PRESS || 784 event->type() == ui::ET_GESTURE_LONG_TAP) { 785 select_all_on_gesture_tap_ = false; 786 } 787} 788 789void OmniboxViewViews::AboutToRequestFocusFromTabTraversal(bool reverse) { 790 views::Textfield::AboutToRequestFocusFromTabTraversal(reverse); 791 // Tabbing into the omnibox should affect the origin chip in the same way 792 // clicking it should. 793 HandleOriginChipMouseRelease(); 794} 795 796bool OmniboxViewViews::SkipDefaultKeyEventProcessing( 797 const ui::KeyEvent& event) { 798 if (views::FocusManager::IsTabTraversalKeyEvent(event) && 799 ((model()->is_keyword_hint() && !event.IsShiftDown()) || 800 model()->popup_model()->IsOpen())) { 801 return true; 802 } 803 return Textfield::SkipDefaultKeyEventProcessing(event); 804} 805 806void OmniboxViewViews::GetAccessibleState(ui::AXViewState* state) { 807 state->role = ui::AX_ROLE_TEXT_FIELD; 808 state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_LOCATION); 809 state->value = GetText(); 810 811 base::string16::size_type entry_start; 812 base::string16::size_type entry_end; 813 GetSelectionBounds(&entry_start, &entry_end); 814 state->selection_start = entry_start; 815 state->selection_end = entry_end; 816 817 if (popup_window_mode_) { 818 state->AddStateFlag(ui::AX_STATE_READ_ONLY); 819 } else { 820 state->set_value_callback = 821 base::Bind(&OmniboxViewViews::AccessibilitySetValue, 822 weak_ptr_factory_.GetWeakPtr()); 823 } 824 825} 826 827void OmniboxViewViews::OnFocus() { 828 views::Textfield::OnFocus(); 829 // TODO(oshima): Get control key state. 830 model()->OnSetFocus(false); 831 // Don't call controller()->OnSetFocus, this view has already acquired focus. 832 833 // Restore the selection we saved in OnBlur() if it's still valid. 834 if (saved_selection_for_focus_change_.IsValid()) { 835 SelectRange(saved_selection_for_focus_change_); 836 saved_selection_for_focus_change_ = gfx::Range::InvalidRange(); 837 } 838} 839 840void OmniboxViewViews::OnBlur() { 841 // Save the user's existing selection to restore it later. 842 saved_selection_for_focus_change_ = GetSelectedRange(); 843 844 views::Textfield::OnBlur(); 845 gfx::NativeView native_view = NULL; 846 views::Widget* widget = GetWidget(); 847 if (widget) { 848 aura::client::FocusClient* client = 849 aura::client::GetFocusClient(widget->GetNativeView()); 850 if (client) 851 native_view = client->GetFocusedWindow(); 852 } 853 model()->OnWillKillFocus(native_view); 854 // Close the popup. 855 CloseOmniboxPopup(); 856 857 // Tell the model to reset itself. 858 model()->OnKillFocus(); 859 860 // Ignore loss of focus if we lost focus because the website settings popup 861 // is open. When the popup is destroyed, focus will return to the Omnibox. 862 if (!WebsiteSettingsPopupView::IsPopupShowing()) 863 OnDidKillFocus(); 864 865 // Make sure the beginning of the text is visible. 866 SelectRange(gfx::Range(0)); 867} 868 869bool OmniboxViewViews::IsCommandIdEnabled(int command_id) const { 870 if (command_id == IDS_APP_PASTE) 871 return !read_only() && !GetClipboardText().empty(); 872 if (command_id == IDS_PASTE_AND_GO) 873 return !read_only() && model()->CanPasteAndGo(GetClipboardText()); 874 if (command_id == IDS_SHOW_URL) 875 return controller()->GetToolbarModel()->WouldReplaceURL(); 876 return command_id == IDS_MOVE_DOWN || command_id == IDS_MOVE_UP || 877 Textfield::IsCommandIdEnabled(command_id) || 878 command_updater()->IsCommandEnabled(command_id); 879} 880 881base::string16 OmniboxViewViews::GetSelectionClipboardText() const { 882 return SanitizeTextForPaste(Textfield::GetSelectionClipboardText()); 883} 884 885#if defined(OS_CHROMEOS) 886void OmniboxViewViews::CandidateWindowOpened( 887 chromeos::input_method::InputMethodManager* manager) { 888 ime_candidate_window_open_ = true; 889} 890 891void OmniboxViewViews::CandidateWindowClosed( 892 chromeos::input_method::InputMethodManager* manager) { 893 ime_candidate_window_open_ = false; 894} 895#endif 896 897void OmniboxViewViews::ContentsChanged(views::Textfield* sender, 898 const base::string16& new_contents) { 899} 900 901bool OmniboxViewViews::HandleKeyEvent(views::Textfield* textfield, 902 const ui::KeyEvent& event) { 903 delete_at_end_pressed_ = false; 904 905 if (event.key_code() == ui::VKEY_BACK) { 906 // No extra handling is needed in keyword search mode, if there is a 907 // non-empty selection, or if the cursor is not leading the text. 908 if (model()->is_keyword_hint() || model()->keyword().empty() || 909 HasSelection() || GetCursorPosition() != 0) 910 return false; 911 model()->ClearKeyword(text()); 912 return true; 913 } 914 915 if (event.key_code() == ui::VKEY_DELETE && !event.IsAltDown()) { 916 delete_at_end_pressed_ = 917 (!HasSelection() && GetCursorPosition() == text().length()); 918 } 919 920 // Handle the right-arrow key for LTR text and the left-arrow key for RTL text 921 // if there is gray text that needs to be committed. 922 if (GetCursorPosition() == text().length()) { 923 base::i18n::TextDirection direction = GetTextDirection(); 924 if ((direction == base::i18n::LEFT_TO_RIGHT && 925 event.key_code() == ui::VKEY_RIGHT) || 926 (direction == base::i18n::RIGHT_TO_LEFT && 927 event.key_code() == ui::VKEY_LEFT)) { 928 return model()->CommitSuggestedText(); 929 } 930 } 931 932 return false; 933} 934 935void OmniboxViewViews::OnBeforeUserAction(views::Textfield* sender) { 936 OnBeforePossibleChange(); 937} 938 939void OmniboxViewViews::OnAfterUserAction(views::Textfield* sender) { 940 OnAfterPossibleChange(); 941} 942 943void OmniboxViewViews::OnAfterCutOrCopy(ui::ClipboardType clipboard_type) { 944 ui::Clipboard* cb = ui::Clipboard::GetForCurrentThread(); 945 base::string16 selected_text; 946 cb->ReadText(clipboard_type, &selected_text); 947 GURL url; 948 bool write_url; 949 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(), 950 &selected_text, &url, &write_url); 951 if (IsSelectAll()) 952 UMA_HISTOGRAM_COUNTS(OmniboxEditModel::kCutOrCopyAllTextHistogram, 1); 953 954 if (write_url) { 955 BookmarkNodeData data; 956 data.ReadFromTuple(url, selected_text); 957 data.WriteToClipboard(clipboard_type); 958 } else { 959 ui::ScopedClipboardWriter scoped_clipboard_writer( 960 ui::Clipboard::GetForCurrentThread(), clipboard_type); 961 scoped_clipboard_writer.WriteText(selected_text); 962 } 963} 964 965void OmniboxViewViews::OnWriteDragData(ui::OSExchangeData* data) { 966 GURL url; 967 bool write_url; 968 bool is_all_selected = IsSelectAll(); 969 base::string16 selected_text = GetSelectedText(); 970 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), is_all_selected, 971 &selected_text, &url, &write_url); 972 data->SetString(selected_text); 973 if (write_url) { 974 gfx::Image favicon; 975 base::string16 title = selected_text; 976 if (is_all_selected) 977 model()->GetDataForURLExport(&url, &title, &favicon); 978 button_drag_utils::SetURLAndDragImage(url, title, favicon.AsImageSkia(), 979 NULL, data, GetWidget()); 980 data->SetURL(url, title); 981 } 982} 983 984void OmniboxViewViews::OnGetDragOperationsForTextfield(int* drag_operations) { 985 base::string16 selected_text = GetSelectedText(); 986 GURL url; 987 bool write_url; 988 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(), 989 &selected_text, &url, &write_url); 990 if (write_url) 991 *drag_operations |= ui::DragDropTypes::DRAG_LINK; 992} 993 994void OmniboxViewViews::AppendDropFormats( 995 int* formats, 996 std::set<ui::OSExchangeData::CustomFormat>* custom_formats) { 997 *formats = *formats | ui::OSExchangeData::URL; 998} 999 1000int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) { 1001 if (HasTextBeingDragged()) 1002 return ui::DragDropTypes::DRAG_NONE; 1003 1004 if (data.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)) { 1005 GURL url; 1006 base::string16 title; 1007 if (data.GetURLAndTitle( 1008 ui::OSExchangeData::CONVERT_FILENAMES, &url, &title)) { 1009 base::string16 text( 1010 StripJavascriptSchemas(base::UTF8ToUTF16(url.spec()))); 1011 if (model()->CanPasteAndGo(text)) { 1012 model()->PasteAndGo(text); 1013 return ui::DragDropTypes::DRAG_COPY; 1014 } 1015 } 1016 } else if (data.HasString()) { 1017 base::string16 text; 1018 if (data.GetString(&text)) { 1019 base::string16 collapsed_text(base::CollapseWhitespace(text, true)); 1020 if (model()->CanPasteAndGo(collapsed_text)) 1021 model()->PasteAndGo(collapsed_text); 1022 return ui::DragDropTypes::DRAG_COPY; 1023 } 1024 } 1025 1026 return ui::DragDropTypes::DRAG_NONE; 1027} 1028 1029void OmniboxViewViews::UpdateContextMenu(ui::SimpleMenuModel* menu_contents) { 1030 int paste_position = menu_contents->GetIndexOfCommandId(IDS_APP_PASTE); 1031 DCHECK_GE(paste_position, 0); 1032 menu_contents->InsertItemWithStringIdAt( 1033 paste_position + 1, IDS_PASTE_AND_GO, IDS_PASTE_AND_GO); 1034 1035 menu_contents->AddSeparator(ui::NORMAL_SEPARATOR); 1036 1037 if (chrome::IsQueryExtractionEnabled() || chrome::ShouldDisplayOriginChip()) { 1038 int select_all_position = menu_contents->GetIndexOfCommandId( 1039 IDS_APP_SELECT_ALL); 1040 DCHECK_GE(select_all_position, 0); 1041 menu_contents->InsertItemWithStringIdAt( 1042 select_all_position + 1, IDS_SHOW_URL, IDS_SHOW_URL); 1043 } 1044 1045 // Minor note: We use IDC_ for command id here while the underlying textfield 1046 // is using IDS_ for all its command ids. This is because views cannot depend 1047 // on IDC_ for now. 1048 menu_contents->AddItemWithStringId(IDC_EDIT_SEARCH_ENGINES, 1049 IDS_EDIT_SEARCH_ENGINES); 1050} 1051