omnibox_edit_model.cc revision 116680a4aac90f2aa7413d9095a592090648e557
1// Copyright 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/omnibox/omnibox_edit_model.h" 6 7#include <algorithm> 8#include <string> 9 10#include "base/auto_reset.h" 11#include "base/format_macros.h" 12#include "base/metrics/histogram.h" 13#include "base/prefs/pref_service.h" 14#include "base/strings/string_number_conversions.h" 15#include "base/strings/string_util.h" 16#include "base/strings/stringprintf.h" 17#include "base/strings/utf_string_conversions.h" 18#include "chrome/app/chrome_command_ids.h" 19#include "chrome/browser/autocomplete/autocomplete_classifier.h" 20#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h" 21#include "chrome/browser/autocomplete/autocomplete_provider.h" 22#include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h" 23#include "chrome/browser/autocomplete/history_url_provider.h" 24#include "chrome/browser/autocomplete/keyword_provider.h" 25#include "chrome/browser/autocomplete/search_provider.h" 26#include "chrome/browser/bookmarks/bookmark_stats.h" 27#include "chrome/browser/chrome_notification_types.h" 28#include "chrome/browser/command_updater.h" 29#include "chrome/browser/extensions/api/omnibox/omnibox_api.h" 30#include "chrome/browser/favicon/favicon_tab_helper.h" 31#include "chrome/browser/google/google_url_tracker_factory.h" 32#include "chrome/browser/net/predictor.h" 33#include "chrome/browser/omnibox/omnibox_log.h" 34#include "chrome/browser/predictors/autocomplete_action_predictor.h" 35#include "chrome/browser/predictors/autocomplete_action_predictor_factory.h" 36#include "chrome/browser/prerender/prerender_field_trial.h" 37#include "chrome/browser/prerender/prerender_manager.h" 38#include "chrome/browser/prerender/prerender_manager_factory.h" 39#include "chrome/browser/profiles/profile.h" 40#include "chrome/browser/search/search.h" 41#include "chrome/browser/search_engines/template_url_service_factory.h" 42#include "chrome/browser/search_engines/ui_thread_search_terms_data.h" 43#include "chrome/browser/sessions/session_tab_helper.h" 44#include "chrome/browser/ui/browser_list.h" 45#include "chrome/browser/ui/omnibox/omnibox_current_page_delegate_impl.h" 46#include "chrome/browser/ui/omnibox/omnibox_edit_controller.h" 47#include "chrome/browser/ui/omnibox/omnibox_navigation_observer.h" 48#include "chrome/browser/ui/omnibox/omnibox_popup_model.h" 49#include "chrome/browser/ui/omnibox/omnibox_popup_view.h" 50#include "chrome/browser/ui/omnibox/omnibox_view.h" 51#include "chrome/browser/ui/search/instant_search_prerenderer.h" 52#include "chrome/browser/ui/search/search_tab_helper.h" 53#include "chrome/browser/ui/toolbar/toolbar_model.h" 54#include "chrome/common/chrome_switches.h" 55#include "chrome/common/pref_names.h" 56#include "chrome/common/url_constants.h" 57#include "components/google/core/browser/google_url_tracker.h" 58#include "components/metrics/proto/omnibox_event.pb.h" 59#include "components/search_engines/template_url.h" 60#include "components/search_engines/template_url_prepopulate_data.h" 61#include "components/search_engines/template_url_service.h" 62#include "components/url_fixer/url_fixer.h" 63#include "content/public/browser/navigation_controller.h" 64#include "content/public/browser/navigation_entry.h" 65#include "content/public/browser/notification_service.h" 66#include "content/public/browser/render_view_host.h" 67#include "content/public/browser/user_metrics.h" 68#include "extensions/common/constants.h" 69#include "ui/gfx/image/image.h" 70#include "url/url_util.h" 71 72using metrics::OmniboxEventProto; 73using predictors::AutocompleteActionPredictor; 74 75 76// Helpers -------------------------------------------------------------------- 77 78namespace { 79 80// Histogram name which counts the number of times that the user text is 81// cleared. IME users are sometimes in the situation that IME was 82// unintentionally turned on and failed to input latin alphabets (ASCII 83// characters) or the opposite case. In that case, users may delete all 84// the text and the user text gets cleared. We'd like to measure how often 85// this scenario happens. 86// 87// Note that since we don't currently correlate "text cleared" events with 88// IME usage, this also captures many other cases where users clear the text; 89// though it explicitly doesn't log deleting all the permanent text as 90// the first action of an editing sequence (see comments in 91// OnAfterPossibleChange()). 92const char kOmniboxUserTextClearedHistogram[] = "Omnibox.UserTextCleared"; 93 94enum UserTextClearedType { 95 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING = 0, 96 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE = 1, 97 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS, 98}; 99 100// Histogram name which counts the number of times the user enters 101// keyword hint mode and via what method. The possible values are listed 102// in the EnteredKeywordModeMethod enum which is defined in the .h file. 103const char kEnteredKeywordModeHistogram[] = "Omnibox.EnteredKeywordMode"; 104 105// Histogram name which counts the number of milliseconds a user takes 106// between focusing and editing the omnibox. 107const char kFocusToEditTimeHistogram[] = "Omnibox.FocusToEditTime"; 108 109// Histogram name which counts the number of milliseconds a user takes 110// between focusing and opening an omnibox match. 111const char kFocusToOpenTimeHistogram[] = "Omnibox.FocusToOpenTimeAnyPopupState"; 112 113// Split the percentage match histograms into buckets based on the width of the 114// omnibox. 115const int kPercentageMatchHistogramWidthBuckets[] = { 400, 700, 1200 }; 116 117void RecordPercentageMatchHistogram(const base::string16& old_text, 118 const base::string16& new_text, 119 bool url_replacement_active, 120 content::PageTransition transition, 121 int omnibox_width) { 122 size_t avg_length = (old_text.length() + new_text.length()) / 2; 123 124 int percent = 0; 125 if (!old_text.empty() && !new_text.empty()) { 126 size_t shorter_length = std::min(old_text.length(), new_text.length()); 127 base::string16::const_iterator end(old_text.begin() + shorter_length); 128 base::string16::const_iterator mismatch( 129 std::mismatch(old_text.begin(), end, new_text.begin()).first); 130 size_t matching_characters = mismatch - old_text.begin(); 131 percent = static_cast<float>(matching_characters) / avg_length * 100; 132 } 133 134 std::string histogram_name; 135 if (url_replacement_active) { 136 if (transition == content::PAGE_TRANSITION_TYPED) { 137 histogram_name = "InstantExtended.PercentageMatchV2_QuerytoURL"; 138 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent); 139 } else { 140 histogram_name = "InstantExtended.PercentageMatchV2_QuerytoQuery"; 141 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent); 142 } 143 } else { 144 if (transition == content::PAGE_TRANSITION_TYPED) { 145 histogram_name = "InstantExtended.PercentageMatchV2_URLtoURL"; 146 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent); 147 } else { 148 histogram_name = "InstantExtended.PercentageMatchV2_URLtoQuery"; 149 UMA_HISTOGRAM_PERCENTAGE(histogram_name, percent); 150 } 151 } 152 153 std::string suffix = "large"; 154 for (size_t i = 0; i < arraysize(kPercentageMatchHistogramWidthBuckets); 155 ++i) { 156 if (omnibox_width < kPercentageMatchHistogramWidthBuckets[i]) { 157 suffix = base::IntToString(kPercentageMatchHistogramWidthBuckets[i]); 158 break; 159 } 160 } 161 162 // Cannot rely on UMA histograms macro because the name of the histogram is 163 // generated dynamically. 164 base::HistogramBase* counter = base::LinearHistogram::FactoryGet( 165 histogram_name + "_" + suffix, 1, 101, 102, 166 base::Histogram::kUmaTargetedHistogramFlag); 167 counter->Add(percent); 168} 169 170} // namespace 171 172 173// OmniboxEditModel::State ---------------------------------------------------- 174 175OmniboxEditModel::State::State(bool user_input_in_progress, 176 const base::string16& user_text, 177 const base::string16& gray_text, 178 const base::string16& keyword, 179 bool is_keyword_hint, 180 bool url_replacement_enabled, 181 OmniboxFocusState focus_state, 182 FocusSource focus_source, 183 const AutocompleteInput& autocomplete_input) 184 : user_input_in_progress(user_input_in_progress), 185 user_text(user_text), 186 gray_text(gray_text), 187 keyword(keyword), 188 is_keyword_hint(is_keyword_hint), 189 url_replacement_enabled(url_replacement_enabled), 190 focus_state(focus_state), 191 focus_source(focus_source), 192 autocomplete_input(autocomplete_input) { 193} 194 195OmniboxEditModel::State::~State() { 196} 197 198 199// OmniboxEditModel ----------------------------------------------------------- 200 201OmniboxEditModel::OmniboxEditModel(OmniboxView* view, 202 OmniboxEditController* controller, 203 Profile* profile) 204 : view_(view), 205 controller_(controller), 206 focus_state_(OMNIBOX_FOCUS_NONE), 207 focus_source_(INVALID), 208 user_input_in_progress_(false), 209 user_input_since_focus_(true), 210 just_deleted_text_(false), 211 has_temporary_text_(false), 212 paste_state_(NONE), 213 control_key_state_(UP), 214 is_keyword_hint_(false), 215 profile_(profile), 216 in_revert_(false), 217 allow_exact_keyword_match_(false) { 218 omnibox_controller_.reset(new OmniboxController(this, profile)); 219 delegate_.reset(new OmniboxCurrentPageDelegateImpl(controller, profile)); 220} 221 222OmniboxEditModel::~OmniboxEditModel() { 223} 224 225const OmniboxEditModel::State OmniboxEditModel::GetStateForTabSwitch() { 226 // Like typing, switching tabs "accepts" the temporary text as the user 227 // text, because it makes little sense to have temporary text when the 228 // popup is closed. 229 if (user_input_in_progress_) { 230 // Weird edge case to match other browsers: if the edit is empty, revert to 231 // the permanent text (so the user can get it back easily) but select it (so 232 // on switching back, typing will "just work"). 233 const base::string16 user_text(UserTextFromDisplayText(view_->GetText())); 234 if (user_text.empty()) { 235 base::AutoReset<bool> tmp(&in_revert_, true); 236 view_->RevertAll(); 237 view_->SelectAll(true); 238 } else { 239 InternalSetUserText(user_text); 240 } 241 } 242 243 UMA_HISTOGRAM_BOOLEAN("Omnibox.SaveStateForTabSwitch.UserInputInProgress", 244 user_input_in_progress_); 245 return State( 246 user_input_in_progress_, user_text_, view_->GetGrayTextAutocompletion(), 247 keyword_, is_keyword_hint_, 248 controller_->GetToolbarModel()->url_replacement_enabled(), 249 focus_state_, focus_source_, input_); 250} 251 252void OmniboxEditModel::RestoreState(const State* state) { 253 // We need to update the permanent text correctly and revert the view 254 // regardless of whether there is saved state. 255 bool url_replacement_enabled = !state || state->url_replacement_enabled; 256 controller_->GetToolbarModel()->set_url_replacement_enabled( 257 url_replacement_enabled); 258 controller_->GetToolbarModel()->set_origin_chip_enabled( 259 url_replacement_enabled); 260 permanent_text_ = controller_->GetToolbarModel()->GetText(); 261 // Don't muck with the search term replacement state, as we've just set it 262 // correctly. 263 view_->RevertWithoutResettingSearchTermReplacement(); 264 // Restore the autocomplete controller's input, or clear it if this is a new 265 // tab. 266 input_ = state ? state->autocomplete_input : AutocompleteInput(); 267 if (!state) 268 return; 269 270 SetFocusState(state->focus_state, OMNIBOX_FOCUS_CHANGE_TAB_SWITCH); 271 focus_source_ = state->focus_source; 272 // Restore any user editing. 273 if (state->user_input_in_progress) { 274 // NOTE: Be sure and set keyword-related state BEFORE invoking 275 // DisplayTextFromUserText(), as its result depends upon this state. 276 keyword_ = state->keyword; 277 is_keyword_hint_ = state->is_keyword_hint; 278 view_->SetUserText(state->user_text, 279 DisplayTextFromUserText(state->user_text), false); 280 view_->SetGrayTextAutocompletion(state->gray_text); 281 } 282} 283 284AutocompleteMatch OmniboxEditModel::CurrentMatch( 285 GURL* alternate_nav_url) const { 286 // If we have a valid match use it. Otherwise get one for the current text. 287 AutocompleteMatch match = omnibox_controller_->current_match(); 288 289 if (!match.destination_url.is_valid()) { 290 GetInfoForCurrentText(&match, alternate_nav_url); 291 } else if (alternate_nav_url) { 292 *alternate_nav_url = AutocompleteResult::ComputeAlternateNavUrl( 293 input_, match); 294 } 295 return match; 296} 297 298bool OmniboxEditModel::UpdatePermanentText() { 299 SearchProvider* search_provider = 300 autocomplete_controller()->search_provider(); 301 if (search_provider && delegate_->CurrentPageExists()) 302 search_provider->set_current_page_url(delegate_->GetURL()); 303 304 // When there's new permanent text, and the user isn't interacting with the 305 // omnibox, we want to revert the edit to show the new text. We could simply 306 // define "interacting" as "the omnibox has focus", but we still allow updates 307 // when the omnibox has focus as long as the user hasn't begun editing, isn't 308 // seeing zerosuggestions (because changing this text would require changing 309 // or hiding those suggestions), and hasn't toggled on "Show URL" (because 310 // this update will re-enable search term replacement, which will be annoying 311 // if the user is trying to copy the URL). When the omnibox doesn't have 312 // focus, we assume the user may have abandoned their interaction and it's 313 // always safe to change the text; this also prevents someone toggling "Show 314 // URL" (which sounds as if it might be persistent) from seeing just that URL 315 // forever afterwards. 316 // 317 // If the page is auto-committing gray text, however, we generally don't want 318 // to make any change to the edit. While auto-commits modify the underlying 319 // permanent URL, they're intended to have no effect on the user's editing 320 // process -- before and after the auto-commit, the omnibox should show the 321 // same user text and the same instant suggestion, even if the auto-commit 322 // happens while the edit doesn't have focus. 323 base::string16 new_permanent_text = controller_->GetToolbarModel()->GetText(); 324 base::string16 gray_text = view_->GetGrayTextAutocompletion(); 325 const bool visibly_changed_permanent_text = 326 (permanent_text_ != new_permanent_text) && 327 (!has_focus() || 328 (!user_input_in_progress_ && 329 !(popup_model() && popup_model()->IsOpen()) && 330 controller_->GetToolbarModel()->url_replacement_enabled())) && 331 (gray_text.empty() || 332 new_permanent_text != user_text_ + gray_text); 333 334 permanent_text_ = new_permanent_text; 335 return visibly_changed_permanent_text; 336} 337 338GURL OmniboxEditModel::PermanentURL() { 339 return url_fixer::FixupURL(base::UTF16ToUTF8(permanent_text_), std::string()); 340} 341 342void OmniboxEditModel::SetUserText(const base::string16& text) { 343 SetInputInProgress(true); 344 InternalSetUserText(text); 345 omnibox_controller_->InvalidateCurrentMatch(); 346 paste_state_ = NONE; 347 has_temporary_text_ = false; 348} 349 350bool OmniboxEditModel::CommitSuggestedText() { 351 const base::string16 suggestion = view_->GetGrayTextAutocompletion(); 352 if (suggestion.empty()) 353 return false; 354 355 const base::string16 final_text = view_->GetText() + suggestion; 356 view_->OnBeforePossibleChange(); 357 view_->SetWindowTextAndCaretPos(final_text, final_text.length(), false, 358 false); 359 view_->OnAfterPossibleChange(); 360 return true; 361} 362 363void OmniboxEditModel::OnChanged() { 364 // Don't call CurrentMatch() when there's no editing, as in this case we'll 365 // never actually use it. This avoids running the autocomplete providers (and 366 // any systems they then spin up) during startup. 367 const AutocompleteMatch& current_match = user_input_in_progress_ ? 368 CurrentMatch(NULL) : AutocompleteMatch(); 369 370 AutocompleteActionPredictor::Action recommended_action = 371 AutocompleteActionPredictor::ACTION_NONE; 372 if (user_input_in_progress_) { 373 InstantSearchPrerenderer* prerenderer = 374 InstantSearchPrerenderer::GetForProfile(profile_); 375 if (prerenderer && 376 prerenderer->IsAllowed(current_match, controller_->GetWebContents()) && 377 popup_model()->IsOpen() && has_focus()) { 378 recommended_action = AutocompleteActionPredictor::ACTION_PRERENDER; 379 } else { 380 AutocompleteActionPredictor* action_predictor = 381 predictors::AutocompleteActionPredictorFactory::GetForProfile( 382 profile_); 383 action_predictor->RegisterTransitionalMatches(user_text_, result()); 384 // Confer with the AutocompleteActionPredictor to determine what action, 385 // if any, we should take. Get the recommended action here even if we 386 // don't need it so we can get stats for anyone who is opted in to UMA, 387 // but only get it if the user has actually typed something to avoid 388 // constructing it before it's needed. Note: This event is triggered as 389 // part of startup when the initial tab transitions to the start page. 390 recommended_action = 391 action_predictor->RecommendAction(user_text_, current_match); 392 } 393 } 394 395 UMA_HISTOGRAM_ENUMERATION("AutocompleteActionPredictor.Action", 396 recommended_action, 397 AutocompleteActionPredictor::LAST_PREDICT_ACTION); 398 399 // Hide any suggestions we might be showing. 400 view_->SetGrayTextAutocompletion(base::string16()); 401 402 switch (recommended_action) { 403 case AutocompleteActionPredictor::ACTION_PRERENDER: 404 // It's possible that there is no current page, for instance if the tab 405 // has been closed or on return from a sleep state. 406 // (http://crbug.com/105689) 407 if (!delegate_->CurrentPageExists()) 408 break; 409 // Ask for prerendering if the destination URL is different than the 410 // current URL. 411 if (current_match.destination_url != delegate_->GetURL()) 412 delegate_->DoPrerender(current_match); 413 break; 414 case AutocompleteActionPredictor::ACTION_PRECONNECT: 415 omnibox_controller_->DoPreconnect(current_match); 416 break; 417 case AutocompleteActionPredictor::ACTION_NONE: 418 break; 419 } 420 421 controller_->OnChanged(); 422} 423 424void OmniboxEditModel::GetDataForURLExport(GURL* url, 425 base::string16* title, 426 gfx::Image* favicon) { 427 *url = CurrentMatch(NULL).destination_url; 428 if (*url == delegate_->GetURL()) { 429 content::WebContents* web_contents = controller_->GetWebContents(); 430 *title = web_contents->GetTitle(); 431 *favicon = FaviconTabHelper::FromWebContents(web_contents)->GetFavicon(); 432 } 433} 434 435bool OmniboxEditModel::CurrentTextIsURL() const { 436 if (controller_->GetToolbarModel()->WouldReplaceURL()) 437 return false; 438 439 // If current text is not composed of replaced search terms and 440 // !user_input_in_progress_, then permanent text is showing and should be a 441 // URL, so no further checking is needed. By avoiding checking in this case, 442 // we avoid calling into the autocomplete providers, and thus initializing the 443 // history system, as long as possible, which speeds startup. 444 if (!user_input_in_progress_) 445 return true; 446 447 return !AutocompleteMatch::IsSearchType(CurrentMatch(NULL).type); 448} 449 450AutocompleteMatch::Type OmniboxEditModel::CurrentTextType() const { 451 return CurrentMatch(NULL).type; 452} 453 454void OmniboxEditModel::AdjustTextForCopy(int sel_min, 455 bool is_all_selected, 456 base::string16* text, 457 GURL* url, 458 bool* write_url) { 459 *write_url = false; 460 461 // Do not adjust if selection did not start at the beginning of the field, or 462 // if the URL was omitted. 463 if ((sel_min != 0) || controller_->GetToolbarModel()->WouldReplaceURL()) 464 return; 465 466 if (!user_input_in_progress_ && is_all_selected) { 467 // The user selected all the text and has not edited it. Use the url as the 468 // text so that if the scheme was stripped it's added back, and the url 469 // is unescaped (we escape parts of the url for display). 470 *url = PermanentURL(); 471 *text = base::UTF8ToUTF16(url->spec()); 472 *write_url = true; 473 return; 474 } 475 476 // We can't use CurrentTextIsURL() or GetDataForURLExport() because right now 477 // the user is probably holding down control to cause the copy, which will 478 // screw up our calculation of the desired_tld. 479 AutocompleteMatch match; 480 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify( 481 *text, is_keyword_selected(), true, ClassifyPage(), &match, NULL); 482 if (AutocompleteMatch::IsSearchType(match.type)) 483 return; 484 *url = match.destination_url; 485 486 // Prefix the text with 'http://' if the text doesn't start with 'http://', 487 // the text parses as a url with a scheme of http, the user selected the 488 // entire host, and the user hasn't edited the host or manually removed the 489 // scheme. 490 GURL perm_url(PermanentURL()); 491 if (perm_url.SchemeIs(url::kHttpScheme) && 492 url->SchemeIs(url::kHttpScheme) && perm_url.host() == url->host()) { 493 *write_url = true; 494 base::string16 http = base::ASCIIToUTF16(url::kHttpScheme) + 495 base::ASCIIToUTF16(url::kStandardSchemeSeparator); 496 if (text->compare(0, http.length(), http) != 0) 497 *text = http + *text; 498 } 499} 500 501void OmniboxEditModel::SetInputInProgress(bool in_progress) { 502 if (in_progress && !user_input_since_focus_) { 503 base::TimeTicks now = base::TimeTicks::Now(); 504 DCHECK(last_omnibox_focus_ <= now); 505 UMA_HISTOGRAM_TIMES(kFocusToEditTimeHistogram, now - last_omnibox_focus_); 506 user_input_since_focus_ = true; 507 } 508 509 if (user_input_in_progress_ == in_progress) 510 return; 511 512 user_input_in_progress_ = in_progress; 513 if (user_input_in_progress_) { 514 time_user_first_modified_omnibox_ = base::TimeTicks::Now(); 515 content::RecordAction(base::UserMetricsAction("OmniboxInputInProgress")); 516 autocomplete_controller()->ResetSession(); 517 } 518 519 // The following code handles two cases: 520 // * For HIDE_ON_USER_INPUT and ON_SRP, it hides the chip when user input 521 // begins. 522 // * For HIDE_ON_MOUSE_RELEASE, which only hides the chip on mouse release if 523 // the omnibox is empty, it handles the "omnibox was not empty" case by 524 // acting like HIDE_ON_USER_INPUT. 525 if (chrome::ShouldDisplayOriginChip() && in_progress) 526 controller()->GetToolbarModel()->set_origin_chip_enabled(false); 527 528 controller_->GetToolbarModel()->set_input_in_progress(in_progress); 529 controller_->EndOriginChipAnimations(true); 530 controller_->Update(NULL); 531 532 if (user_input_in_progress_ || !in_revert_) 533 delegate_->OnInputStateChanged(); 534} 535 536void OmniboxEditModel::Revert() { 537 SetInputInProgress(false); 538 paste_state_ = NONE; 539 InternalSetUserText(base::string16()); 540 keyword_.clear(); 541 is_keyword_hint_ = false; 542 has_temporary_text_ = false; 543 view_->SetWindowTextAndCaretPos(permanent_text_, 544 has_focus() ? permanent_text_.length() : 0, 545 false, true); 546 AutocompleteActionPredictor* action_predictor = 547 predictors::AutocompleteActionPredictorFactory::GetForProfile(profile_); 548 action_predictor->ClearTransitionalMatches(); 549 action_predictor->CancelPrerender(); 550} 551 552void OmniboxEditModel::StartAutocomplete( 553 bool has_selected_text, 554 bool prevent_inline_autocomplete) { 555 size_t cursor_position; 556 if (inline_autocomplete_text_.empty()) { 557 // Cursor position is equivalent to the current selection's end. 558 size_t start; 559 view_->GetSelectionBounds(&start, &cursor_position); 560 // Adjust cursor position taking into account possible keyword in the user 561 // text. We rely on DisplayTextFromUserText() method which is consistent 562 // with keyword extraction done in KeywordProvider/SearchProvider. 563 const size_t cursor_offset = 564 user_text_.length() - DisplayTextFromUserText(user_text_).length(); 565 cursor_position += cursor_offset; 566 } else { 567 // There are some cases where StartAutocomplete() may be called 568 // with non-empty |inline_autocomplete_text_|. In such cases, we cannot 569 // use the current selection, because it could result with the cursor 570 // position past the last character from the user text. Instead, 571 // we assume that the cursor is simply at the end of input. 572 // One example is when user presses Ctrl key while having a highlighted 573 // inline autocomplete text. 574 // TODO: Rethink how we are going to handle this case to avoid 575 // inconsistent behavior when user presses Ctrl key. 576 // See http://crbug.com/165961 and http://crbug.com/165968 for more details. 577 cursor_position = user_text_.length(); 578 } 579 580 GURL current_url = 581 (delegate_->CurrentPageExists() && view_->IsIndicatingQueryRefinement()) ? 582 delegate_->GetURL() : GURL(); 583 input_ = AutocompleteInput( 584 user_text_, cursor_position, base::string16(), current_url, 585 ClassifyPage(), 586 prevent_inline_autocomplete || just_deleted_text_ || 587 (has_selected_text && inline_autocomplete_text_.empty()) || 588 (paste_state_ != NONE), 589 is_keyword_selected(), 590 is_keyword_selected() || allow_exact_keyword_match_, 591 true, ChromeAutocompleteSchemeClassifier(profile_)); 592 593 omnibox_controller_->StartAutocomplete(input_); 594} 595 596void OmniboxEditModel::StopAutocomplete() { 597 autocomplete_controller()->Stop(true); 598} 599 600bool OmniboxEditModel::CanPasteAndGo(const base::string16& text) const { 601 if (!view_->command_updater()->IsCommandEnabled(IDC_OPEN_CURRENT_URL)) 602 return false; 603 604 AutocompleteMatch match; 605 ClassifyStringForPasteAndGo(text, &match, NULL); 606 return match.destination_url.is_valid(); 607} 608 609void OmniboxEditModel::PasteAndGo(const base::string16& text) { 610 DCHECK(CanPasteAndGo(text)); 611 UMA_HISTOGRAM_COUNTS("Omnibox.PasteAndGo", 1); 612 613 view_->RevertAll(); 614 AutocompleteMatch match; 615 GURL alternate_nav_url; 616 ClassifyStringForPasteAndGo(text, &match, &alternate_nav_url); 617 view_->OpenMatch(match, CURRENT_TAB, alternate_nav_url, text, 618 OmniboxPopupModel::kNoMatch); 619} 620 621bool OmniboxEditModel::IsPasteAndSearch(const base::string16& text) const { 622 AutocompleteMatch match; 623 ClassifyStringForPasteAndGo(text, &match, NULL); 624 return AutocompleteMatch::IsSearchType(match.type); 625} 626 627void OmniboxEditModel::AcceptInput(WindowOpenDisposition disposition, 628 bool for_drop) { 629 // Get the URL and transition type for the selected entry. 630 GURL alternate_nav_url; 631 AutocompleteMatch match = CurrentMatch(&alternate_nav_url); 632 633 // If CTRL is down it means the user wants to append ".com" to the text he 634 // typed. If we can successfully generate a URL_WHAT_YOU_TYPED match doing 635 // that, then we use this. These matches are marked as generated by the 636 // HistoryURLProvider so we only generate them if this provider is present. 637 if (control_key_state_ == DOWN_WITHOUT_CHANGE && !is_keyword_selected() && 638 autocomplete_controller()->history_url_provider()) { 639 // Generate a new AutocompleteInput, copying the latest one but using "com" 640 // as the desired TLD. Then use this autocomplete input to generate a 641 // URL_WHAT_YOU_TYPED AutocompleteMatch. Note that using the most recent 642 // input instead of the currently visible text means we'll ignore any 643 // visible inline autocompletion: if a user types "foo" and is autocompleted 644 // to "foodnetwork.com", ctrl-enter will navigate to "foo.com", not 645 // "foodnetwork.com". At the time of writing, this behavior matches 646 // Internet Explorer, but not Firefox. 647 input_ = AutocompleteInput( 648 has_temporary_text_ ? 649 UserTextFromDisplayText(view_->GetText()) : input_.text(), 650 input_.cursor_position(), base::ASCIIToUTF16("com"), GURL(), 651 input_.current_page_classification(), 652 input_.prevent_inline_autocomplete(), input_.prefer_keyword(), 653 input_.allow_exact_keyword_match(), input_.want_asynchronous_matches(), 654 ChromeAutocompleteSchemeClassifier(profile_)); 655 AutocompleteMatch url_match( 656 autocomplete_controller()->history_url_provider()->SuggestExactInput( 657 input_.text(), input_.canonicalized_url(), false)); 658 659 660 if (url_match.destination_url.is_valid()) { 661 // We have a valid URL, we use this newly generated AutocompleteMatch. 662 match = url_match; 663 alternate_nav_url = GURL(); 664 } 665 } 666 667 if (!match.destination_url.is_valid()) 668 return; 669 670 if ((match.transition == content::PAGE_TRANSITION_TYPED) && 671 (match.destination_url == PermanentURL())) { 672 // When the user hit enter on the existing permanent URL, treat it like a 673 // reload for scoring purposes. We could detect this by just checking 674 // user_input_in_progress_, but it seems better to treat "edits" that end 675 // up leaving the URL unchanged (e.g. deleting the last character and then 676 // retyping it) as reloads too. We exclude non-TYPED transitions because if 677 // the transition is GENERATED, the user input something that looked 678 // different from the current URL, even if it wound up at the same place 679 // (e.g. manually retyping the same search query), and it seems wrong to 680 // treat this as a reload. 681 match.transition = content::PAGE_TRANSITION_RELOAD; 682 } else if (for_drop || ((paste_state_ != NONE) && 683 match.is_history_what_you_typed_match)) { 684 // When the user pasted in a URL and hit enter, score it like a link click 685 // rather than a normal typed URL, so it doesn't get inline autocompleted 686 // as aggressively later. 687 match.transition = content::PAGE_TRANSITION_LINK; 688 } 689 690 TemplateURLService* service = 691 TemplateURLServiceFactory::GetForProfile(profile_); 692 const TemplateURL* template_url = match.GetTemplateURL(service, false); 693 if (template_url && template_url->url_ref().HasGoogleBaseURLs( 694 UIThreadSearchTermsData(profile_))) { 695 GoogleURLTracker* tracker = 696 GoogleURLTrackerFactory::GetForProfile(profile_); 697 if (tracker) 698 tracker->SearchCommitted(); 699 } 700 701 DCHECK(popup_model()); 702 view_->OpenMatch(match, disposition, alternate_nav_url, base::string16(), 703 popup_model()->selected_line()); 704} 705 706void OmniboxEditModel::OpenMatch(AutocompleteMatch match, 707 WindowOpenDisposition disposition, 708 const GURL& alternate_nav_url, 709 const base::string16& pasted_text, 710 size_t index) { 711 const base::TimeTicks& now(base::TimeTicks::Now()); 712 base::TimeDelta elapsed_time_since_user_first_modified_omnibox( 713 now - time_user_first_modified_omnibox_); 714 autocomplete_controller()->UpdateMatchDestinationURL( 715 elapsed_time_since_user_first_modified_omnibox, &match); 716 717 base::string16 input_text(pasted_text); 718 if (input_text.empty()) 719 input_text = user_input_in_progress_ ? user_text_ : permanent_text_; 720 scoped_ptr<OmniboxNavigationObserver> observer( 721 new OmniboxNavigationObserver( 722 profile_, input_text, match, 723 autocomplete_controller()->history_url_provider()->SuggestExactInput( 724 input_text, alternate_nav_url, 725 AutocompleteInput::HasHTTPScheme(input_text)))); 726 727 base::TimeDelta elapsed_time_since_last_change_to_default_match( 728 now - autocomplete_controller()->last_time_default_match_changed()); 729 DCHECK(match.provider); 730 // These elapsed times don't really make sense for ZeroSuggest matches 731 // (because the user does not modify the omnibox for ZeroSuggest), so for 732 // those we set the elapsed times to something that will be ignored by 733 // metrics_log.cc. They also don't necessarily make sense if the omnibox 734 // dropdown is closed or the user used a paste-and-go action. (In most 735 // cases when this happens, the user never modified the omnibox.) 736 if ((match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST) || 737 !popup_model()->IsOpen() || !pasted_text.empty()) { 738 const base::TimeDelta default_time_delta = 739 base::TimeDelta::FromMilliseconds(-1); 740 elapsed_time_since_user_first_modified_omnibox = default_time_delta; 741 elapsed_time_since_last_change_to_default_match = default_time_delta; 742 } 743 // If the popup is closed or this is a paste-and-go action (meaning the 744 // contents of the dropdown are ignored regardless), we record for logging 745 // purposes a selected_index of 0 and a suggestion list as having a single 746 // entry of the match used. 747 ACMatches fake_single_entry_matches; 748 fake_single_entry_matches.push_back(match); 749 AutocompleteResult fake_single_entry_result; 750 fake_single_entry_result.AppendMatches(fake_single_entry_matches); 751 OmniboxLog log( 752 input_text, 753 just_deleted_text_, 754 input_.type(), 755 popup_model()->IsOpen(), 756 (!popup_model()->IsOpen() || !pasted_text.empty()) ? 0 : index, 757 !pasted_text.empty(), 758 -1, // don't yet know tab ID; set later if appropriate 759 ClassifyPage(), 760 elapsed_time_since_user_first_modified_omnibox, 761 match.allowed_to_be_default_match ? match.inline_autocompletion.length() : 762 base::string16::npos, 763 elapsed_time_since_last_change_to_default_match, 764 (!popup_model()->IsOpen() || !pasted_text.empty()) ? 765 fake_single_entry_result : result()); 766 DCHECK(!popup_model()->IsOpen() || !pasted_text.empty() || 767 (log.elapsed_time_since_user_first_modified_omnibox >= 768 log.elapsed_time_since_last_change_to_default_match)) 769 << "We should've got the notification that the user modified the " 770 << "omnibox text at same time or before the most recent time the " 771 << "default match changed."; 772 773 if ((disposition == CURRENT_TAB) && delegate_->CurrentPageExists()) { 774 // If we know the destination is being opened in the current tab, 775 // we can easily get the tab ID. (If it's being opened in a new 776 // tab, we don't know the tab ID yet.) 777 log.tab_id = delegate_->GetSessionID().id(); 778 } 779 autocomplete_controller()->AddProvidersInfo(&log.providers_info); 780 content::NotificationService::current()->Notify( 781 chrome::NOTIFICATION_OMNIBOX_OPENED_URL, 782 content::Source<Profile>(profile_), 783 content::Details<OmniboxLog>(&log)); 784 HISTOGRAM_ENUMERATION("Omnibox.EventCount", 1, 2); 785 DCHECK(!last_omnibox_focus_.is_null()) 786 << "An omnibox focus should have occurred before opening a match."; 787 UMA_HISTOGRAM_TIMES(kFocusToOpenTimeHistogram, now - last_omnibox_focus_); 788 789 TemplateURLService* service = 790 TemplateURLServiceFactory::GetForProfile(profile_); 791 TemplateURL* template_url = match.GetTemplateURL(service, false); 792 if (template_url) { 793 if (match.transition == content::PAGE_TRANSITION_KEYWORD) { 794 // The user is using a non-substituting keyword or is explicitly in 795 // keyword mode. 796 797 // Don't increment usage count for extension keywords. 798 if (delegate_->ProcessExtensionKeyword(template_url, match, 799 disposition)) { 800 observer->OnSuccessfulNavigation(); 801 if (disposition != NEW_BACKGROUND_TAB) 802 view_->RevertAll(); 803 return; 804 } 805 806 content::RecordAction(base::UserMetricsAction("AcceptedKeyword")); 807 TemplateURLServiceFactory::GetForProfile(profile_)->IncrementUsageCount( 808 template_url); 809 } else { 810 DCHECK_EQ(content::PAGE_TRANSITION_GENERATED, match.transition); 811 // NOTE: We purposefully don't increment the usage count of the default 812 // search engine here like we do for explicit keywords above; see comments 813 // in template_url.h. 814 } 815 816 UMA_HISTOGRAM_ENUMERATION( 817 "Omnibox.SearchEngineType", 818 TemplateURLPrepopulateData::GetEngineType( 819 *template_url, UIThreadSearchTermsData(profile_)), 820 SEARCH_ENGINE_MAX); 821 } 822 823 // Get the current text before we call RevertAll() which will clear it. 824 base::string16 current_text = view_->GetText(); 825 826 if (disposition != NEW_BACKGROUND_TAB) { 827 base::AutoReset<bool> tmp(&in_revert_, true); 828 view_->RevertAll(); // Revert the box to its unedited state. 829 } 830 831 RecordPercentageMatchHistogram( 832 permanent_text_, current_text, 833 controller_->GetToolbarModel()->WouldReplaceURL(), 834 match.transition, view_->GetWidth()); 835 836 // Track whether the destination URL sends us to a search results page 837 // using the default search provider. 838 if (TemplateURLServiceFactory::GetForProfile(profile_)-> 839 IsSearchResultsPageFromDefaultSearchProvider(match.destination_url)) { 840 content::RecordAction( 841 base::UserMetricsAction("OmniboxDestinationURLIsSearchOnDSP")); 842 } 843 844 if (match.destination_url.is_valid()) { 845 // This calls RevertAll again. 846 base::AutoReset<bool> tmp(&in_revert_, true); 847 controller_->OnAutocompleteAccept( 848 match.destination_url, disposition, 849 content::PageTransitionFromInt( 850 match.transition | content::PAGE_TRANSITION_FROM_ADDRESS_BAR)); 851 if (observer->load_state() != OmniboxNavigationObserver::LOAD_NOT_SEEN) 852 ignore_result(observer.release()); // The observer will delete itself. 853 } 854 855 if (match.starred) 856 RecordBookmarkLaunch(NULL, BOOKMARK_LAUNCH_LOCATION_OMNIBOX); 857} 858 859bool OmniboxEditModel::AcceptKeyword(EnteredKeywordModeMethod entered_method) { 860 DCHECK(is_keyword_hint_ && !keyword_.empty()); 861 862 autocomplete_controller()->Stop(false); 863 is_keyword_hint_ = false; 864 865 if (popup_model() && popup_model()->IsOpen()) 866 popup_model()->SetSelectedLineState(OmniboxPopupModel::KEYWORD); 867 else 868 StartAutocomplete(false, true); 869 870 // Ensure the current selection is saved before showing keyword mode 871 // so that moving to another line and then reverting the text will restore 872 // the current state properly. 873 bool save_original_selection = !has_temporary_text_; 874 has_temporary_text_ = true; 875 view_->OnTemporaryTextMaybeChanged( 876 DisplayTextFromUserText(CurrentMatch(NULL).fill_into_edit), 877 save_original_selection, true); 878 879 view_->UpdatePlaceholderText(); 880 881 content::RecordAction(base::UserMetricsAction("AcceptedKeywordHint")); 882 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram, entered_method, 883 ENTERED_KEYWORD_MODE_NUM_ITEMS); 884 885 return true; 886} 887 888void OmniboxEditModel::AcceptTemporaryTextAsUserText() { 889 InternalSetUserText(UserTextFromDisplayText(view_->GetText())); 890 has_temporary_text_ = false; 891 892 if (user_input_in_progress_ || !in_revert_) 893 delegate_->OnInputStateChanged(); 894} 895 896void OmniboxEditModel::ClearKeyword(const base::string16& visible_text) { 897 autocomplete_controller()->Stop(false); 898 omnibox_controller_->ClearPopupKeywordMode(); 899 900 const base::string16 window_text(keyword_ + visible_text); 901 902 // Only reset the result if the edit text has changed since the 903 // keyword was accepted, or if the popup is closed. 904 if (just_deleted_text_ || !visible_text.empty() || 905 !(popup_model() && popup_model()->IsOpen())) { 906 view_->OnBeforePossibleChange(); 907 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(), 908 false, false); 909 keyword_.clear(); 910 is_keyword_hint_ = false; 911 view_->OnAfterPossibleChange(); 912 just_deleted_text_ = true; // OnAfterPossibleChange() fails to clear this 913 // since the edit contents have actually grown 914 // longer. 915 } else { 916 is_keyword_hint_ = true; 917 view_->SetWindowTextAndCaretPos(window_text.c_str(), keyword_.length(), 918 false, true); 919 } 920 921 view_->UpdatePlaceholderText(); 922} 923 924void OmniboxEditModel::OnSetFocus(bool control_down) { 925 last_omnibox_focus_ = base::TimeTicks::Now(); 926 user_input_since_focus_ = false; 927 928 // If the omnibox lost focus while the caret was hidden and then regained 929 // focus, OnSetFocus() is called and should restore visibility. Note that 930 // focus can be regained without an accompanying call to 931 // OmniboxView::SetFocus(), e.g. by tabbing in. 932 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_EXPLICIT); 933 control_key_state_ = control_down ? DOWN_WITHOUT_CHANGE : UP; 934 935 // Try to get ZeroSuggest suggestions if a page is loaded and the user has 936 // not been typing in the omnibox. The |user_input_in_progress_| check is 937 // used to detect the case where this function is called after right-clicking 938 // in the omnibox and selecting paste in Linux (in which case we actually get 939 // the OnSetFocus() call after the process of handling the paste has kicked 940 // off). 941 // TODO(hfung): Remove this when crbug/271590 is fixed. 942 if (delegate_->CurrentPageExists() && !user_input_in_progress_) { 943 // TODO(jered): We may want to merge this into Start() and just call that 944 // here rather than having a special entry point for zero-suggest. Note 945 // that we avoid PermanentURL() here because it's not guaranteed to give us 946 // the actual underlying current URL, e.g. if we're on the NTP and the 947 // |permanent_text_| is empty. 948 autocomplete_controller()->StartZeroSuggest(AutocompleteInput( 949 permanent_text_, base::string16::npos, base::string16(), 950 delegate_->GetURL(), ClassifyPage(), false, false, true, true, 951 ChromeAutocompleteSchemeClassifier(profile_))); 952 } 953 954 if (user_input_in_progress_ || !in_revert_) 955 delegate_->OnInputStateChanged(); 956} 957 958void OmniboxEditModel::SetCaretVisibility(bool visible) { 959 // Caret visibility only matters if the omnibox has focus. 960 if (focus_state_ != OMNIBOX_FOCUS_NONE) { 961 SetFocusState(visible ? OMNIBOX_FOCUS_VISIBLE : OMNIBOX_FOCUS_INVISIBLE, 962 OMNIBOX_FOCUS_CHANGE_EXPLICIT); 963 } 964} 965 966void OmniboxEditModel::OnWillKillFocus(gfx::NativeView view_gaining_focus) { 967 if (user_input_in_progress_ || !in_revert_) 968 delegate_->OnInputStateChanged(); 969} 970 971void OmniboxEditModel::OnKillFocus() { 972 SetFocusState(OMNIBOX_FOCUS_NONE, OMNIBOX_FOCUS_CHANGE_EXPLICIT); 973 focus_source_ = INVALID; 974 control_key_state_ = UP; 975 paste_state_ = NONE; 976} 977 978bool OmniboxEditModel::OnEscapeKeyPressed() { 979 const AutocompleteMatch& match = CurrentMatch(NULL); 980 if (has_temporary_text_) { 981 if (match.destination_url != original_url_) { 982 RevertTemporaryText(true); 983 return true; 984 } 985 } 986 987 // We do not clear the pending entry from the omnibox when a load is first 988 // stopped. If the user presses Escape while stopped, we clear it. 989 if (delegate_->CurrentPageExists() && !delegate_->IsLoading()) { 990 delegate_->GetNavigationController().DiscardNonCommittedEntries(); 991 view_->Update(); 992 } 993 994 // When using the origin chip, hitting escape to revert all should either 995 // display the URL (when search term replacement would not be performed for 996 // this page) or the search terms (when it would). To accomplish this, 997 // we'll need to disable URL replacement iff it's currently enabled and 998 // search term replacement wouldn't normally happen. 999 bool should_disable_url_replacement = 1000 controller_->GetToolbarModel()->url_replacement_enabled() && 1001 !controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(true); 1002 1003 // If the user wasn't editing, but merely had focus in the edit, allow <esc> 1004 // to be processed as an accelerator, so it can still be used to stop a load. 1005 // When the permanent text isn't all selected we still fall through to the 1006 // SelectAll() call below so users can arrow around in the text and then hit 1007 // <esc> to quickly replace all the text; this matches IE. 1008 const bool has_zero_suggest_match = match.provider && 1009 (match.provider->type() == AutocompleteProvider::TYPE_ZERO_SUGGEST); 1010 if (!has_zero_suggest_match && !should_disable_url_replacement && 1011 !user_input_in_progress_ && view_->IsSelectAll()) 1012 return false; 1013 1014 if (!user_text_.empty()) { 1015 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram, 1016 OMNIBOX_USER_TEXT_CLEARED_WITH_ESCAPE, 1017 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS); 1018 } 1019 1020 if (should_disable_url_replacement) { 1021 controller_->GetToolbarModel()->set_url_replacement_enabled(false); 1022 UpdatePermanentText(); 1023 } 1024 view_->RevertWithoutResettingSearchTermReplacement(); 1025 view_->SelectAll(true); 1026 return true; 1027} 1028 1029void OmniboxEditModel::OnControlKeyChanged(bool pressed) { 1030 if (pressed == (control_key_state_ == UP)) 1031 control_key_state_ = pressed ? DOWN_WITHOUT_CHANGE : UP; 1032} 1033 1034void OmniboxEditModel::OnPaste() { 1035 UMA_HISTOGRAM_COUNTS("Omnibox.Paste", 1); 1036 paste_state_ = PASTING; 1037} 1038 1039void OmniboxEditModel::OnUpOrDownKeyPressed(int count) { 1040 // NOTE: This purposefully doesn't trigger any code that resets paste_state_. 1041 if (popup_model() && popup_model()->IsOpen()) { 1042 // The popup is open, so the user should be able to interact with it 1043 // normally. 1044 popup_model()->Move(count); 1045 return; 1046 } 1047 1048 if (!query_in_progress()) { 1049 // The popup is neither open nor working on a query already. So, start an 1050 // autocomplete query for the current text. This also sets 1051 // user_input_in_progress_ to true, which we want: if the user has started 1052 // to interact with the popup, changing the permanent_text_ shouldn't change 1053 // the displayed text. 1054 // Note: This does not force the popup to open immediately. 1055 // TODO(pkasting): We should, in fact, force this particular query to open 1056 // the popup immediately. 1057 if (!user_input_in_progress_) 1058 InternalSetUserText(permanent_text_); 1059 view_->UpdatePopup(); 1060 return; 1061 } 1062 1063 // TODO(pkasting): The popup is working on a query but is not open. We should 1064 // force it to open immediately. 1065} 1066 1067void OmniboxEditModel::OnPopupDataChanged( 1068 const base::string16& text, 1069 GURL* destination_for_temporary_text_change, 1070 const base::string16& keyword, 1071 bool is_keyword_hint) { 1072 // The popup changed its data, the match in the controller is no longer valid. 1073 omnibox_controller_->InvalidateCurrentMatch(); 1074 1075 // Update keyword/hint-related local state. 1076 bool keyword_state_changed = (keyword_ != keyword) || 1077 ((is_keyword_hint_ != is_keyword_hint) && !keyword.empty()); 1078 if (keyword_state_changed) { 1079 keyword_ = keyword; 1080 is_keyword_hint_ = is_keyword_hint; 1081 1082 // |is_keyword_hint_| should always be false if |keyword_| is empty. 1083 DCHECK(!keyword_.empty() || !is_keyword_hint_); 1084 } 1085 1086 // Handle changes to temporary text. 1087 if (destination_for_temporary_text_change != NULL) { 1088 const bool save_original_selection = !has_temporary_text_; 1089 if (save_original_selection) { 1090 // Save the original selection and URL so it can be reverted later. 1091 has_temporary_text_ = true; 1092 original_url_ = *destination_for_temporary_text_change; 1093 inline_autocomplete_text_.clear(); 1094 view_->OnInlineAutocompleteTextCleared(); 1095 } 1096 if (control_key_state_ == DOWN_WITHOUT_CHANGE) { 1097 // Arrowing around the popup cancels control-enter. 1098 control_key_state_ = DOWN_WITH_CHANGE; 1099 // Now things are a bit screwy: the desired_tld has changed, but if we 1100 // update the popup, the new order of entries won't match the old, so the 1101 // user's selection gets screwy; and if we don't update the popup, and the 1102 // user reverts, then the selected item will be as if control is still 1103 // pressed, even though maybe it isn't any more. There is no obvious 1104 // right answer here :( 1105 } 1106 view_->OnTemporaryTextMaybeChanged(DisplayTextFromUserText(text), 1107 save_original_selection, true); 1108 return; 1109 } 1110 1111 bool call_controller_onchanged = true; 1112 inline_autocomplete_text_ = text; 1113 if (inline_autocomplete_text_.empty()) 1114 view_->OnInlineAutocompleteTextCleared(); 1115 1116 const base::string16& user_text = 1117 user_input_in_progress_ ? user_text_ : permanent_text_; 1118 if (keyword_state_changed && is_keyword_selected()) { 1119 // If we reach here, the user most likely entered keyword mode by inserting 1120 // a space between a keyword name and a search string (as pressing space or 1121 // tab after the keyword name alone would have been be handled in 1122 // MaybeAcceptKeywordBySpace() by calling AcceptKeyword(), which won't reach 1123 // here). In this case, we don't want to call 1124 // OnInlineAutocompleteTextMaybeChanged() as normal, because that will 1125 // correctly change the text (to the search string alone) but move the caret 1126 // to the end of the string; instead we want the caret at the start of the 1127 // search string since that's where it was in the original input. So we set 1128 // the text and caret position directly. 1129 // 1130 // It may also be possible to reach here if we're reverting from having 1131 // temporary text back to a default match that's a keyword search, but in 1132 // that case the RevertTemporaryText() call below will reset the caret or 1133 // selection correctly so the caret positioning we do here won't matter. 1134 view_->SetWindowTextAndCaretPos(DisplayTextFromUserText(user_text), 0, 1135 false, false); 1136 } else if (view_->OnInlineAutocompleteTextMaybeChanged( 1137 DisplayTextFromUserText(user_text + inline_autocomplete_text_), 1138 DisplayTextFromUserText(user_text).length())) { 1139 call_controller_onchanged = false; 1140 } 1141 1142 // If |has_temporary_text_| is true, then we previously had a manual selection 1143 // but now don't (or |destination_for_temporary_text_change| would have been 1144 // non-NULL). This can happen when deleting the selected item in the popup. 1145 // In this case, we've already reverted the popup to the default match, so we 1146 // need to revert ourselves as well. 1147 if (has_temporary_text_) { 1148 RevertTemporaryText(false); 1149 call_controller_onchanged = false; 1150 } 1151 1152 // We need to invoke OnChanged in case the destination url changed (as could 1153 // happen when control is toggled). 1154 if (call_controller_onchanged) 1155 OnChanged(); 1156} 1157 1158bool OmniboxEditModel::OnAfterPossibleChange(const base::string16& old_text, 1159 const base::string16& new_text, 1160 size_t selection_start, 1161 size_t selection_end, 1162 bool selection_differs, 1163 bool text_differs, 1164 bool just_deleted_text, 1165 bool allow_keyword_ui_change) { 1166 // Update the paste state as appropriate: if we're just finishing a paste 1167 // that replaced all the text, preserve that information; otherwise, if we've 1168 // made some other edit, clear paste tracking. 1169 if (paste_state_ == PASTING) 1170 paste_state_ = PASTED; 1171 else if (text_differs) 1172 paste_state_ = NONE; 1173 1174 if (text_differs || selection_differs) { 1175 // Record current focus state for this input if we haven't already. 1176 if (focus_source_ == INVALID) { 1177 // We should generally expect the omnibox to have focus at this point, but 1178 // it doesn't always on Linux. This is because, unlike other platforms, 1179 // right clicking in the omnibox on Linux doesn't focus it. So pasting via 1180 // right-click can change the contents without focusing the omnibox. 1181 // TODO(samarth): fix Linux focus behavior and add a DCHECK here to 1182 // check that the omnibox does have focus. 1183 focus_source_ = (focus_state_ == OMNIBOX_FOCUS_INVISIBLE) ? 1184 FAKEBOX : OMNIBOX; 1185 } 1186 1187 // Restore caret visibility whenever the user changes text or selection in 1188 // the omnibox. 1189 SetFocusState(OMNIBOX_FOCUS_VISIBLE, OMNIBOX_FOCUS_CHANGE_TYPING); 1190 } 1191 1192 // Modifying the selection counts as accepting the autocompleted text. 1193 const bool user_text_changed = 1194 text_differs || (selection_differs && !inline_autocomplete_text_.empty()); 1195 1196 // If something has changed while the control key is down, prevent 1197 // "ctrl-enter" until the control key is released. 1198 if ((text_differs || selection_differs) && 1199 (control_key_state_ == DOWN_WITHOUT_CHANGE)) 1200 control_key_state_ = DOWN_WITH_CHANGE; 1201 1202 if (!user_text_changed) 1203 return false; 1204 1205 // If the user text has not changed, we do not want to change the model's 1206 // state associated with the text. Otherwise, we can get surprising behavior 1207 // where the autocompleted text unexpectedly reappears, e.g. crbug.com/55983 1208 InternalSetUserText(UserTextFromDisplayText(new_text)); 1209 has_temporary_text_ = false; 1210 1211 // Track when the user has deleted text so we won't allow inline 1212 // autocomplete. 1213 just_deleted_text_ = just_deleted_text; 1214 1215 if (user_input_in_progress_ && user_text_.empty()) { 1216 // Log cases where the user started editing and then subsequently cleared 1217 // all the text. Note that this explicitly doesn't catch cases like 1218 // "hit ctrl-l to select whole edit contents, then hit backspace", because 1219 // in such cases, |user_input_in_progress| won't be true here. 1220 UMA_HISTOGRAM_ENUMERATION(kOmniboxUserTextClearedHistogram, 1221 OMNIBOX_USER_TEXT_CLEARED_BY_EDITING, 1222 OMNIBOX_USER_TEXT_CLEARED_NUM_OF_ITEMS); 1223 } 1224 1225 const bool no_selection = selection_start == selection_end; 1226 1227 // Update the popup for the change, in the process changing to keyword mode 1228 // if the user hit space in mid-string after a keyword. 1229 // |allow_exact_keyword_match_| will be used by StartAutocomplete() method, 1230 // which will be called by |view_->UpdatePopup()|; so after that returns we 1231 // can safely reset this flag. 1232 allow_exact_keyword_match_ = text_differs && allow_keyword_ui_change && 1233 !just_deleted_text && no_selection && 1234 CreatedKeywordSearchByInsertingSpaceInMiddle(old_text, user_text_, 1235 selection_start); 1236 view_->UpdatePopup(); 1237 if (allow_exact_keyword_match_) { 1238 view_->UpdatePlaceholderText(); 1239 UMA_HISTOGRAM_ENUMERATION(kEnteredKeywordModeHistogram, 1240 ENTERED_KEYWORD_MODE_VIA_SPACE_IN_MIDDLE, 1241 ENTERED_KEYWORD_MODE_NUM_ITEMS); 1242 allow_exact_keyword_match_ = false; 1243 } 1244 1245 // Change to keyword mode if the user is now pressing space after a keyword 1246 // name. Note that if this is the case, then even if there was no keyword 1247 // hint when we entered this function (e.g. if the user has used space to 1248 // replace some selected text that was adjoined to this keyword), there will 1249 // be one now because of the call to UpdatePopup() above; so it's safe for 1250 // MaybeAcceptKeywordBySpace() to look at |keyword_| and |is_keyword_hint_| to 1251 // determine what keyword, if any, is applicable. 1252 // 1253 // If MaybeAcceptKeywordBySpace() accepts the keyword and returns true, that 1254 // will have updated our state already, so in that case we don't also return 1255 // true from this function. 1256 return !(text_differs && allow_keyword_ui_change && !just_deleted_text && 1257 no_selection && (selection_start == user_text_.length()) && 1258 MaybeAcceptKeywordBySpace(user_text_)); 1259} 1260 1261// TODO(beaudoin): Merge OnPopupDataChanged with this method once the popup 1262// handling has completely migrated to omnibox_controller. 1263void OmniboxEditModel::OnCurrentMatchChanged() { 1264 has_temporary_text_ = false; 1265 1266 const AutocompleteMatch& match = omnibox_controller_->current_match(); 1267 1268 // We store |keyword| and |is_keyword_hint| in temporary variables since 1269 // OnPopupDataChanged use their previous state to detect changes. 1270 base::string16 keyword; 1271 bool is_keyword_hint; 1272 TemplateURLService* service = 1273 TemplateURLServiceFactory::GetForProfile(profile_); 1274 match.GetKeywordUIState(service, &keyword, &is_keyword_hint); 1275 if (popup_model()) 1276 popup_model()->OnResultChanged(); 1277 // OnPopupDataChanged() resets OmniboxController's |current_match_| early 1278 // on. Therefore, copy match.inline_autocompletion to a temp to preserve 1279 // its value across the entire call. 1280 const base::string16 inline_autocompletion(match.inline_autocompletion); 1281 OnPopupDataChanged(inline_autocompletion, NULL, keyword, is_keyword_hint); 1282} 1283 1284void OmniboxEditModel::SetSuggestionToPrefetch( 1285 const InstantSuggestion& suggestion) { 1286 delegate_->SetSuggestionToPrefetch(suggestion); 1287} 1288 1289// static 1290const char OmniboxEditModel::kCutOrCopyAllTextHistogram[] = 1291 "Omnibox.CutOrCopyAllText"; 1292 1293bool OmniboxEditModel::query_in_progress() const { 1294 return !autocomplete_controller()->done(); 1295} 1296 1297void OmniboxEditModel::InternalSetUserText(const base::string16& text) { 1298 user_text_ = text; 1299 just_deleted_text_ = false; 1300 inline_autocomplete_text_.clear(); 1301 view_->OnInlineAutocompleteTextCleared(); 1302} 1303 1304void OmniboxEditModel::ClearPopupKeywordMode() const { 1305 omnibox_controller_->ClearPopupKeywordMode(); 1306} 1307 1308base::string16 OmniboxEditModel::DisplayTextFromUserText( 1309 const base::string16& text) const { 1310 return is_keyword_selected() ? 1311 KeywordProvider::SplitReplacementStringFromInput(text, false) : text; 1312} 1313 1314base::string16 OmniboxEditModel::UserTextFromDisplayText( 1315 const base::string16& text) const { 1316 return is_keyword_selected() ? (keyword_ + base::char16(' ') + text) : text; 1317} 1318 1319void OmniboxEditModel::GetInfoForCurrentText(AutocompleteMatch* match, 1320 GURL* alternate_nav_url) const { 1321 DCHECK(match != NULL); 1322 1323 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement( 1324 false)) { 1325 // Any time the user hits enter on the unchanged omnibox, we should reload. 1326 // When we're not extracting search terms, AcceptInput() will take care of 1327 // this (see code referring to PAGE_TRANSITION_RELOAD there), but when we're 1328 // extracting search terms, the conditionals there won't fire, so we 1329 // explicitly set up a match that will reload here. 1330 1331 // It's important that we fetch the current visible URL to reload instead of 1332 // just getting a "search what you typed" URL from 1333 // SearchProvider::CreateSearchSuggestion(), since the user may be in a 1334 // non-default search mode such as image search. 1335 match->type = AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED; 1336 match->provider = autocomplete_controller()->search_provider(); 1337 match->destination_url = 1338 delegate_->GetNavigationController().GetVisibleEntry()->GetURL(); 1339 match->transition = content::PAGE_TRANSITION_RELOAD; 1340 } else if (query_in_progress() || 1341 (popup_model() && popup_model()->IsOpen())) { 1342 if (query_in_progress()) { 1343 // It's technically possible for |result| to be empty if no provider 1344 // returns a synchronous result but the query has not completed 1345 // synchronously; pratically, however, that should never actually happen. 1346 if (result().empty()) 1347 return; 1348 // The user cannot have manually selected a match, or the query would have 1349 // stopped. So the default match must be the desired selection. 1350 *match = *result().default_match(); 1351 } else { 1352 // If there are no results, the popup should be closed, so we shouldn't 1353 // have gotten here. 1354 CHECK(!result().empty()); 1355 CHECK(popup_model()->selected_line() < result().size()); 1356 *match = result().match_at(popup_model()->selected_line()); 1357 } 1358 if (alternate_nav_url && 1359 (!popup_model() || popup_model()->manually_selected_match().empty())) 1360 *alternate_nav_url = result().alternate_nav_url(); 1361 } else { 1362 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify( 1363 UserTextFromDisplayText(view_->GetText()), is_keyword_selected(), true, 1364 ClassifyPage(), match, alternate_nav_url); 1365 } 1366} 1367 1368void OmniboxEditModel::RevertTemporaryText(bool revert_popup) { 1369 // The user typed something, then selected a different item. Restore the 1370 // text they typed and change back to the default item. 1371 // NOTE: This purposefully does not reset paste_state_. 1372 just_deleted_text_ = false; 1373 has_temporary_text_ = false; 1374 1375 if (revert_popup && popup_model()) 1376 popup_model()->ResetToDefaultMatch(); 1377 view_->OnRevertTemporaryText(); 1378} 1379 1380bool OmniboxEditModel::MaybeAcceptKeywordBySpace( 1381 const base::string16& new_text) { 1382 size_t keyword_length = new_text.length() - 1; 1383 return (paste_state_ == NONE) && is_keyword_hint_ && !keyword_.empty() && 1384 inline_autocomplete_text_.empty() && 1385 (keyword_.length() == keyword_length) && 1386 IsSpaceCharForAcceptingKeyword(new_text[keyword_length]) && 1387 !new_text.compare(0, keyword_length, keyword_, 0, keyword_length) && 1388 AcceptKeyword(ENTERED_KEYWORD_MODE_VIA_SPACE_AT_END); 1389} 1390 1391bool OmniboxEditModel::CreatedKeywordSearchByInsertingSpaceInMiddle( 1392 const base::string16& old_text, 1393 const base::string16& new_text, 1394 size_t caret_position) const { 1395 DCHECK_GE(new_text.length(), caret_position); 1396 1397 // Check simple conditions first. 1398 if ((paste_state_ != NONE) || (caret_position < 2) || 1399 (old_text.length() < caret_position) || 1400 (new_text.length() == caret_position)) 1401 return false; 1402 size_t space_position = caret_position - 1; 1403 if (!IsSpaceCharForAcceptingKeyword(new_text[space_position]) || 1404 IsWhitespace(new_text[space_position - 1]) || 1405 new_text.compare(0, space_position, old_text, 0, space_position) || 1406 !new_text.compare(space_position, new_text.length() - space_position, 1407 old_text, space_position, 1408 old_text.length() - space_position)) { 1409 return false; 1410 } 1411 1412 // Then check if the text before the inserted space matches a keyword. 1413 base::string16 keyword; 1414 base::TrimWhitespace(new_text.substr(0, space_position), base::TRIM_LEADING, 1415 &keyword); 1416 return !keyword.empty() && !autocomplete_controller()->keyword_provider()-> 1417 GetKeywordForText(keyword).empty(); 1418} 1419 1420// static 1421bool OmniboxEditModel::IsSpaceCharForAcceptingKeyword(wchar_t c) { 1422 switch (c) { 1423 case 0x0020: // Space 1424 case 0x3000: // Ideographic Space 1425 return true; 1426 default: 1427 return false; 1428 } 1429} 1430 1431OmniboxEventProto::PageClassification OmniboxEditModel::ClassifyPage() const { 1432 if (!delegate_->CurrentPageExists()) 1433 return OmniboxEventProto::OTHER; 1434 if (delegate_->IsInstantNTP()) { 1435 // Note that we treat OMNIBOX as the source if focus_source_ is INVALID, 1436 // i.e., if input isn't actually in progress. 1437 return (focus_source_ == FAKEBOX) ? 1438 OmniboxEventProto::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS : 1439 OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS; 1440 } 1441 const GURL& gurl = delegate_->GetURL(); 1442 if (!gurl.is_valid()) 1443 return OmniboxEventProto::INVALID_SPEC; 1444 const std::string& url = gurl.spec(); 1445 if (url == chrome::kChromeUINewTabURL) 1446 return OmniboxEventProto::NTP; 1447 if (url == url::kAboutBlankURL) 1448 return OmniboxEventProto::BLANK; 1449 if (url == profile()->GetPrefs()->GetString(prefs::kHomePage)) 1450 return OmniboxEventProto::HOME_PAGE; 1451 if (controller_->GetToolbarModel()->WouldPerformSearchTermReplacement(true)) 1452 return OmniboxEventProto::SEARCH_RESULT_PAGE_DOING_SEARCH_TERM_REPLACEMENT; 1453 if (delegate_->IsSearchResultsPage()) 1454 return OmniboxEventProto::SEARCH_RESULT_PAGE_NO_SEARCH_TERM_REPLACEMENT; 1455 return OmniboxEventProto::OTHER; 1456} 1457 1458void OmniboxEditModel::ClassifyStringForPasteAndGo( 1459 const base::string16& text, 1460 AutocompleteMatch* match, 1461 GURL* alternate_nav_url) const { 1462 DCHECK(match); 1463 AutocompleteClassifierFactory::GetForProfile(profile_)->Classify( 1464 text, false, false, ClassifyPage(), match, alternate_nav_url); 1465} 1466 1467void OmniboxEditModel::SetFocusState(OmniboxFocusState state, 1468 OmniboxFocusChangeReason reason) { 1469 if (state == focus_state_) 1470 return; 1471 1472 // Update state and notify view if the omnibox has focus and the caret 1473 // visibility changed. 1474 const bool was_caret_visible = is_caret_visible(); 1475 focus_state_ = state; 1476 if (focus_state_ != OMNIBOX_FOCUS_NONE && 1477 is_caret_visible() != was_caret_visible) 1478 view_->ApplyCaretVisibility(); 1479 1480 delegate_->OnFocusChanged(focus_state_, reason); 1481} 1482