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