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