history_quick_provider.cc revision 2a99a7e74a7f215066514fe81d2bfa6639d9eddd
1// Copyright (c) 2012 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#include "chrome/browser/autocomplete/history_quick_provider.h" 6 7#include <vector> 8 9#include "base/basictypes.h" 10#include "base/command_line.h" 11#include "base/i18n/break_iterator.h" 12#include "base/logging.h" 13#include "base/metrics/field_trial.h" 14#include "base/metrics/histogram.h" 15#include "base/prefs/pref_service.h" 16#include "base/string_util.h" 17#include "base/strings/string_number_conversions.h" 18#include "base/time.h" 19#include "base/utf_string_conversions.h" 20#include "chrome/browser/autocomplete/autocomplete_result.h" 21#include "chrome/browser/autocomplete/history_url_provider.h" 22#include "chrome/browser/history/history_database.h" 23#include "chrome/browser/history/history_service.h" 24#include "chrome/browser/history/history_service_factory.h" 25#include "chrome/browser/history/in_memory_url_index.h" 26#include "chrome/browser/history/in_memory_url_index_types.h" 27#include "chrome/browser/history/scored_history_match.h" 28#include "chrome/browser/net/url_fixer_upper.h" 29#include "chrome/browser/omnibox/omnibox_field_trial.h" 30#include "chrome/browser/profiles/profile.h" 31#include "chrome/browser/search/search.h" 32#include "chrome/browser/search_engines/template_url.h" 33#include "chrome/browser/search_engines/template_url_service.h" 34#include "chrome/browser/search_engines/template_url_service_factory.h" 35#include "chrome/common/chrome_switches.h" 36#include "chrome/common/pref_names.h" 37#include "chrome/common/url_constants.h" 38#include "content/public/browser/browser_thread.h" 39#include "content/public/browser/notification_source.h" 40#include "content/public/browser/notification_types.h" 41#include "googleurl/src/url_parse.h" 42#include "googleurl/src/url_util.h" 43#include "net/base/escape.h" 44#include "net/base/net_util.h" 45#include "net/base/registry_controlled_domains/registry_controlled_domain.h" 46 47using history::InMemoryURLIndex; 48using history::ScoredHistoryMatch; 49using history::ScoredHistoryMatches; 50 51bool HistoryQuickProvider::disabled_ = false; 52 53HistoryQuickProvider::HistoryQuickProvider( 54 AutocompleteProviderListener* listener, 55 Profile* profile) 56 : HistoryProvider(listener, profile, 57 AutocompleteProvider::TYPE_HISTORY_QUICK), 58 languages_(profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)), 59 reorder_for_inlining_(false) { 60 enum InliningOption { 61 INLINING_PROHIBITED = 0, 62 INLINING_ALLOWED = 1, 63 INLINING_AUTO_BUT_NOT_IN_FIELD_TRIAL = 2, 64 INLINING_FIELD_TRIAL_DEFAULT_GROUP = 3, 65 INLINING_FIELD_TRIAL_EXPERIMENT_GROUP = 4, 66 NUM_OPTIONS = 5 67 }; 68 // should always be overwritten 69 InliningOption inlining_option = NUM_OPTIONS; 70 71 const std::string switch_value = CommandLine::ForCurrentProcess()-> 72 GetSwitchValueASCII(switches::kOmniboxInlineHistoryQuickProvider); 73 if (switch_value == switches::kOmniboxInlineHistoryQuickProviderAllowed) { 74 inlining_option = INLINING_ALLOWED; 75 always_prevent_inline_autocomplete_ = false; 76 } else if (switch_value == 77 switches::kOmniboxInlineHistoryQuickProviderProhibited) { 78 inlining_option = INLINING_PROHIBITED; 79 always_prevent_inline_autocomplete_ = true; 80 } else { 81 // We'll assume any other flag means automatic. 82 // Automatic means eligible for the field trial. 83 84 // For the field trial stuff to work correctly, we must be running 85 // on the same thread as the thread that created the field trial, 86 // which happens via a call to OmniboxFieldTrial::Active in 87 // chrome_browser_main.cc on the main thread. Let's check this to 88 // be sure. We check "if we've heard of the UI thread then we'd better 89 // be on it." The first part is necessary so unit tests pass. (Many 90 // unit tests don't set up the threading naming system; hence 91 // CurrentlyOn(UI thread) will fail.) 92 DCHECK(!content::BrowserThread::IsWellKnownThread( 93 content::BrowserThread::UI) || 94 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); 95 if (OmniboxFieldTrial::InDisallowInlineHQPFieldTrial()) { 96 if (OmniboxFieldTrial::InDisallowInlineHQPFieldTrialExperimentGroup()) { 97 always_prevent_inline_autocomplete_ = true; 98 inlining_option = INLINING_FIELD_TRIAL_EXPERIMENT_GROUP; 99 } else { 100 always_prevent_inline_autocomplete_ = false; 101 inlining_option = INLINING_FIELD_TRIAL_DEFAULT_GROUP; 102 } 103 } else { 104 always_prevent_inline_autocomplete_ = false; 105 inlining_option = INLINING_AUTO_BUT_NOT_IN_FIELD_TRIAL; 106 } 107 } 108 109 // Add a beacon to the logs that'll allow us to identify later what 110 // inlining state a user is in. Do this by incrementing a bucket in 111 // a histogram, where the bucket represents the user's inlining state. 112 UMA_HISTOGRAM_ENUMERATION( 113 "Omnibox.InlineHistoryQuickProviderFieldTrialBeacon", 114 inlining_option, NUM_OPTIONS); 115 116 reorder_for_inlining_ = CommandLine::ForCurrentProcess()-> 117 GetSwitchValueASCII(switches:: 118 kOmniboxHistoryQuickProviderReorderForInlining) == 119 switches::kOmniboxHistoryQuickProviderReorderForInliningEnabled; 120} 121 122void HistoryQuickProvider::Start(const AutocompleteInput& input, 123 bool minimal_changes) { 124 matches_.clear(); 125 if (disabled_) 126 return; 127 128 // Don't bother with INVALID and FORCED_QUERY. Also pass when looking for 129 // BEST_MATCH and there is no inline autocompletion because none of the HQP 130 // matches can score highly enough to qualify. 131 if ((input.type() == AutocompleteInput::INVALID) || 132 (input.type() == AutocompleteInput::FORCED_QUERY) || 133 (input.matches_requested() == AutocompleteInput::BEST_MATCH && 134 input.prevent_inline_autocomplete())) 135 return; 136 137 autocomplete_input_ = input; 138 139 // TODO(pkasting): We should just block here until this loads. Any time 140 // someone unloads the history backend, we'll get inconsistent inline 141 // autocomplete behavior here. 142 if (GetIndex()) { 143 base::TimeTicks start_time = base::TimeTicks::Now(); 144 DoAutocomplete(); 145 if (input.text().length() < 6) { 146 base::TimeTicks end_time = base::TimeTicks::Now(); 147 std::string name = "HistoryQuickProvider.QueryIndexTime." + 148 base::IntToString(input.text().length()); 149 base::HistogramBase* counter = base::Histogram::FactoryGet( 150 name, 1, 1000, 50, base::Histogram::kUmaTargetedHistogramFlag); 151 counter->Add(static_cast<int>((end_time - start_time).InMilliseconds())); 152 } 153 UpdateStarredStateOfMatches(); 154 } 155} 156 157void HistoryQuickProvider::DeleteMatch(const AutocompleteMatch& match) { 158 DCHECK(match.deletable); 159 DCHECK(match.destination_url.is_valid()); 160 // Delete the match from the InMemoryURLIndex. 161 GetIndex()->DeleteURL(match.destination_url); 162 DeleteMatchFromMatches(match); 163} 164 165HistoryQuickProvider::~HistoryQuickProvider() {} 166 167void HistoryQuickProvider::DoAutocomplete() { 168 // Get the matching URLs from the DB. 169 ScoredHistoryMatches matches = GetIndex()->HistoryItemsForTerms( 170 autocomplete_input_.text(), 171 autocomplete_input_.cursor_position()); 172 if (matches.empty()) 173 return; 174 175 // If we're allowed to reorder results in order to get an inlineable 176 // result to appear first (and hence have a HistoryQuickProvider 177 // suggestion possibly appear first), find the first inlineable 178 // result and then swap it to the front. Obviously, don't do this 179 // if we're told to prevent inline autocompletion. (If we're told 180 // we're going to prevent inline autocompletion, we're going to 181 // later demote the score of all results so none will be inlined. 182 // Hence there's no need to reorder the results so an inlineable one 183 // appears first.) 184 if (reorder_for_inlining_ && 185 !PreventInlineAutocomplete(autocomplete_input_)) { 186 for (ScoredHistoryMatches::iterator i(matches.begin()); 187 (i != matches.end()) && 188 (i->raw_score >= AutocompleteResult::kLowestDefaultScore); 189 ++i) { 190 if (i->can_inline) { // this test is only true once because of the break 191 if (i != matches.begin()) 192 std::rotate(matches.begin(), i, i + 1); 193 break; 194 } 195 } 196 } 197 198 // Figure out if HistoryURL provider has a URL-what-you-typed match 199 // that ought to go first and what its score will be. 200 bool will_have_url_what_you_typed_match_first = false; 201 int url_what_you_typed_match_score = -1; // undefined 202 // These are necessary (but not sufficient) conditions for the omnibox 203 // input to be a URL-what-you-typed match. The username test checks that 204 // either the username does not exist (a regular URL such as http://site/) 205 // or, if the username exists (http://user@site/), there must be either 206 // a password or a port. Together these exclude pure username@site 207 // inputs because these are likely to be an e-mail address. HistoryURL 208 // provider won't promote the URL-what-you-typed match to first 209 // for these inputs. 210 const bool can_have_url_what_you_typed_match_first = 211 autocomplete_input_.canonicalized_url().is_valid() && 212 (autocomplete_input_.type() != AutocompleteInput::QUERY) && 213 (autocomplete_input_.type() != AutocompleteInput::FORCED_QUERY) && 214 (!autocomplete_input_.parts().username.is_nonempty() || 215 autocomplete_input_.parts().password.is_nonempty() || 216 autocomplete_input_.parts().path.is_nonempty()); 217 if (can_have_url_what_you_typed_match_first) { 218 HistoryService* const history_service = 219 HistoryServiceFactory::GetForProfile(profile_, 220 Profile::EXPLICIT_ACCESS); 221 // We expect HistoryService to be available. In case it's not, 222 // (e.g., due to Profile corruption) we let HistoryQuick provider 223 // completions (which may be available because it's a different 224 // data structure) compete with the URL-what-you-typed match as 225 // normal. 226 if (history_service) { 227 history::URLDatabase* url_db = history_service->InMemoryDatabase(); 228 // url_db can be NULL if it hasn't finished initializing (or 229 // failed to to initialize). In this case, we let HistoryQuick 230 // provider completions compete with the URL-what-you-typed 231 // match as normal. 232 if (url_db) { 233 const std::string host(UTF16ToUTF8(autocomplete_input_.text().substr( 234 autocomplete_input_.parts().host.begin, 235 autocomplete_input_.parts().host.len))); 236 // We want to put the URL-what-you-typed match first if either 237 // * the user visited the URL before (intranet or internet). 238 // * it's a URL on a host that user visited before and this 239 // is the root path of the host. (If the user types some 240 // of a path--more than a simple "/"--we let autocomplete compete 241 // normally with the URL-what-you-typed match.) 242 // TODO(mpearson): Remove this hacky code and simply score URL-what- 243 // you-typed in some sane way relative to possible completions: 244 // URL-what-you-typed should get some sort of a boost relative 245 // to completions, but completions should naturally win if 246 // they're a lot more popular. In this process, if the input 247 // is a bare intranet hostname that has been visited before, we 248 // may want to enforce that the only completions that can outscore 249 // the URL-what-you-typed match are on the same host (i.e., aren't 250 // from a longer internet hostname for which the omnibox input is 251 // a prefix). 252 if (url_db->GetRowForURL( 253 autocomplete_input_.canonicalized_url(), NULL) != 0) { 254 // We visited this URL before. 255 will_have_url_what_you_typed_match_first = true; 256 // HistoryURLProvider gives visited what-you-typed URLs a high score. 257 url_what_you_typed_match_score = 258 HistoryURLProvider::kScoreForBestInlineableResult; 259 } else if (url_db->IsTypedHost(host) && 260 (!autocomplete_input_.parts().path.is_nonempty() || 261 ((autocomplete_input_.parts().path.len == 1) && 262 (autocomplete_input_.text()[ 263 autocomplete_input_.parts().path.begin] == '/'))) && 264 !autocomplete_input_.parts().query.is_nonempty() && 265 !autocomplete_input_.parts().ref.is_nonempty()) { 266 // Not visited, but we've seen the host before. 267 will_have_url_what_you_typed_match_first = true; 268 if (net::RegistryControlledDomainService::GetRegistryLength( 269 host, false) == 0) { 270 // Known intranet hosts get one score. 271 url_what_you_typed_match_score = 272 HistoryURLProvider::kScoreForUnvisitedIntranetResult; 273 } else { 274 // Known internet hosts get another. 275 url_what_you_typed_match_score = 276 HistoryURLProvider::kScoreForWhatYouTypedResult; 277 } 278 } 279 } 280 } 281 } 282 283 // Loop over every result and add it to matches_. In the process, 284 // guarantee that scores are decreasing. |max_match_score| keeps 285 // track of the highest score we can assign to any later results we 286 // see. Also, if we're not allowing inline autocompletions in 287 // general or the current best suggestion isn't inlineable, 288 // artificially reduce the starting |max_match_score| (which 289 // therefore applies to all results) to something low enough that 290 // guarantees no result will be offered as an autocomplete 291 // suggestion. Also do a similar reduction if we think there will be 292 // a URL-what-you-typed match. (We want URL-what-you-typed matches for 293 // visited URLs to beat out any longer URLs, no matter how frequently 294 // they're visited.) The strength of this last reduction depends on the 295 // likely score for the URL-what-you-typed result. 296 297 // |template_url_service| or |template_url| can be NULL in unit tests. 298 TemplateURLService* template_url_service = 299 TemplateURLServiceFactory::GetForProfile(profile_); 300 TemplateURL* template_url = template_url_service ? 301 template_url_service->GetDefaultSearchProvider() : NULL; 302 int max_match_score = (PreventInlineAutocomplete(autocomplete_input_) || 303 !matches.begin()->can_inline) ? 304 (AutocompleteResult::kLowestDefaultScore - 1) : 305 matches.begin()->raw_score; 306 if (will_have_url_what_you_typed_match_first) { 307 max_match_score = std::min(max_match_score, 308 url_what_you_typed_match_score - 1); 309 } 310 for (ScoredHistoryMatches::const_iterator match_iter = matches.begin(); 311 match_iter != matches.end(); ++match_iter) { 312 const ScoredHistoryMatch& history_match(*match_iter); 313 // Culls results corresponding to queries from the default search engine. 314 // These are low-quality, difficult-to-understand matches for users, and the 315 // SearchProvider should surface past queries in a better way anyway. 316 if (!template_url || 317 !template_url->IsSearchURL(history_match.url_info.url())) { 318 // Set max_match_score to the score we'll assign this result: 319 max_match_score = std::min(max_match_score, history_match.raw_score); 320 matches_.push_back(QuickMatchToACMatch(history_match, max_match_score)); 321 // Mark this max_match_score as being used: 322 max_match_score--; 323 } 324 } 325} 326 327AutocompleteMatch HistoryQuickProvider::QuickMatchToACMatch( 328 const ScoredHistoryMatch& history_match, 329 int score) { 330 const history::URLRow& info = history_match.url_info; 331 AutocompleteMatch match(this, score, !!info.visit_count(), 332 history_match.url_matches.empty() ? 333 AutocompleteMatch::HISTORY_TITLE : AutocompleteMatch::HISTORY_URL); 334 match.typed_count = info.typed_count(); 335 match.destination_url = info.url(); 336 DCHECK(match.destination_url.is_valid()); 337 338 // Format the URL autocomplete presentation. 339 std::vector<size_t> offsets = 340 OffsetsFromTermMatches(history_match.url_matches); 341 const net::FormatUrlTypes format_types = net::kFormatUrlOmitAll & 342 ~(!history_match.match_in_scheme ? 0 : net::kFormatUrlOmitHTTP); 343 match.fill_into_edit = 344 AutocompleteInput::FormattedStringWithEquivalentMeaning(info.url(), 345 net::FormatUrlWithOffsets(info.url(), languages_, format_types, 346 net::UnescapeRule::SPACES, NULL, NULL, &offsets)); 347 history::TermMatches new_matches = 348 ReplaceOffsetsInTermMatches(history_match.url_matches, offsets); 349 match.contents = net::FormatUrl(info.url(), languages_, format_types, 350 net::UnescapeRule::SPACES, NULL, NULL, NULL); 351 match.contents_class = 352 SpansFromTermMatch(new_matches, match.contents.length(), true); 353 354 if (!history_match.can_inline) { 355 match.inline_autocomplete_offset = string16::npos; 356 } else { 357 DCHECK(!new_matches.empty()); 358 match.inline_autocomplete_offset = new_matches[0].offset + 359 new_matches[0].length; 360 // The following will happen if the user has typed an URL with a scheme 361 // and the last character typed is a slash because that slash is removed 362 // by the FormatURLWithOffsets call above. 363 if (match.inline_autocomplete_offset > match.fill_into_edit.length()) 364 match.inline_autocomplete_offset = match.fill_into_edit.length(); 365 } 366 367 // Format the description autocomplete presentation. 368 match.description = info.title(); 369 match.description_class = SpansFromTermMatch( 370 history_match.title_matches, match.description.length(), false); 371 372 match.RecordAdditionalInfo("typed count", info.typed_count()); 373 match.RecordAdditionalInfo("visit count", info.visit_count()); 374 match.RecordAdditionalInfo("last visit", info.last_visit()); 375 376 return match; 377} 378 379history::InMemoryURLIndex* HistoryQuickProvider::GetIndex() { 380 if (index_for_testing_.get()) 381 return index_for_testing_.get(); 382 383 HistoryService* const history_service = 384 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS); 385 if (!history_service) 386 return NULL; 387 388 return history_service->InMemoryIndex(); 389} 390 391// static 392ACMatchClassifications HistoryQuickProvider::SpansFromTermMatch( 393 const history::TermMatches& matches, 394 size_t text_length, 395 bool is_url) { 396 ACMatchClassification::Style url_style = 397 is_url ? ACMatchClassification::URL : ACMatchClassification::NONE; 398 ACMatchClassifications spans; 399 if (matches.empty()) { 400 if (text_length) 401 spans.push_back(ACMatchClassification(0, url_style)); 402 return spans; 403 } 404 if (matches[0].offset) 405 spans.push_back(ACMatchClassification(0, url_style)); 406 size_t match_count = matches.size(); 407 for (size_t i = 0; i < match_count;) { 408 size_t offset = matches[i].offset; 409 spans.push_back(ACMatchClassification(offset, 410 ACMatchClassification::MATCH | url_style)); 411 // Skip all adjacent matches. 412 do { 413 offset += matches[i].length; 414 ++i; 415 } while ((i < match_count) && (offset == matches[i].offset)); 416 if (offset < text_length) 417 spans.push_back(ACMatchClassification(offset, url_style)); 418 } 419 420 return spans; 421} 422