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