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