omnibox_view_views.cc revision b2df76ea8fec9e32f6f3718986dba0d95315b29c
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/logging.h" 8#include "base/string_util.h" 9#include "base/utf_string_conversions.h" 10#include "chrome/app/chrome_command_ids.h" 11#include "chrome/browser/autocomplete/autocomplete_input.h" 12#include "chrome/browser/autocomplete/autocomplete_match.h" 13#include "chrome/browser/bookmarks/bookmark_node_data.h" 14#include "chrome/browser/chromeos/input_method/input_method_configuration.h" 15#include "chrome/browser/command_updater.h" 16#include "chrome/browser/profiles/profile.h" 17#include "chrome/browser/search/search.h" 18#include "chrome/browser/ui/omnibox/omnibox_edit_controller.h" 19#include "chrome/browser/ui/omnibox/omnibox_edit_model.h" 20#include "chrome/browser/ui/omnibox/omnibox_popup_model.h" 21#include "chrome/browser/ui/view_ids.h" 22#include "chrome/browser/ui/views/location_bar/location_bar_view.h" 23#include "chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h" 24#include "content/public/browser/web_contents.h" 25#include "extensions/common/constants.h" 26#include "googleurl/src/gurl.h" 27#include "grit/app_locale_settings.h" 28#include "grit/generated_resources.h" 29#include "grit/ui_strings.h" 30#include "net/base/escape.h" 31#include "third_party/skia/include/core/SkColor.h" 32#include "ui/base/accessibility/accessible_view_state.h" 33#include "ui/base/clipboard/scoped_clipboard_writer.h" 34#include "ui/base/dragdrop/drag_drop_types.h" 35#include "ui/base/dragdrop/os_exchange_data.h" 36#include "ui/base/events/event.h" 37#include "ui/base/ime/text_input_client.h" 38#include "ui/base/ime/text_input_type.h" 39#include "ui/base/l10n/l10n_util.h" 40#include "ui/base/models/simple_menu_model.h" 41#include "ui/base/resource/resource_bundle.h" 42#include "ui/gfx/canvas.h" 43#include "ui/gfx/font.h" 44#include "ui/gfx/selection_model.h" 45#include "ui/views/border.h" 46#include "ui/views/button_drag_utils.h" 47#include "ui/views/controls/textfield/textfield.h" 48#include "ui/views/ime/input_method.h" 49#include "ui/views/layout/fill_layout.h" 50#include "ui/views/views_delegate.h" 51#include "ui/views/widget/widget.h" 52 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// The following const value is the same as in browser_defaults. 85const int kAutocompleteEditFontPixelSize = 15; 86// Font size 10px (as defined in browser_defaults) is too small for many 87// non-Latin/Greek/Cyrillic (non-LGC) scripts. For pop-up window, the total 88// rectangle is 21px tall and the height available for "ink" is 17px (please 89// refer to kAutocompleteVerticalMarginInPopup). With 12px font size, the 90// tallest glyphs in UI fonts we're building for ChromeOS (across all scripts) 91// still fit within 17px "ink" height. 92const int kAutocompleteEditFontPixelSizeInPopup = 12; 93 94// The following 2 values are based on kAutocompleteEditFontPixelSize and 95// kAutocompleteEditFontPixelSizeInPopup. They should be changed accordingly 96// if font size for autocomplete edit (in popup) change. 97const int kAutocompleteVerticalMargin = 1; 98const int kAutocompleteVerticalMarginInPopup = 2; 99 100int GetEditFontPixelSize(bool popup_window_mode) { 101 return popup_window_mode ? kAutocompleteEditFontPixelSizeInPopup : 102 kAutocompleteEditFontPixelSize; 103} 104 105// This will write |url| and |text| to the clipboard as a well-formed URL. 106void DoCopyURL(const GURL& url, const string16& text, Profile* profile) { 107 BookmarkNodeData data; 108 data.ReadFromTuple(url, text); 109 data.WriteToClipboard(profile); 110} 111 112} // namespace 113 114// static 115const char OmniboxViewViews::kViewClassName[] = "OmniboxViewViews"; 116 117OmniboxViewViews::OmniboxViewViews(OmniboxEditController* controller, 118 ToolbarModel* toolbar_model, 119 Profile* profile, 120 CommandUpdater* command_updater, 121 bool popup_window_mode, 122 LocationBarView* location_bar) 123 : OmniboxView(profile, controller, toolbar_model, command_updater), 124 popup_window_mode_(popup_window_mode), 125 security_level_(ToolbarModel::NONE), 126 ime_composing_before_change_(false), 127 delete_at_end_pressed_(false), 128 location_bar_view_(location_bar), 129 ime_candidate_window_open_(false), 130 select_all_on_mouse_release_(false), 131 select_all_on_gesture_tap_(false) { 132 RemoveBorder(); 133 set_id(VIEW_ID_OMNIBOX); 134} 135 136OmniboxViewViews::~OmniboxViewViews() { 137#if defined(OS_CHROMEOS) 138 chromeos::input_method::GetInputMethodManager()-> 139 RemoveCandidateWindowObserver(this); 140#endif 141 142 // Explicitly teardown members which have a reference to us. Just to be safe 143 // we want them to be destroyed before destroying any other internal state. 144 popup_view_.reset(); 145} 146 147//////////////////////////////////////////////////////////////////////////////// 148// OmniboxViewViews public: 149 150void OmniboxViewViews::Init() { 151 // The height of the text view is going to change based on the font used. We 152 // don't want to stretch the height, and we want it vertically centered. 153 // TODO(oshima): make sure the above happens with views. 154 SetController(this); 155 SetTextInputType(ui::TEXT_INPUT_TYPE_URL); 156 SetBackgroundColor(location_bar_view_->GetColor( 157 ToolbarModel::NONE, LocationBarView::BACKGROUND)); 158 159 if (popup_window_mode_) 160 SetReadOnly(true); 161 162 const int font_size = GetEditFontPixelSize(popup_window_mode_); 163 if (font_size != font().GetFontSize()) 164 SetFont(font().DeriveFont(font_size - font().GetFontSize())); 165 166 // Initialize the popup view using the same font. 167 popup_view_.reset(OmniboxPopupContentsView::Create( 168 font(), this, model(), location_bar_view_)); 169 170 // A null-border to zero out the focused border on textfield. 171 const int vertical_margin = !popup_window_mode_ ? 172 kAutocompleteVerticalMargin : kAutocompleteVerticalMarginInPopup; 173 set_border(views::Border::CreateEmptyBorder(vertical_margin, 0, 174 vertical_margin, 0)); 175#if defined(OS_CHROMEOS) 176 chromeos::input_method::GetInputMethodManager()-> 177 AddCandidateWindowObserver(this); 178#endif 179} 180 181gfx::Font OmniboxViewViews::GetFont() { 182 return font(); 183} 184 185//////////////////////////////////////////////////////////////////////////////// 186// OmniboxViewViews, views::Textfield implementation: 187 188const char* OmniboxViewViews::GetClassName() const { 189 return kViewClassName; 190} 191 192void OmniboxViewViews::OnGestureEvent(ui::GestureEvent* event) { 193 views::Textfield::OnGestureEvent(event); 194 if (!HasFocus() && event->type() == ui::ET_GESTURE_TAP_DOWN) { 195 select_all_on_gesture_tap_ = true; 196 return; 197 } 198 if (select_all_on_gesture_tap_ && event->type() == ui::ET_GESTURE_TAP) 199 SelectAll(false); 200 select_all_on_gesture_tap_ = false; 201} 202 203void OmniboxViewViews::GetAccessibleState(ui::AccessibleViewState* state) { 204 location_bar_view_->GetAccessibleState(state); 205 state->role = ui::AccessibilityTypes::ROLE_TEXT; 206} 207 208void OmniboxViewViews::OnBoundsChanged(const gfx::Rect& previous_bounds) { 209 if (popup_view_->IsOpen()) 210 popup_view_->UpdatePopupAppearance(); 211} 212 213bool OmniboxViewViews::OnMousePressed(const ui::MouseEvent& event) { 214 select_all_on_mouse_release_ = 215 (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) && 216 (!HasFocus() || (model()->focus_state() == OMNIBOX_FOCUS_INVISIBLE)); 217 // Restore caret visibility whenever the user clicks in the omnibox in a way 218 // that would give it focus. We must handle this case separately here because 219 // if the omnibox currently has invisible focus, the mouse event won't trigger 220 // either SetFocus() or OmniboxEditModel::OnSetFocus(). 221 if (select_all_on_mouse_release_) 222 model()->SetCaretVisibility(true); 223 return views::Textfield::OnMousePressed(event); 224} 225 226bool OmniboxViewViews::OnMouseDragged(const ui::MouseEvent& event) { 227 select_all_on_mouse_release_ = false; 228 return views::Textfield::OnMouseDragged(event); 229} 230 231void OmniboxViewViews::OnMouseReleased(const ui::MouseEvent& event) { 232 views::Textfield::OnMouseReleased(event); 233 if ((event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) && 234 select_all_on_mouse_release_) { 235 // Select all in the reverse direction so as not to scroll the caret 236 // into view and shift the contents jarringly. 237 SelectAll(true); 238 } 239 select_all_on_mouse_release_ = false; 240} 241 242bool OmniboxViewViews::OnKeyPressed(const ui::KeyEvent& event) { 243 // Skip processing of [Alt]+<num-pad digit> Unicode alt key codes. 244 // Otherwise, if num-lock is off, the events are handled as [Up], [Down], etc. 245 if (event.IsUnicodeKeyCode()) 246 return views::Textfield::OnKeyPressed(event); 247 248 switch (event.key_code()) { 249 case ui::VKEY_RETURN: 250 model()->AcceptInput(event.IsAltDown() ? NEW_FOREGROUND_TAB : CURRENT_TAB, 251 false); 252 return true; 253 case ui::VKEY_ESCAPE: 254 return model()->OnEscapeKeyPressed(); 255 case ui::VKEY_CONTROL: 256 model()->OnControlKeyChanged(true); 257 break; 258 case ui::VKEY_DELETE: 259 if (event.IsShiftDown() && model()->popup_model()->IsOpen()) 260 model()->popup_model()->TryDeletingCurrentItem(); 261 break; 262 case ui::VKEY_UP: 263 model()->OnUpOrDownKeyPressed(-1); 264 return true; 265 case ui::VKEY_DOWN: 266 model()->OnUpOrDownKeyPressed(1); 267 return true; 268 case ui::VKEY_PRIOR: 269 if (event.IsControlDown() || event.IsAltDown() || 270 event.IsShiftDown()) { 271 return false; 272 } 273 model()->OnUpOrDownKeyPressed(-1 * model()->result().size()); 274 return true; 275 case ui::VKEY_NEXT: 276 if (event.IsControlDown() || event.IsAltDown() || 277 event.IsShiftDown()) { 278 return false; 279 } 280 model()->OnUpOrDownKeyPressed(model()->result().size()); 281 return true; 282 case ui::VKEY_V: 283 if (event.IsControlDown() && !read_only()) { 284 OnBeforePossibleChange(); 285 OnPaste(); 286 OnAfterPossibleChange(); 287 return true; 288 } 289 break; 290 default: 291 break; 292 } 293 294 bool handled = views::Textfield::OnKeyPressed(event); 295#if !defined(OS_WIN) || defined(USE_AURA) 296 // TODO(msw): Avoid this complexity, consolidate cross-platform behavior. 297 handled |= SkipDefaultKeyEventProcessing(event); 298#endif 299 return handled; 300} 301 302bool OmniboxViewViews::OnKeyReleased(const ui::KeyEvent& event) { 303 // The omnibox contents may change while the control key is pressed. 304 if (event.key_code() == ui::VKEY_CONTROL) 305 model()->OnControlKeyChanged(false); 306 return views::Textfield::OnKeyReleased(event); 307} 308 309bool OmniboxViewViews::SkipDefaultKeyEventProcessing( 310 const ui::KeyEvent& event) { 311 // Handle keyword hint tab-to-search and tabbing through dropdown results. 312 // This must run before acclerator handling invokes a focus change on tab. 313 if (views::FocusManager::IsTabTraversalKeyEvent(event)) { 314 if (model()->is_keyword_hint() && !event.IsShiftDown()) { 315 model()->AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_TAB); 316 return true; 317 } 318 if (model()->popup_model()->IsOpen()) { 319 if (event.IsShiftDown() && 320 model()->popup_model()->selected_line_state() == 321 OmniboxPopupModel::KEYWORD) { 322 model()->ClearKeyword(text()); 323 } else { 324 model()->OnUpOrDownKeyPressed(event.IsShiftDown() ? -1 : 1); 325 } 326 return true; 327 } 328 } 329 330 return Textfield::SkipDefaultKeyEventProcessing(event); 331} 332 333void OmniboxViewViews::OnFocus() { 334 views::Textfield::OnFocus(); 335 // TODO(oshima): Get control key state. 336 model()->OnSetFocus(false); 337 // Don't call controller()->OnSetFocus, this view has already acquired focus. 338 339 // Restore a valid saved selection on tab-to-focus. 340 if (saved_temporary_selection_.IsValid() && !select_all_on_mouse_release_) 341 SelectRange(saved_temporary_selection_); 342} 343 344void OmniboxViewViews::OnBlur() { 345 // Save the selection to restore on tab-to-focus. 346 saved_temporary_selection_ = GetSelectedRange(); 347 348 views::Textfield::OnBlur(); 349 gfx::NativeView native_view = NULL; 350#if defined(USE_AURA) 351 views::Widget* widget = GetWidget(); 352 if (widget) { 353 aura::client::FocusClient* client = 354 aura::client::GetFocusClient(widget->GetNativeView()); 355 if (client) 356 native_view = client->GetFocusedWindow(); 357 } 358#endif 359 model()->OnWillKillFocus(native_view); 360 // Close the popup. 361 CloseOmniboxPopup(); 362 // Tell the model to reset itself. 363 model()->OnKillFocus(); 364 controller()->OnKillFocus(); 365 366 // Make sure the beginning of the text is visible. 367 SelectRange(ui::Range(0)); 368} 369 370//////////////////////////////////////////////////////////////////////////////// 371// OmniboxViewViews, OmniboxView implementation: 372 373void OmniboxViewViews::SaveStateToTab(content::WebContents* tab) { 374 DCHECK(tab); 375 376 // We don't want to keep the IME status, so force quit the current 377 // session here. It may affect the selection status, so order is 378 // also important. 379 if (IsIMEComposing()) { 380 GetTextInputClient()->ConfirmCompositionText(); 381 GetInputMethod()->CancelComposition(this); 382 } 383 384 // NOTE: GetStateForTabSwitch may affect GetSelection, so order is important. 385 OmniboxEditModel::State state = model()->GetStateForTabSwitch(); 386 const gfx::SelectionModel selection = GetSelectionModel(); 387 tab->SetUserData(OmniboxState::kKey, new OmniboxState(state, selection)); 388} 389 390void OmniboxViewViews::Update(const content::WebContents* contents) { 391 // NOTE: We're getting the URL text here from the ToolbarModel. 392 bool visibly_changed_permanent_text = 393 model()->UpdatePermanentText(toolbar_model()->GetText(true)); 394 ToolbarModel::SecurityLevel security_level = 395 toolbar_model()->GetSecurityLevel(); 396 bool changed_security_level = (security_level != security_level_); 397 security_level_ = security_level; 398 399 // TODO(msw|oshima): Copied from GTK, determine correct Win/CrOS behavior. 400 if (contents) { 401 RevertAll(); 402 const OmniboxState* state = static_cast<OmniboxState*>( 403 contents->GetUserData(&OmniboxState::kKey)); 404 if (state) { 405 // Restore the saved state and selection. 406 model()->RestoreState(state->model_state); 407 SelectSelectionModel(state->selection_model); 408 // TODO(oshima): Consider saving/restoring edit history. 409 ClearEditHistory(); 410 } 411 } else if (visibly_changed_permanent_text) { 412 RevertAll(); 413 } else if (changed_security_level) { 414 EmphasizeURLComponents(); 415 } 416} 417 418string16 OmniboxViewViews::GetText() const { 419 // TODO(oshima): IME support 420 return text(); 421} 422 423void OmniboxViewViews::SetWindowTextAndCaretPos(const string16& text, 424 size_t caret_pos, 425 bool update_popup, 426 bool notify_text_changed) { 427 const ui::Range range(caret_pos, caret_pos); 428 SetTextAndSelectedRange(text, range); 429 430 if (update_popup) 431 UpdatePopup(); 432 433 if (notify_text_changed) 434 TextChanged(); 435} 436 437void OmniboxViewViews::SetForcedQuery() { 438 const string16 current_text(text()); 439 const size_t start = current_text.find_first_not_of(kWhitespaceUTF16); 440 if (start == string16::npos || (current_text[start] != '?')) 441 SetUserText(ASCIIToUTF16("?")); 442 else 443 SelectRange(ui::Range(current_text.size(), start + 1)); 444} 445 446bool OmniboxViewViews::IsSelectAll() const { 447 // TODO(oshima): IME support. 448 return text() == GetSelectedText(); 449} 450 451bool OmniboxViewViews::DeleteAtEndPressed() { 452 return delete_at_end_pressed_; 453} 454 455void OmniboxViewViews::GetSelectionBounds(string16::size_type* start, 456 string16::size_type* end) const { 457 const ui::Range range = GetSelectedRange(); 458 *start = static_cast<size_t>(range.start()); 459 *end = static_cast<size_t>(range.end()); 460} 461 462void OmniboxViewViews::SelectAll(bool reversed) { 463 views::Textfield::SelectAll(reversed); 464} 465 466void OmniboxViewViews::UpdatePopup() { 467 model()->SetInputInProgress(true); 468 if (ime_candidate_window_open_) 469 return; 470 if (!model()->has_focus()) 471 return; 472 473 // Prevent inline autocomplete when the caret isn't at the end of the text, 474 // and during IME composition editing. 475 const ui::Range sel = GetSelectedRange(); 476 model()->StartAutocomplete( 477 !sel.is_empty(), 478 sel.GetMax() < text().length() || IsIMEComposing()); 479} 480 481void OmniboxViewViews::SetFocus() { 482 RequestFocus(); 483 // Restore caret visibility if focus is explicitly requested. This is 484 // necessary because if we already have invisible focus, the RequestFocus() 485 // call above will short-circuit, preventing us from reaching 486 // OmniboxEditModel::OnSetFocus(), which handles restoring visibility when the 487 // omnibox regains focus after losing focus. 488 model()->SetCaretVisibility(true); 489} 490 491void OmniboxViewViews::ApplyCaretVisibility() { 492 SetCursorEnabled(model()->is_caret_visible()); 493} 494 495void OmniboxViewViews::OnTemporaryTextMaybeChanged( 496 const string16& display_text, 497 bool save_original_selection, 498 bool notify_text_changed) { 499 if (save_original_selection) 500 saved_temporary_selection_ = GetSelectedRange(); 501 502 SetWindowTextAndCaretPos(display_text, display_text.length(), false, 503 notify_text_changed); 504} 505 506bool OmniboxViewViews::OnInlineAutocompleteTextMaybeChanged( 507 const string16& display_text, 508 size_t user_text_length) { 509 if (display_text == text()) 510 return false; 511 ui::Range range(display_text.size(), user_text_length); 512 SetTextAndSelectedRange(display_text, range); 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 calling it breaks Instant-Extended, and isn't needed 521 // otherwise (in regular non-Instant or Instant-but-not-Extended modes). 522 // 523 // Why it breaks Instant-Extended: Instant handles the Escape key separately 524 // (cf: OmniboxEditModel::RevertTemporaryText). Calling TextChanged() makes 525 // the page think the user additionally typed some text, causing it to update 526 // its suggestions dropdown with new suggestions, which is wrong. 527 // 528 // Why it isn't needed: OmniboxPopupModel::ResetToDefaultMatch() has already 529 // been called by now; it would've called TextChanged() if it was warranted. 530} 531 532void OmniboxViewViews::OnBeforePossibleChange() { 533 // Record our state. 534 text_before_change_ = text(); 535 sel_before_change_ = GetSelectedRange(); 536 ime_composing_before_change_ = IsIMEComposing(); 537} 538 539bool OmniboxViewViews::OnAfterPossibleChange() { 540 // See if the text or selection have changed since OnBeforePossibleChange(). 541 const string16 new_text = text(); 542 const ui::Range new_sel = GetSelectedRange(); 543 const bool text_changed = (new_text != text_before_change_) || 544 (ime_composing_before_change_ != IsIMEComposing()); 545 const bool selection_differs = 546 !((sel_before_change_.is_empty() && new_sel.is_empty()) || 547 sel_before_change_.EqualsIgnoringDirection(new_sel)); 548 549 // When the user has deleted text, we don't allow inline autocomplete. Make 550 // sure to not flag cases like selecting part of the text and then pasting 551 // (or typing) the prefix of that selection. (We detect these by making 552 // sure the caret, which should be after any insertion, hasn't moved 553 // forward of the old selection start.) 554 const bool just_deleted_text = 555 (text_before_change_.length() > new_text.length()) && 556 (new_sel.start() <= sel_before_change_.GetMin()); 557 558 const bool something_changed = model()->OnAfterPossibleChange( 559 text_before_change_, new_text, new_sel.start(), new_sel.end(), 560 selection_differs, text_changed, just_deleted_text, !IsIMEComposing()); 561 562 // If only selection was changed, we don't need to call model()'s 563 // OnChanged() method, which is called in TextChanged(). 564 // But we still need to call EmphasizeURLComponents() to make sure the text 565 // attributes are updated correctly. 566 if (something_changed && text_changed) 567 TextChanged(); 568 else if (selection_differs) 569 EmphasizeURLComponents(); 570 else if (delete_at_end_pressed_) 571 model()->OnChanged(); 572 573 return something_changed; 574} 575 576gfx::NativeView OmniboxViewViews::GetNativeView() const { 577 return GetWidget()->GetNativeView(); 578} 579 580gfx::NativeView OmniboxViewViews::GetRelativeWindowForPopup() const { 581 return GetWidget()->GetTopLevelWidget()->GetNativeView(); 582} 583 584void OmniboxViewViews::SetInstantSuggestion(const string16& input) { 585#if defined(OS_WIN) || defined(USE_AURA) 586 location_bar_view_->SetInstantSuggestion(input); 587#endif 588} 589 590string16 OmniboxViewViews::GetInstantSuggestion() const { 591#if defined(OS_WIN) || defined(USE_AURA) 592 return location_bar_view_->GetInstantSuggestion(); 593#else 594 return string16(); 595#endif 596} 597 598int OmniboxViewViews::TextWidth() const { 599 return native_wrapper_->GetWidthNeededForText(); 600} 601 602bool OmniboxViewViews::IsImeComposing() const { 603 return false; 604} 605 606int OmniboxViewViews::GetMaxEditWidth(int entry_width) const { 607 return entry_width; 608} 609 610views::View* OmniboxViewViews::AddToView(views::View* parent) { 611 parent->AddChildView(this); 612 return this; 613} 614 615int OmniboxViewViews::OnPerformDrop(const ui::DropTargetEvent& event) { 616 NOTIMPLEMENTED(); 617 return ui::DragDropTypes::DRAG_NONE; 618} 619 620//////////////////////////////////////////////////////////////////////////////// 621// OmniboxViewViews, views::TextfieldController implementation: 622 623void OmniboxViewViews::ContentsChanged(views::Textfield* sender, 624 const string16& new_contents) { 625} 626 627bool OmniboxViewViews::HandleKeyEvent(views::Textfield* textfield, 628 const ui::KeyEvent& event) { 629 delete_at_end_pressed_ = false; 630 631 if (event.key_code() == ui::VKEY_BACK) { 632 // No extra handling is needed in keyword search mode, if there is a 633 // non-empty selection, or if the cursor is not leading the text. 634 if (model()->is_keyword_hint() || model()->keyword().empty() || 635 HasSelection() || GetCursorPosition() != 0) 636 return false; 637 model()->ClearKeyword(text()); 638 return true; 639 } 640 641 if (event.key_code() == ui::VKEY_DELETE && !event.IsAltDown()) { 642 delete_at_end_pressed_ = 643 (!HasSelection() && GetCursorPosition() == text().length()); 644 } 645 646 // Handle the right-arrow key for LTR text and the left-arrow key for RTL text 647 // if there is an Instant suggestion (gray text) that needs to be committed. 648 if (GetCursorPosition() == text().length()) { 649 base::i18n::TextDirection direction = GetTextDirection(); 650 if ((direction == base::i18n::LEFT_TO_RIGHT && 651 event.key_code() == ui::VKEY_RIGHT) || 652 (direction == base::i18n::RIGHT_TO_LEFT && 653 event.key_code() == ui::VKEY_LEFT)) { 654 return model()->CommitSuggestedText(true); 655 } 656 } 657 658 return false; 659} 660 661void OmniboxViewViews::OnBeforeUserAction(views::Textfield* sender) { 662 OnBeforePossibleChange(); 663} 664 665void OmniboxViewViews::OnAfterUserAction(views::Textfield* sender) { 666 OnAfterPossibleChange(); 667} 668 669void OmniboxViewViews::OnAfterCutOrCopy() { 670 ui::Clipboard* cb = ui::Clipboard::GetForCurrentThread(); 671 string16 selected_text; 672 cb->ReadText(ui::Clipboard::BUFFER_STANDARD, &selected_text); 673 GURL url; 674 bool write_url; 675 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(), 676 &selected_text, &url, &write_url); 677 if (write_url) { 678 DoCopyURL(url, selected_text, model()->profile()); 679 } else { 680 ui::ScopedClipboardWriter scoped_clipboard_writer( 681 ui::Clipboard::GetForCurrentThread(), 682 ui::Clipboard::BUFFER_STANDARD, 683 content::BrowserContext::GetMarkerForOffTheRecordContext( 684 model()->profile())); 685 scoped_clipboard_writer.WriteText(selected_text); 686 } 687} 688 689void OmniboxViewViews::OnGetDragOperationsForTextfield(int* drag_operations) { 690 string16 selected_text = GetSelectedText(); 691 GURL url; 692 bool write_url; 693 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), IsSelectAll(), 694 &selected_text, &url, &write_url); 695 if (write_url) 696 *drag_operations |= ui::DragDropTypes::DRAG_LINK; 697} 698 699void OmniboxViewViews::OnWriteDragData(ui::OSExchangeData* data) { 700 string16 selected_text = GetSelectedText(); 701 GURL url; 702 bool write_url; 703 bool is_all_selected = IsSelectAll(); 704 model()->AdjustTextForCopy(GetSelectedRange().GetMin(), is_all_selected, 705 &selected_text, &url, &write_url); 706 data->SetString(selected_text); 707 if (write_url) { 708 gfx::Image favicon; 709 string16 title = selected_text; 710 if (is_all_selected) 711 model()->GetDataForURLExport(&url, &title, &favicon); 712 button_drag_utils::SetURLAndDragImage(url, title, favicon.AsImageSkia(), 713 data, GetWidget()); 714 data->SetURL(url, title); 715 } 716} 717 718void OmniboxViewViews::AppendDropFormats( 719 int* formats, 720 std::set<ui::OSExchangeData::CustomFormat>* custom_formats) { 721 *formats = *formats | ui::OSExchangeData::URL; 722} 723 724int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) { 725 if (HasTextBeingDragged()) 726 return ui::DragDropTypes::DRAG_NONE; 727 728 if (data.HasURL()) { 729 GURL url; 730 string16 title; 731 if (data.GetURLAndTitle(&url, &title)) { 732 string16 text(StripJavascriptSchemas(UTF8ToUTF16(url.spec()))); 733 if (model()->CanPasteAndGo(text)) { 734 model()->PasteAndGo(text); 735 return ui::DragDropTypes::DRAG_COPY; 736 } 737 } 738 } else if (data.HasString()) { 739 string16 text; 740 if (data.GetString(&text)) { 741 string16 collapsed_text(CollapseWhitespace(text, true)); 742 if (model()->CanPasteAndGo(collapsed_text)) 743 model()->PasteAndGo(collapsed_text); 744 return ui::DragDropTypes::DRAG_COPY; 745 } 746 } 747 748 return ui::DragDropTypes::DRAG_NONE; 749} 750 751void OmniboxViewViews::UpdateContextMenu(ui::SimpleMenuModel* menu_contents) { 752 // Minor note: We use IDC_ for command id here while the underlying textfield 753 // is using IDS_ for all its command ids. This is because views cannot depend 754 // on IDC_ for now. 755 menu_contents->AddItemWithStringId(IDC_EDIT_SEARCH_ENGINES, 756 IDS_EDIT_SEARCH_ENGINES); 757 758 if (chrome::IsQueryExtractionEnabled(model()->profile())) { 759 int copy_position = menu_contents->GetIndexOfCommandId(IDS_APP_COPY); 760 DCHECK(copy_position >= 0); 761 menu_contents->InsertItemWithStringIdAt( 762 copy_position + 1, IDC_COPY_URL, IDS_COPY_URL); 763 } 764 765 int paste_position = menu_contents->GetIndexOfCommandId(IDS_APP_PASTE); 766 DCHECK(paste_position >= 0); 767 menu_contents->InsertItemWithStringIdAt( 768 paste_position + 1, IDS_PASTE_AND_GO, IDS_PASTE_AND_GO); 769} 770 771bool OmniboxViewViews::IsCommandIdEnabled(int command_id) const { 772 if (command_id == IDS_PASTE_AND_GO) 773 return model()->CanPasteAndGo(GetClipboardText()); 774 if (command_id == IDC_COPY_URL) { 775 return !model()->user_input_in_progress() && 776 (toolbar_model()->GetSearchTermsType() != 777 ToolbarModel::NO_SEARCH_TERMS); 778 } 779 return command_updater()->IsCommandEnabled(command_id); 780} 781 782bool OmniboxViewViews::IsItemForCommandIdDynamic(int command_id) const { 783 return command_id == IDS_PASTE_AND_GO; 784} 785 786string16 OmniboxViewViews::GetLabelForCommandId(int command_id) const { 787 if (command_id == IDS_PASTE_AND_GO) { 788 return l10n_util::GetStringUTF16( 789 model()->IsPasteAndSearch(GetClipboardText()) ? 790 IDS_PASTE_AND_SEARCH : IDS_PASTE_AND_GO); 791 } 792 793 return string16(); 794} 795 796bool OmniboxViewViews::HandlesCommand(int command_id) const { 797 // See description in OnPaste() for details on why we need to handle paste. 798 return command_id == IDS_APP_PASTE; 799} 800 801void OmniboxViewViews::ExecuteCommand(int command_id, int event_flags) { 802 switch (command_id) { 803 // These commands don't invoke the popup via OnBefore/AfterPossibleChange(). 804 case IDS_PASTE_AND_GO: 805 model()->PasteAndGo(GetClipboardText()); 806 break; 807 case IDC_EDIT_SEARCH_ENGINES: 808 command_updater()->ExecuteCommand(command_id); 809 break; 810 case IDC_COPY_URL: 811 CopyURL(); 812 break; 813 814 case IDS_APP_PASTE: 815 OnBeforePossibleChange(); 816 OnPaste(); 817 OnAfterPossibleChange(); 818 break; 819 default: 820 OnBeforePossibleChange(); 821 command_updater()->ExecuteCommand(command_id); 822 OnAfterPossibleChange(); 823 break; 824 } 825} 826 827#if defined(OS_CHROMEOS) 828void OmniboxViewViews::CandidateWindowOpened( 829 chromeos::input_method::InputMethodManager* manager) { 830 ime_candidate_window_open_ = true; 831 CloseOmniboxPopup(); 832} 833 834void OmniboxViewViews::CandidateWindowClosed( 835 chromeos::input_method::InputMethodManager* manager) { 836 ime_candidate_window_open_ = false; 837 UpdatePopup(); 838} 839#endif 840 841//////////////////////////////////////////////////////////////////////////////// 842// OmniboxViewViews, private: 843 844int OmniboxViewViews::GetOmniboxTextLength() const { 845 // TODO(oshima): Support instant, 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 instant, IME. 896 return views::Textfield::GetSelectedText(); 897} 898 899void OmniboxViewViews::CopyURL() { 900 DoCopyURL(toolbar_model()->GetURL(), 901 toolbar_model()->GetText(false), 902 model()->profile()); 903} 904 905void OmniboxViewViews::OnPaste() { 906 // Replace the selection if we have something to paste. 907 const string16 text(GetClipboardText()); 908 if (!text.empty()) { 909 // Record this paste, so we can do different behavior. 910 model()->on_paste(); 911 // Force a Paste operation to trigger the text_changed code in 912 // OnAfterPossibleChange(), even if identical contents are pasted. 913 text_before_change_.clear(); 914 ReplaceSelection(text); 915 } 916} 917