history_quick_provider.cc revision a93a17c8d99d686bd4a1511e5504e5e6cc9fcadf
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 const size_t registry_length = 269 net::registry_controlled_domains::GetRegistryLength( 270 host, 271 net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES, 272 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES); 273 if (registry_length == 0) { 274 // Known intranet hosts get one score. 275 url_what_you_typed_match_score = 276 HistoryURLProvider::kScoreForUnvisitedIntranetResult; 277 } else { 278 // Known internet hosts get another. 279 url_what_you_typed_match_score = 280 HistoryURLProvider::kScoreForWhatYouTypedResult; 281 } 282 } 283 } 284 } 285 } 286 287 // Loop over every result and add it to matches_. In the process, 288 // guarantee that scores are decreasing. |max_match_score| keeps 289 // track of the highest score we can assign to any later results we 290 // see. Also, if we're not allowing inline autocompletions in 291 // general or the current best suggestion isn't inlineable, 292 // artificially reduce the starting |max_match_score| (which 293 // therefore applies to all results) to something low enough that 294 // guarantees no result will be offered as an autocomplete 295 // suggestion. Also do a similar reduction if we think there will be 296 // a URL-what-you-typed match. (We want URL-what-you-typed matches for 297 // visited URLs to beat out any longer URLs, no matter how frequently 298 // they're visited.) The strength of this last reduction depends on the 299 // likely score for the URL-what-you-typed result. 300 301 // |template_url_service| or |template_url| can be NULL in unit tests. 302 TemplateURLService* template_url_service = 303 TemplateURLServiceFactory::GetForProfile(profile_); 304 TemplateURL* template_url = template_url_service ? 305 template_url_service->GetDefaultSearchProvider() : NULL; 306 int max_match_score = (PreventInlineAutocomplete(autocomplete_input_) || 307 !matches.begin()->can_inline) ? 308 (AutocompleteResult::kLowestDefaultScore - 1) : 309 matches.begin()->raw_score; 310 if (will_have_url_what_you_typed_match_first) { 311 max_match_score = std::min(max_match_score, 312 url_what_you_typed_match_score - 1); 313 } 314 for (ScoredHistoryMatches::const_iterator match_iter = matches.begin(); 315 match_iter != matches.end(); ++match_iter) { 316 const ScoredHistoryMatch& history_match(*match_iter); 317 // Culls results corresponding to queries from the default search engine. 318 // These are low-quality, difficult-to-understand matches for users, and the 319 // SearchProvider should surface past queries in a better way anyway. 320 if (!template_url || 321 !template_url->IsSearchURL(history_match.url_info.url())) { 322 // Set max_match_score to the score we'll assign this result: 323 max_match_score = std::min(max_match_score, history_match.raw_score); 324 matches_.push_back(QuickMatchToACMatch(history_match, max_match_score)); 325 // Mark this max_match_score as being used: 326 max_match_score--; 327 } 328 } 329} 330 331AutocompleteMatch HistoryQuickProvider::QuickMatchToACMatch( 332 const ScoredHistoryMatch& history_match, 333 int score) { 334 const history::URLRow& info = history_match.url_info; 335 AutocompleteMatch match(this, score, !!info.visit_count(), 336 history_match.url_matches.empty() ? 337 AutocompleteMatch::HISTORY_TITLE : AutocompleteMatch::HISTORY_URL); 338 match.typed_count = info.typed_count(); 339 match.destination_url = info.url(); 340 DCHECK(match.destination_url.is_valid()); 341 342 // Format the URL autocomplete presentation. 343 std::vector<size_t> offsets = 344 OffsetsFromTermMatches(history_match.url_matches); 345 const net::FormatUrlTypes format_types = net::kFormatUrlOmitAll & 346 ~(!history_match.match_in_scheme ? 0 : net::kFormatUrlOmitHTTP); 347 match.fill_into_edit = 348 AutocompleteInput::FormattedStringWithEquivalentMeaning(info.url(), 349 net::FormatUrlWithOffsets(info.url(), languages_, format_types, 350 net::UnescapeRule::SPACES, NULL, NULL, &offsets)); 351 history::TermMatches new_matches = 352 ReplaceOffsetsInTermMatches(history_match.url_matches, offsets); 353 match.contents = net::FormatUrl(info.url(), languages_, format_types, 354 net::UnescapeRule::SPACES, NULL, NULL, NULL); 355 match.contents_class = 356 SpansFromTermMatch(new_matches, match.contents.length(), true); 357 358 if (!history_match.can_inline) { 359 match.inline_autocomplete_offset = string16::npos; 360 } else { 361 DCHECK(!new_matches.empty()); 362 match.inline_autocomplete_offset = new_matches[0].offset + 363 new_matches[0].length; 364 // The following will happen if the user has typed an URL with a scheme 365 // and the last character typed is a slash because that slash is removed 366 // by the FormatURLWithOffsets call above. 367 if (match.inline_autocomplete_offset > match.fill_into_edit.length()) 368 match.inline_autocomplete_offset = match.fill_into_edit.length(); 369 } 370 371 // Format the description autocomplete presentation. 372 match.description = info.title(); 373 match.description_class = SpansFromTermMatch( 374 history_match.title_matches, match.description.length(), false); 375 376 match.RecordAdditionalInfo("typed count", info.typed_count()); 377 match.RecordAdditionalInfo("visit count", info.visit_count()); 378 match.RecordAdditionalInfo("last visit", info.last_visit()); 379 380 return match; 381} 382 383history::InMemoryURLIndex* HistoryQuickProvider::GetIndex() { 384 if (index_for_testing_.get()) 385 return index_for_testing_.get(); 386 387 HistoryService* const history_service = 388 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS); 389 if (!history_service) 390 return NULL; 391 392 return history_service->InMemoryIndex(); 393} 394 395// static 396ACMatchClassifications HistoryQuickProvider::SpansFromTermMatch( 397 const history::TermMatches& matches, 398 size_t text_length, 399 bool is_url) { 400 ACMatchClassification::Style url_style = 401 is_url ? ACMatchClassification::URL : ACMatchClassification::NONE; 402 ACMatchClassifications spans; 403 if (matches.empty()) { 404 if (text_length) 405 spans.push_back(ACMatchClassification(0, url_style)); 406 return spans; 407 } 408 if (matches[0].offset) 409 spans.push_back(ACMatchClassification(0, url_style)); 410 size_t match_count = matches.size(); 411 for (size_t i = 0; i < match_count;) { 412 size_t offset = matches[i].offset; 413 spans.push_back(ACMatchClassification(offset, 414 ACMatchClassification::MATCH | url_style)); 415 // Skip all adjacent matches. 416 do { 417 offset += matches[i].length; 418 ++i; 419 } while ((i < match_count) && (offset == matches[i].offset)); 420 if (offset < text_length) 421 spans.push_back(ACMatchClassification(offset, url_style)); 422 } 423 424 return spans; 425} 426