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