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