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