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