omnibox_view_views.cc revision 7dbb3d5cf0c15f500944d211057644d6a2f37371
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 91} // namespace 92 93// static 94const char OmniboxViewViews::kViewClassName[] = "OmniboxViewViews"; 95 96OmniboxViewViews::OmniboxViewViews(OmniboxEditController* controller, 97 ToolbarModel* toolbar_model, 98 Profile* profile, 99 CommandUpdater* command_updater, 100 bool popup_window_mode, 101 LocationBarView* location_bar, 102 const gfx::Font& font, 103 int font_y_offset) 104 : OmniboxView(profile, controller, toolbar_model, command_updater), 105 popup_window_mode_(popup_window_mode), 106 security_level_(ToolbarModel::NONE), 107 ime_composing_before_change_(false), 108 delete_at_end_pressed_(false), 109 location_bar_view_(location_bar), 110 ime_candidate_window_open_(false), 111 select_all_on_mouse_release_(false), 112 select_all_on_gesture_tap_(false) { 113 RemoveBorder(); 114 set_id(VIEW_ID_OMNIBOX); 115 SetFont(font); 116 SetVerticalMargins(font_y_offset, 0); 117 SetVerticalAlignment(gfx::ALIGN_TOP); 118} 119 120OmniboxViewViews::~OmniboxViewViews() { 121#if defined(OS_CHROMEOS) 122 chromeos::input_method::InputMethodManager::Get()-> 123 RemoveCandidateWindowObserver(this); 124#endif 125 126 // Explicitly teardown members which have a reference to us. Just to be safe 127 // we want them to be destroyed before destroying any other internal state. 128 popup_view_.reset(); 129} 130 131//////////////////////////////////////////////////////////////////////////////// 132// OmniboxViewViews public: 133 134void OmniboxViewViews::Init() { 135 SetController(this); 136 SetTextInputType(ui::TEXT_INPUT_TYPE_URL); 137 SetBackgroundColor(location_bar_view_->GetColor( 138 ToolbarModel::NONE, LocationBarView::BACKGROUND)); 139 140 if (popup_window_mode_) 141 SetReadOnly(true); 142 143 // Initialize the popup view using the same font. 144 popup_view_.reset(OmniboxPopupContentsView::Create( 145 font(), this, model(), location_bar_view_)); 146 147#if defined(OS_CHROMEOS) 148 chromeos::input_method::InputMethodManager::Get()-> 149 AddCandidateWindowObserver(this); 150#endif 151} 152 153//////////////////////////////////////////////////////////////////////////////// 154// OmniboxViewViews, views::Textfield implementation: 155 156const char* OmniboxViewViews::GetClassName() const { 157 return kViewClassName; 158} 159 160void OmniboxViewViews::OnGestureEvent(ui::GestureEvent* event) { 161 views::Textfield::OnGestureEvent(event); 162 if (!HasFocus() && event->type() == ui::ET_GESTURE_TAP_DOWN) { 163 select_all_on_gesture_tap_ = true; 164 return; 165 } 166 if (select_all_on_gesture_tap_ && event->type() == ui::ET_GESTURE_TAP) 167 SelectAll(false); 168 select_all_on_gesture_tap_ = false; 169} 170 171void OmniboxViewViews::GetAccessibleState(ui::AccessibleViewState* state) { 172 location_bar_view_->GetAccessibleState(state); 173 state->role = ui::AccessibilityTypes::ROLE_TEXT; 174} 175 176bool OmniboxViewViews::OnMousePressed(const ui::MouseEvent& event) { 177 select_all_on_mouse_release_ = 178 (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) && 179 (!HasFocus() || (model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE)); 180 // Restore caret visibility whenever the user clicks in the omnibox in a way 181 // that would give it focus. We must handle this case separately here because 182 // if the omnibox currently has invisible focus, the mouse event won't trigger 183 // either SetFocus() or OmniboxEditModel::OnSetFocus(). 184 if (select_all_on_mouse_release_) 185 model()->SetCaretVisibility(true); 186 return views::Textfield::OnMousePressed(event); 187} 188 189bool OmniboxViewViews::OnMouseDragged(const ui::MouseEvent& event) { 190 select_all_on_mouse_release_ = false; 191 return views::Textfield::OnMouseDragged(event); 192} 193 194void OmniboxViewViews::OnMouseReleased(const ui::MouseEvent& event) { 195 views::Textfield::OnMouseReleased(event); 196 if ((event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) && 197 select_all_on_mouse_release_) { 198 // Select all in the reverse direction so as not to scroll the caret 199 // into view and shift the contents jarringly. 200 SelectAll(true); 201 } 202 select_all_on_mouse_release_ = false; 203} 204 205bool OmniboxViewViews::OnKeyPressed(const ui::KeyEvent& event) { 206 // Skip processing of [Alt]+<num-pad digit> Unicode alt key codes. 207 // Otherwise, if num-lock is off, the events are handled as [Up], [Down], etc. 208 if (event.IsUnicodeKeyCode()) 209 return views::Textfield::OnKeyPressed(event); 210 211 switch (event.key_code()) { 212 case ui::VKEY_RETURN: 213 model()->AcceptInput(event.IsAltDown() ? NEW_FOREGROUND_TAB : CURRENT_TAB, 214 false); 215 return true; 216 case ui::VKEY_ESCAPE: 217 return model()->OnEscapeKeyPressed(); 218 case ui::VKEY_CONTROL: 219 model()->OnControlKeyChanged(true); 220 break; 221 case ui::VKEY_DELETE: 222 if (event.IsShiftDown() && model()->popup_model()->IsOpen()) 223 model()->popup_model()->TryDeletingCurrentItem(); 224 break; 225 case ui::VKEY_UP: 226 model()->OnUpOrDownKeyPressed(-1); 227 return true; 228 case ui::VKEY_DOWN: 229 model()->OnUpOrDownKeyPressed(1); 230 return true; 231 case ui::VKEY_PRIOR: 232 if (event.IsControlDown() || event.IsAltDown() || 233 event.IsShiftDown()) { 234 return false; 235 } 236 model()->OnUpOrDownKeyPressed(-1 * model()->result().size()); 237 return true; 238 case ui::VKEY_NEXT: 239 if (event.IsControlDown() || event.IsAltDown() || 240 event.IsShiftDown()) { 241 return false; 242 } 243 model()->OnUpOrDownKeyPressed(model()->result().size()); 244 return true; 245 case ui::VKEY_V: 246 if (event.IsControlDown() && !read_only()) { 247 OnBeforePossibleChange(); 248 OnPaste(); 249 OnAfterPossibleChange(); 250 return true; 251 } 252 break; 253 default: 254 break; 255 } 256 257 bool handled = views::Textfield::OnKeyPressed(event); 258#if !defined(OS_WIN) || defined(USE_AURA) 259 // TODO(msw): Avoid this complexity, consolidate cross-platform behavior. 260 handled |= SkipDefaultKeyEventProcessing(event); 261#endif 262 return handled; 263} 264 265bool OmniboxViewViews::OnKeyReleased(const ui::KeyEvent& event) { 266 // The omnibox contents may change while the control key is pressed. 267 if (event.key_code() == ui::VKEY_CONTROL) 268 model()->OnControlKeyChanged(false); 269 return views::Textfield::OnKeyReleased(event); 270} 271 272bool OmniboxViewViews::SkipDefaultKeyEventProcessing( 273 const ui::KeyEvent& event) { 274 // Handle keyword hint tab-to-search and tabbing through dropdown results. 275 // This must run before acclerator handling invokes a focus change on tab. 276 if (views::FocusManager::IsTabTraversalKeyEvent(event)) { 277 if (model()->is_keyword_hint() && !event.IsShiftDown()) { 278 model()->AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_TAB); 279 return true; 280 } 281 if (model()->popup_model()->IsOpen()) { 282 if (event.IsShiftDown() && 283 model()->popup_model()->selected_line_state() == 284 OmniboxPopupModel::KEYWORD) { 285 model()->ClearKeyword(text()); 286 } else { 287 model()->OnUpOrDownKeyPressed(event.IsShiftDown() ? -1 : 1); 288 } 289 return true; 290 } 291 } 292 293 return Textfield::SkipDefaultKeyEventProcessing(event); 294} 295 296void OmniboxViewViews::OnFocus() { 297 views::Textfield::OnFocus(); 298 // TODO(oshima): Get control key state. 299 model()->OnSetFocus(false); 300 // Don't call controller()->OnSetFocus, this view has already acquired focus. 301 302 // Restore a valid saved selection on tab-to-focus. 303 if (location_bar_view_->GetWebContents() && !select_all_on_mouse_release_) { 304 const OmniboxState* state = static_cast<OmniboxState*>( 305 location_bar_view_->GetWebContents()->GetUserData(&OmniboxState::kKey)); 306 if (state) 307 SelectSelectionModel(state->selection_model); 308 } 309} 310 311void OmniboxViewViews::OnBlur() { 312 // Save the selection to restore on tab-to-focus. 313 if (location_bar_view_->GetWebContents()) 314 SaveStateToTab(location_bar_view_->GetWebContents()); 315 316 views::Textfield::OnBlur(); 317 gfx::NativeView native_view = NULL; 318#if defined(USE_AURA) 319 views::Widget* widget = GetWidget(); 320 if (widget) { 321 aura::client::FocusClient* client = 322 aura::client::GetFocusClient(widget->GetNativeView()); 323 if (client) 324 native_view = client->GetFocusedWindow(); 325 } 326#endif 327 model()->OnWillKillFocus(native_view); 328 // Close the popup. 329 CloseOmniboxPopup(); 330 // Tell the model to reset itself. 331 model()->OnKillFocus(); 332 controller()->OnKillFocus(); 333 334 // Make sure the beginning of the text is visible. 335 SelectRange(ui::Range(0)); 336} 337 338//////////////////////////////////////////////////////////////////////////////// 339// OmniboxViewViews, OmniboxView implementation: 340 341void OmniboxViewViews::SaveStateToTab(content::WebContents* tab) { 342 DCHECK(tab); 343 344 // We don't want to keep the IME status, so force quit the current 345 // session here. It may affect the selection status, so order is 346 // also important. 347 if (IsIMEComposing()) { 348 GetTextInputClient()->ConfirmCompositionText(); 349 GetInputMethod()->CancelComposition(this); 350 } 351 352 // NOTE: GetStateForTabSwitch may affect GetSelection, so order is important. 353 OmniboxEditModel::State state = model()->GetStateForTabSwitch(); 354 const gfx::SelectionModel selection = GetSelectionModel(); 355 tab->SetUserData(OmniboxState::kKey, new OmniboxState(state, selection)); 356} 357 358void OmniboxViewViews::Update(const content::WebContents* contents) { 359 // NOTE: We're getting the URL text here from the ToolbarModel. 360 bool visibly_changed_permanent_text = 361 model()->UpdatePermanentText(toolbar_model()->GetText(true)); 362 ToolbarModel::SecurityLevel security_level = 363 toolbar_model()->GetSecurityLevel(); 364 bool changed_security_level = (security_level != security_level_); 365 security_level_ = security_level; 366 367 if (contents) { 368 RevertAll(); 369 const OmniboxState* state = static_cast<OmniboxState*>( 370 contents->GetUserData(&OmniboxState::kKey)); 371 if (state) { 372 // Restore the saved state and selection. 373 model()->RestoreState(state->model_state); 374 SelectSelectionModel(state->selection_model); 375 // TODO(msw|oshima): Consider saving/restoring edit history. 376 ClearEditHistory(); 377 } 378 } else if (visibly_changed_permanent_text) { 379 // Not switching tabs, just updating the permanent text. (In the case where 380 // we _were_ switching tabs, the RevertAll() above already drew the new 381 // permanent text.) 382 383 // Tweak: if the user had all the text selected, select all the new text. 384 // This makes one particular case better: the user clicks in the box to 385 // change it right before the permanent URL is changed. Since the new URL 386 // is still fully selected, the user's typing will replace the edit contents 387 // as they'd intended. 388 const ui::Range range(GetSelectedRange()); 389 const bool was_select_all = (range.length() == text().length()); 390 391 RevertAll(); 392 393 // Only select all when we have focus. If we don't have focus, selecting 394 // all is unnecessary since the selection will change on regaining focus, 395 // and can in fact cause artifacts, e.g. if the user is on the NTP and 396 // clicks a link to navigate, causing |was_select_all| to be vacuously true 397 // for the empty omnibox, and we then select all here, leading to the 398 // trailing portion of a long URL being scrolled into view. We could try 399 // and address cases like this, but it seems better to just not muck with 400 // things when the omnibox isn't focused to begin with. 401 if (was_select_all && model()->has_focus()) 402 SelectAll(range.is_reversed()); 403 } else if (changed_security_level) { 404 EmphasizeURLComponents(); 405 } 406} 407 408string16 OmniboxViewViews::GetText() const { 409 // TODO(oshima): IME support 410 return text(); 411} 412 413void OmniboxViewViews::SetWindowTextAndCaretPos(const string16& text, 414 size_t caret_pos, 415 bool update_popup, 416 bool notify_text_changed) { 417 const ui::Range range(caret_pos, caret_pos); 418 SetTextAndSelectedRange(text, range); 419 420 if (update_popup) 421 UpdatePopup(); 422 423 if (notify_text_changed) 424 TextChanged(); 425} 426 427void OmniboxViewViews::SetForcedQuery() { 428 const string16 current_text(text()); 429 const size_t start = current_text.find_first_not_of(kWhitespaceUTF16); 430 if (start == string16::npos || (current_text[start] != '?')) 431 SetUserText(ASCIIToUTF16("?")); 432 else 433 SelectRange(ui::Range(current_text.size(), start + 1)); 434} 435 436bool OmniboxViewViews::IsSelectAll() const { 437 // TODO(oshima): IME support. 438 return text() == GetSelectedText(); 439} 440 441bool OmniboxViewViews::DeleteAtEndPressed() { 442 return delete_at_end_pressed_; 443} 444 445void OmniboxViewViews::GetSelectionBounds(string16::size_type* start, 446 string16::size_type* end) const { 447 const ui::Range range = GetSelectedRange(); 448 *start = static_cast<size_t>(range.start()); 449 *end = static_cast<size_t>(range.end()); 450} 451 452void OmniboxViewViews::SelectAll(bool reversed) { 453 views::Textfield::SelectAll(reversed); 454} 455 456void OmniboxViewViews::UpdatePopup() { 457 model()->SetInputInProgress(true); 458 if (!model()->has_focus()) 459 return; 460 461 // Hide the inline autocompletion for IME users. 462 location_bar_view_->SetImeInlineAutocompletion(string16()); 463 464 // Prevent inline autocomplete when the caret isn't at the end of the text, 465 // and during IME composition editing unless 466 // |kEnableOmniboxAutoCompletionForIme| is enabled. 467 const ui::Range sel = GetSelectedRange(); 468 model()->StartAutocomplete( 469 !sel.is_empty(), 470 sel.GetMax() < text().length() || 471 (IsIMEComposing() && !CommandLine::ForCurrentProcess()->HasSwitch( 472 switches::kEnableOmniboxAutoCompletionForIme))); 473} 474 475void OmniboxViewViews::SetFocus() { 476 RequestFocus(); 477 // Restore caret visibility if focus is explicitly requested. This is 478 // necessary because if we already have invisible focus, the RequestFocus() 479 // call above will short-circuit, preventing us from reaching 480 // OmniboxEditModel::OnSetFocus(), which handles restoring visibility when the 481 // omnibox regains focus after losing focus. 482 model()->SetCaretVisibility(true); 483} 484 485void OmniboxViewViews::ApplyCaretVisibility() { 486 SetCursorEnabled(model()->is_caret_visible()); 487} 488 489void OmniboxViewViews::OnTemporaryTextMaybeChanged( 490 const string16& display_text, 491 bool save_original_selection, 492 bool notify_text_changed) { 493 if (save_original_selection) 494 saved_temporary_selection_ = GetSelectedRange(); 495 496 SetWindowTextAndCaretPos(display_text, display_text.length(), false, 497 notify_text_changed); 498} 499 500bool OmniboxViewViews::OnInlineAutocompleteTextMaybeChanged( 501 const string16& display_text, 502 size_t user_text_length) { 503 if (display_text == text()) 504 return false; 505 506 if (IsIMEComposing()) { 507 location_bar_view_->SetImeInlineAutocompletion( 508 display_text.substr(user_text_length)); 509 } else { 510 ui::Range range(display_text.size(), user_text_length); 511 SetTextAndSelectedRange(display_text, range); 512 } 513 TextChanged(); 514 return true; 515} 516 517void OmniboxViewViews::OnRevertTemporaryText() { 518 SelectRange(saved_temporary_selection_); 519 // We got here because the user hit the Escape key. We explicitly don't call 520 // TextChanged(), since OmniboxPopupModel::ResetToDefaultMatch() has already 521 // been called by now, and it would've called TextChanged() if it was 522 // warranted. 523} 524 525void OmniboxViewViews::OnBeforePossibleChange() { 526 // Record our state. 527 text_before_change_ = text(); 528 sel_before_change_ = GetSelectedRange(); 529 ime_composing_before_change_ = IsIMEComposing(); 530} 531 532bool OmniboxViewViews::OnAfterPossibleChange() { 533 // See if the text or selection have changed since OnBeforePossibleChange(). 534 const string16 new_text = text(); 535 const ui::Range new_sel = GetSelectedRange(); 536 const bool text_changed = (new_text != text_before_change_) || 537 (ime_composing_before_change_ != IsIMEComposing()); 538 const bool selection_differs = 539 !((sel_before_change_.is_empty() && new_sel.is_empty()) || 540 sel_before_change_.EqualsIgnoringDirection(new_sel)); 541 542 // When the user has deleted text, we don't allow inline autocomplete. Make 543 // sure to not flag cases like selecting part of the text and then pasting 544 // (or typing) the prefix of that selection. (We detect these by making 545 // sure the caret, which should be after any insertion, hasn't moved 546 // forward of the old selection start.) 547 const bool just_deleted_text = 548 (text_before_change_.length() > new_text.length()) && 549 (new_sel.start() <= sel_before_change_.GetMin()); 550 551 const bool something_changed = model()->OnAfterPossibleChange( 552 text_before_change_, new_text, new_sel.start(), new_sel.end(), 553 selection_differs, text_changed, just_deleted_text, !IsIMEComposing()); 554 555 // If only selection was changed, we don't need to call model()'s 556 // OnChanged() method, which is called in TextChanged(). 557 // But we still need to call EmphasizeURLComponents() to make sure the text 558 // attributes are updated correctly. 559 if (something_changed && text_changed) 560 TextChanged(); 561 else if (selection_differs) 562 EmphasizeURLComponents(); 563 else if (delete_at_end_pressed_) 564 model()->OnChanged(); 565 566 return something_changed; 567} 568 569gfx::NativeView OmniboxViewViews::GetNativeView() const { 570 return GetWidget()->GetNativeView(); 571} 572 573gfx::NativeView OmniboxViewViews::GetRelativeWindowForPopup() const { 574 return GetWidget()->GetTopLevelWidget()->GetNativeView(); 575} 576 577void OmniboxViewViews::SetGrayTextAutocompletion(const string16& input) { 578#if defined(OS_WIN) || defined(USE_AURA) 579 location_bar_view_->SetGrayTextAutocompletion(input); 580#endif 581} 582 583string16 OmniboxViewViews::GetGrayTextAutocompletion() const { 584#if defined(OS_WIN) || defined(USE_AURA) 585 return location_bar_view_->GetGrayTextAutocompletion(); 586#else 587 return string16(); 588#endif 589} 590 591int OmniboxViewViews::TextWidth() const { 592 return native_wrapper_->GetWidthNeededForText(); 593} 594 595bool OmniboxViewViews::IsImeComposing() const { 596 return IsIMEComposing(); 597} 598 599bool OmniboxViewViews::IsImeShowingPopup() const { 600#if defined(OS_CHROMEOS) 601 return ime_candidate_window_open_; 602#else 603 // We need const_cast here because there is no const version of 604 // View::GetInputMethod(). It's because Widget::GetInputMethod(), called from 605 // View::GetInputMethod(), creates a new views::InputMethod at the first-time 606 // call. Except for this point, none of this method, View::GetInputMethod() 607 // or Widget::GetInputMethod() modifies the state of their instances. 608 // TODO(yukishiino): Make {View,Widget}::GetInputMethod() const and make the 609 // underlying input method object mutable. 610 const views::InputMethod* input_method = 611 const_cast<OmniboxViewViews*>(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 toolbar_model()->WouldReplaceSearchURLWithSearchTerms() && 783 !model()->user_input_in_progress(); 784 } 785 return command_updater()->IsCommandEnabled(command_id); 786} 787 788bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id) const { 789 return command_id == IDS_PASTE_AND_GO; 790} 791 792string16 OmniboxViewViews::GetLabelForCommandId(int command_id) const { 793 if (command_id == IDS_PASTE_AND_GO) { 794 return l10n_util::GetStringUTF16( 795 model()->IsPasteAndSearch(GetClipboardText()) ? 796 IDS_PASTE_AND_SEARCH : IDS_PASTE_AND_GO); 797 } 798 799 return string16(); 800} 801 802bool OmniboxViewViews::HandlesCommand(int command_id) const { 803 // See description in OnPaste() for details on why we need to handle paste. 804 return command_id == IDS_APP_PASTE; 805} 806 807void OmniboxViewViews::ExecuteCommand(int command_id, int event_flags) { 808 switch (command_id) { 809 // These commands don't invoke the popup via OnBefore/AfterPossibleChange(). 810 case IDS_PASTE_AND_GO: 811 model()->PasteAndGo(GetClipboardText()); 812 break; 813 case IDC_EDIT_SEARCH_ENGINES: 814 command_updater()->ExecuteCommand(command_id); 815 break; 816 case IDC_COPY_URL: 817 CopyURL(); 818 break; 819 820 case IDS_APP_PASTE: 821 OnBeforePossibleChange(); 822 OnPaste(); 823 OnAfterPossibleChange(); 824 break; 825 default: 826 OnBeforePossibleChange(); 827 command_updater()->ExecuteCommand(command_id); 828 OnAfterPossibleChange(); 829 break; 830 } 831} 832 833#if defined(OS_CHROMEOS) 834void OmniboxViewViews::CandidateWindowOpened( 835 chromeos::input_method::InputMethodManager* manager) { 836 ime_candidate_window_open_ = true; 837} 838 839void OmniboxViewViews::CandidateWindowClosed( 840 chromeos::input_method::InputMethodManager* manager) { 841 ime_candidate_window_open_ = false; 842} 843#endif 844 845//////////////////////////////////////////////////////////////////////////////// 846// OmniboxViewViews, private: 847 848int OmniboxViewViews::GetOmniboxTextLength() const { 849 // TODO(oshima): Support IME. 850 return static_cast<int>(text().length()); 851} 852 853void OmniboxViewViews::EmphasizeURLComponents() { 854 // See whether the contents are a URL with a non-empty host portion, which we 855 // should emphasize. To check for a URL, rather than using the type returned 856 // by Parse(), ask the model, which will check the desired page transition for 857 // this input. This can tell us whether an UNKNOWN input string is going to 858 // be treated as a search or a navigation, and is the same method the Paste 859 // And Go system uses. 860 url_parse::Component scheme, host; 861 AutocompleteInput::ParseForEmphasizeComponents(text(), &scheme, &host); 862 bool grey_out_url = text().substr(scheme.begin, scheme.len) == 863 UTF8ToUTF16(extensions::kExtensionScheme); 864 bool grey_base = model()->CurrentTextIsURL() && 865 (host.is_nonempty() || grey_out_url); 866 SetColor(location_bar_view_->GetColor( 867 security_level_, 868 grey_base ? LocationBarView::DEEMPHASIZED_TEXT : LocationBarView::TEXT)); 869 if (grey_base && !grey_out_url) { 870 ApplyColor( 871 location_bar_view_->GetColor(security_level_, LocationBarView::TEXT), 872 ui::Range(host.begin, host.end())); 873 } 874 875 // Emphasize the scheme for security UI display purposes (if necessary). 876 // Note that we check CurrentTextIsURL() because if we're replacing search 877 // URLs with search terms, we may have a non-URL even when the user is not 878 // editing; and in some cases, e.g. for "site:foo.com" searches, the parser 879 // may have incorrectly identified a qualifier as a scheme. 880 SetStyle(gfx::DIAGONAL_STRIKE, false); 881 if (!model()->user_input_in_progress() && model()->CurrentTextIsURL() && 882 scheme.is_nonempty() && (security_level_ != ToolbarModel::NONE)) { 883 SkColor security_color = location_bar_view_->GetColor( 884 security_level_, LocationBarView::SECURITY_TEXT); 885 const bool strike = (security_level_ == ToolbarModel::SECURITY_ERROR); 886 const ui::Range scheme_range(scheme.begin, scheme.end()); 887 ApplyColor(security_color, scheme_range); 888 ApplyStyle(gfx::DIAGONAL_STRIKE, strike, scheme_range); 889 } 890} 891 892void OmniboxViewViews::SetTextAndSelectedRange(const string16& text, 893 const ui::Range& range) { 894 SetText(text); 895 SelectRange(range); 896} 897 898string16 OmniboxViewViews::GetSelectedText() const { 899 // TODO(oshima): Support IME. 900 return views::Textfield::GetSelectedText(); 901} 902 903void OmniboxViewViews::CopyURL() { 904 DoCopyURL(toolbar_model()->GetURL(), toolbar_model()->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