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