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