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