history_quick_provider.cc revision cedac228d2dd51db4b79ea1e72c7f249408ee061
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/strings/string_number_conversions.h" 17#include "base/strings/string_util.h" 18#include "base/strings/utf_string_conversions.h" 19#include "base/time/time.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/omnibox/omnibox_field_trial.h" 29#include "chrome/browser/profiles/profile.h" 30#include "chrome/browser/search/search.h" 31#include "chrome/browser/search_engines/template_url.h" 32#include "chrome/browser/search_engines/template_url_service.h" 33#include "chrome/browser/search_engines/template_url_service_factory.h" 34#include "chrome/common/autocomplete_match_type.h" 35#include "chrome/common/chrome_switches.h" 36#include "chrome/common/net/url_fixer_upper.h" 37#include "chrome/common/pref_names.h" 38#include "chrome/common/url_constants.h" 39#include "content/public/browser/notification_source.h" 40#include "content/public/browser/notification_types.h" 41#include "net/base/escape.h" 42#include "net/base/net_util.h" 43#include "net/base/registry_controlled_domains/registry_controlled_domain.h" 44#include "url/url_parse.h" 45#include "url/url_util.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} 60 61void HistoryQuickProvider::Start(const AutocompleteInput& input, 62 bool minimal_changes) { 63 matches_.clear(); 64 if (disabled_) 65 return; 66 67 // Don't bother with INVALID and FORCED_QUERY. 68 if ((input.type() == AutocompleteInput::INVALID) || 69 (input.type() == AutocompleteInput::FORCED_QUERY)) 70 return; 71 72 autocomplete_input_ = input; 73 74 // TODO(pkasting): We should just block here until this loads. Any time 75 // someone unloads the history backend, we'll get inconsistent inline 76 // autocomplete behavior here. 77 if (GetIndex()) { 78 base::TimeTicks start_time = base::TimeTicks::Now(); 79 DoAutocomplete(); 80 if (input.text().length() < 6) { 81 base::TimeTicks end_time = base::TimeTicks::Now(); 82 std::string name = "HistoryQuickProvider.QueryIndexTime." + 83 base::IntToString(input.text().length()); 84 base::HistogramBase* counter = base::Histogram::FactoryGet( 85 name, 1, 1000, 50, base::Histogram::kUmaTargetedHistogramFlag); 86 counter->Add(static_cast<int>((end_time - start_time).InMilliseconds())); 87 } 88 UpdateStarredStateOfMatches(); 89 } 90} 91 92void HistoryQuickProvider::DeleteMatch(const AutocompleteMatch& match) { 93 DCHECK(match.deletable); 94 DCHECK(match.destination_url.is_valid()); 95 // Delete the match from the InMemoryURLIndex. 96 GetIndex()->DeleteURL(match.destination_url); 97 DeleteMatchFromMatches(match); 98} 99 100HistoryQuickProvider::~HistoryQuickProvider() {} 101 102void HistoryQuickProvider::DoAutocomplete() { 103 // Get the matching URLs from the DB. 104 ScoredHistoryMatches matches = GetIndex()->HistoryItemsForTerms( 105 autocomplete_input_.text(), 106 autocomplete_input_.cursor_position(), 107 AutocompleteProvider::kMaxMatches); 108 if (matches.empty()) 109 return; 110 111 // Figure out if HistoryURL provider has a URL-what-you-typed match 112 // that ought to go first and what its score will be. 113 bool will_have_url_what_you_typed_match_first = false; 114 int url_what_you_typed_match_score = -1; // undefined 115 // These are necessary (but not sufficient) conditions for the omnibox 116 // input to be a URL-what-you-typed match. The username test checks that 117 // either the username does not exist (a regular URL such as http://site/) 118 // or, if the username exists (http://user@site/), there must be either 119 // a password or a port. Together these exclude pure username@site 120 // inputs because these are likely to be an e-mail address. HistoryURL 121 // provider won't promote the URL-what-you-typed match to first 122 // for these inputs. 123 const bool can_have_url_what_you_typed_match_first = 124 (autocomplete_input_.type() != AutocompleteInput::QUERY) && 125 (!autocomplete_input_.parts().username.is_nonempty() || 126 autocomplete_input_.parts().password.is_nonempty() || 127 autocomplete_input_.parts().path.is_nonempty()); 128 if (can_have_url_what_you_typed_match_first) { 129 HistoryService* const history_service = 130 HistoryServiceFactory::GetForProfile(profile_, 131 Profile::EXPLICIT_ACCESS); 132 // We expect HistoryService to be available. In case it's not, 133 // (e.g., due to Profile corruption) we let HistoryQuick provider 134 // completions (which may be available because it's a different 135 // data structure) compete with the URL-what-you-typed match as 136 // normal. 137 if (history_service) { 138 history::URLDatabase* url_db = history_service->InMemoryDatabase(); 139 // url_db can be NULL if it hasn't finished initializing (or 140 // failed to to initialize). In this case, we let HistoryQuick 141 // provider completions compete with the URL-what-you-typed 142 // match as normal. 143 if (url_db) { 144 const std::string host(base::UTF16ToUTF8( 145 autocomplete_input_.text().substr( 146 autocomplete_input_.parts().host.begin, 147 autocomplete_input_.parts().host.len))); 148 // We want to put the URL-what-you-typed match first if either 149 // * the user visited the URL before (intranet or internet). 150 // * it's a URL on a host that user visited before and this 151 // is the root path of the host. (If the user types some 152 // of a path--more than a simple "/"--we let autocomplete compete 153 // normally with the URL-what-you-typed match.) 154 // TODO(mpearson): Remove this hacky code and simply score URL-what- 155 // you-typed in some sane way relative to possible completions: 156 // URL-what-you-typed should get some sort of a boost relative 157 // to completions, but completions should naturally win if 158 // they're a lot more popular. In this process, if the input 159 // is a bare intranet hostname that has been visited before, we 160 // may want to enforce that the only completions that can outscore 161 // the URL-what-you-typed match are on the same host (i.e., aren't 162 // from a longer internet hostname for which the omnibox input is 163 // a prefix). 164 if (url_db->GetRowForURL( 165 autocomplete_input_.canonicalized_url(), NULL) != 0) { 166 // We visited this URL before. 167 will_have_url_what_you_typed_match_first = true; 168 // HistoryURLProvider gives visited what-you-typed URLs a high score. 169 url_what_you_typed_match_score = 170 HistoryURLProvider::kScoreForBestInlineableResult; 171 } else if (url_db->IsTypedHost(host) && 172 (!autocomplete_input_.parts().path.is_nonempty() || 173 ((autocomplete_input_.parts().path.len == 1) && 174 (autocomplete_input_.text()[ 175 autocomplete_input_.parts().path.begin] == '/'))) && 176 !autocomplete_input_.parts().query.is_nonempty() && 177 !autocomplete_input_.parts().ref.is_nonempty()) { 178 // Not visited, but we've seen the host before. 179 will_have_url_what_you_typed_match_first = true; 180 const size_t registry_length = 181 net::registry_controlled_domains::GetRegistryLength( 182 host, 183 net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES, 184 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES); 185 if (registry_length == 0) { 186 // Known intranet hosts get one score. 187 url_what_you_typed_match_score = 188 HistoryURLProvider::kScoreForUnvisitedIntranetResult; 189 } else { 190 // Known internet hosts get another. 191 url_what_you_typed_match_score = 192 HistoryURLProvider::kScoreForWhatYouTypedResult; 193 } 194 } 195 } 196 } 197 } 198 199 // Loop over every result and add it to matches_. In the process, 200 // guarantee that scores are decreasing. |max_match_score| keeps 201 // track of the highest score we can assign to any later results we 202 // see. Also, reduce |max_match_score| if we think there will be 203 // a URL-what-you-typed match. (We want URL-what-you-typed matches for 204 // visited URLs to beat out any longer URLs, no matter how frequently 205 // they're visited.) The strength of this reduction depends on the 206 // likely score for the URL-what-you-typed result. 207 208 // |template_url_service| or |template_url| can be NULL in unit tests. 209 TemplateURLService* template_url_service = 210 TemplateURLServiceFactory::GetForProfile(profile_); 211 TemplateURL* template_url = template_url_service ? 212 template_url_service->GetDefaultSearchProvider() : NULL; 213 int max_match_score = matches.begin()->raw_score(); 214 if (will_have_url_what_you_typed_match_first) { 215 max_match_score = std::min(max_match_score, 216 url_what_you_typed_match_score - 1); 217 } 218 for (ScoredHistoryMatches::const_iterator match_iter = matches.begin(); 219 match_iter != matches.end(); ++match_iter) { 220 const ScoredHistoryMatch& history_match(*match_iter); 221 // Culls results corresponding to queries from the default search engine. 222 // These are low-quality, difficult-to-understand matches for users, and the 223 // SearchProvider should surface past queries in a better way anyway. 224 if (!template_url || 225 !template_url->IsSearchURL(history_match.url_info.url())) { 226 // Set max_match_score to the score we'll assign this result: 227 max_match_score = std::min(max_match_score, history_match.raw_score()); 228 matches_.push_back(QuickMatchToACMatch(history_match, max_match_score)); 229 // Mark this max_match_score as being used: 230 max_match_score--; 231 } 232 } 233} 234 235AutocompleteMatch HistoryQuickProvider::QuickMatchToACMatch( 236 const ScoredHistoryMatch& history_match, 237 int score) { 238 const history::URLRow& info = history_match.url_info; 239 AutocompleteMatch match( 240 this, score, !!info.visit_count(), 241 history_match.url_matches().empty() ? 242 AutocompleteMatchType::HISTORY_TITLE : 243 AutocompleteMatchType::HISTORY_URL); 244 match.typed_count = info.typed_count(); 245 match.destination_url = info.url(); 246 DCHECK(match.destination_url.is_valid()); 247 248 // Format the URL autocomplete presentation. 249 const net::FormatUrlTypes format_types = net::kFormatUrlOmitAll & 250 ~(!history_match.match_in_scheme ? 0 : net::kFormatUrlOmitHTTP); 251 match.fill_into_edit = 252 AutocompleteInput::FormattedStringWithEquivalentMeaning( 253 info.url(), 254 net::FormatUrl(info.url(), languages_, format_types, 255 net::UnescapeRule::SPACES, NULL, NULL, NULL)); 256 std::vector<size_t> offsets = 257 OffsetsFromTermMatches(history_match.url_matches()); 258 base::OffsetAdjuster::Adjustments adjustments; 259 match.contents = net::FormatUrlWithAdjustments( 260 info.url(), languages_, format_types, net::UnescapeRule::SPACES, NULL, 261 NULL, &adjustments); 262 base::OffsetAdjuster::AdjustOffsets(adjustments, &offsets); 263 history::TermMatches new_matches = 264 ReplaceOffsetsInTermMatches(history_match.url_matches(), offsets); 265 match.contents_class = 266 SpansFromTermMatch(new_matches, match.contents.length(), true); 267 268 // Set |inline_autocompletion| and |allowed_to_be_default_match| if possible. 269 if (history_match.can_inline()) { 270 DCHECK(!new_matches.empty()); 271 size_t inline_autocomplete_offset = new_matches[0].offset + 272 new_matches[0].length; 273 // |inline_autocomplete_offset| may be beyond the end of the 274 // |fill_into_edit| if the user has typed an URL with a scheme and the 275 // last character typed is a slash. That slash is removed by the 276 // FormatURLWithOffsets call above. 277 if (inline_autocomplete_offset < match.fill_into_edit.length()) { 278 match.inline_autocompletion = 279 match.fill_into_edit.substr(inline_autocomplete_offset); 280 } 281 match.allowed_to_be_default_match = match.inline_autocompletion.empty() || 282 !PreventInlineAutocomplete(autocomplete_input_); 283 } 284 285 // Format the description autocomplete presentation. 286 match.description = info.title(); 287 match.description_class = SpansFromTermMatch( 288 history_match.title_matches(), match.description.length(), false); 289 290 match.RecordAdditionalInfo("typed count", info.typed_count()); 291 match.RecordAdditionalInfo("visit count", info.visit_count()); 292 match.RecordAdditionalInfo("last visit", info.last_visit()); 293 294 return match; 295} 296 297history::InMemoryURLIndex* HistoryQuickProvider::GetIndex() { 298 if (index_for_testing_.get()) 299 return index_for_testing_.get(); 300 301 HistoryService* const history_service = 302 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS); 303 if (!history_service) 304 return NULL; 305 306 return history_service->InMemoryIndex(); 307} 308