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