shortcuts_provider.cc revision ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16
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/shortcuts_provider.h" 6 7#include <algorithm> 8#include <cmath> 9#include <map> 10#include <vector> 11 12#include "base/i18n/break_iterator.h" 13#include "base/i18n/case_conversion.h" 14#include "base/logging.h" 15#include "base/metrics/histogram.h" 16#include "base/prefs/pref_service.h" 17#include "base/strings/string_number_conversions.h" 18#include "base/strings/string_util.h" 19#include "base/strings/utf_string_conversions.h" 20#include "base/time/time.h" 21#include "chrome/browser/autocomplete/autocomplete_input.h" 22#include "chrome/browser/autocomplete/autocomplete_provider_listener.h" 23#include "chrome/browser/autocomplete/autocomplete_result.h" 24#include "chrome/browser/history/history_notifications.h" 25#include "chrome/browser/history/history_service.h" 26#include "chrome/browser/history/history_service_factory.h" 27#include "chrome/browser/history/shortcuts_backend_factory.h" 28#include "chrome/browser/omnibox/omnibox_field_trial.h" 29#include "chrome/browser/profiles/profile.h" 30#include "chrome/common/pref_names.h" 31#include "chrome/common/url_constants.h" 32#include "url/url_parse.h" 33 34namespace { 35 36class RemoveMatchPredicate { 37 public: 38 explicit RemoveMatchPredicate(const std::set<GURL>& urls) 39 : urls_(urls) { 40 } 41 bool operator()(const AutocompleteMatch& match) { 42 return urls_.find(match.destination_url) != urls_.end(); 43 } 44 private: 45 // Lifetime of the object is less than the lifetime of passed |urls|, so 46 // it is safe to store reference. 47 const std::set<GURL>& urls_; 48}; 49 50} // namespace 51 52ShortcutsProvider::ShortcutsProvider(AutocompleteProviderListener* listener, 53 Profile* profile) 54 : AutocompleteProvider(listener, profile, 55 AutocompleteProvider::TYPE_SHORTCUTS), 56 languages_(profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)), 57 initialized_(false) { 58 scoped_refptr<history::ShortcutsBackend> backend = 59 ShortcutsBackendFactory::GetForProfile(profile_); 60 if (backend.get()) { 61 backend->AddObserver(this); 62 if (backend->initialized()) 63 initialized_ = true; 64 } 65} 66 67void ShortcutsProvider::Start(const AutocompleteInput& input, 68 bool minimal_changes) { 69 matches_.clear(); 70 71 if ((input.type() == AutocompleteInput::INVALID) || 72 (input.type() == AutocompleteInput::FORCED_QUERY)) 73 return; 74 75 // None of our results are applicable for best match. 76 if (input.matches_requested() == AutocompleteInput::BEST_MATCH) 77 return; 78 79 if (input.text().empty()) 80 return; 81 82 if (!initialized_) 83 return; 84 85 base::TimeTicks start_time = base::TimeTicks::Now(); 86 GetMatches(input); 87 if (input.text().length() < 6) { 88 base::TimeTicks end_time = base::TimeTicks::Now(); 89 std::string name = "ShortcutsProvider.QueryIndexTime." + 90 base::IntToString(input.text().size()); 91 base::HistogramBase* counter = base::Histogram::FactoryGet( 92 name, 1, 1000, 50, base::Histogram::kUmaTargetedHistogramFlag); 93 counter->Add(static_cast<int>((end_time - start_time).InMilliseconds())); 94 } 95 UpdateStarredStateOfMatches(); 96} 97 98void ShortcutsProvider::DeleteMatch(const AutocompleteMatch& match) { 99 // Copy the URL since DeleteMatchesWithURLs() will invalidate |match|. 100 GURL url(match.destination_url); 101 102 // When a user deletes a match, he probably means for the URL to disappear out 103 // of history entirely. So nuke all shortcuts that map to this URL. 104 std::set<GURL> urls; 105 urls.insert(url); 106 // Immediately delete matches and shortcuts with the URL, so we can update the 107 // controller synchronously. 108 DeleteShortcutsWithURLs(urls); 109 DeleteMatchesWithURLs(urls); // NOTE: |match| is now dead! 110 111 // Delete the match from the history DB. This will eventually result in a 112 // second call to DeleteShortcutsWithURLs(), which is harmless. 113 HistoryService* const history_service = 114 HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS); 115 116 DCHECK(history_service && url.is_valid()); 117 history_service->DeleteURL(url); 118} 119 120ShortcutsProvider::~ShortcutsProvider() { 121 scoped_refptr<history::ShortcutsBackend> backend = 122 ShortcutsBackendFactory::GetForProfileIfExists(profile_); 123 if (backend.get()) 124 backend->RemoveObserver(this); 125} 126 127void ShortcutsProvider::OnShortcutsLoaded() { 128 initialized_ = true; 129} 130 131void ShortcutsProvider::DeleteMatchesWithURLs(const std::set<GURL>& urls) { 132 std::remove_if(matches_.begin(), matches_.end(), RemoveMatchPredicate(urls)); 133 listener_->OnProviderUpdate(true); 134} 135 136void ShortcutsProvider::DeleteShortcutsWithURLs(const std::set<GURL>& urls) { 137 scoped_refptr<history::ShortcutsBackend> backend = 138 ShortcutsBackendFactory::GetForProfileIfExists(profile_); 139 if (!backend.get()) 140 return; // We are off the record. 141 for (std::set<GURL>::const_iterator url = urls.begin(); url != urls.end(); 142 ++url) 143 backend->DeleteShortcutsWithUrl(*url); 144} 145 146void ShortcutsProvider::GetMatches(const AutocompleteInput& input) { 147 scoped_refptr<history::ShortcutsBackend> backend = 148 ShortcutsBackendFactory::GetForProfileIfExists(profile_); 149 if (!backend.get()) 150 return; 151 // Get the URLs from the shortcuts database with keys that partially or 152 // completely match the search term. 153 string16 term_string(base::i18n::ToLower(input.text())); 154 DCHECK(!term_string.empty()); 155 156 int max_relevance; 157 if (!OmniboxFieldTrial::ShortcutsScoringMaxRelevance( 158 input.current_page_classification(), &max_relevance)) 159 max_relevance = AutocompleteResult::kLowestDefaultScore - 1; 160 161 for (history::ShortcutsBackend::ShortcutMap::const_iterator it = 162 FindFirstMatch(term_string, backend.get()); 163 it != backend->shortcuts_map().end() && 164 StartsWith(it->first, term_string, true); ++it) { 165 // Don't return shortcuts with zero relevance. 166 int relevance = CalculateScore(term_string, it->second, max_relevance); 167 if (relevance) 168 matches_.push_back(ShortcutToACMatch(relevance, term_string, it->second)); 169 } 170 std::partial_sort(matches_.begin(), 171 matches_.begin() + 172 std::min(AutocompleteProvider::kMaxMatches, matches_.size()), 173 matches_.end(), &AutocompleteMatch::MoreRelevant); 174 if (matches_.size() > AutocompleteProvider::kMaxMatches) { 175 matches_.erase(matches_.begin() + AutocompleteProvider::kMaxMatches, 176 matches_.end()); 177 } 178 // Reset relevance scores to guarantee no results are given an 179 // inlineable score and all scores are decreasing (but not do assign 180 // any scores below 1). 181 max_relevance = AutocompleteResult::kLowestDefaultScore - 1; 182 for (ACMatches::iterator it = matches_.begin(); it != matches_.end(); ++it) { 183 max_relevance = std::min(max_relevance, it->relevance); 184 it->relevance = max_relevance; 185 if (max_relevance > 1) 186 --max_relevance; 187 } 188} 189 190AutocompleteMatch ShortcutsProvider::ShortcutToACMatch( 191 int relevance, 192 const string16& term_string, 193 const history::ShortcutsBackend::Shortcut& shortcut) { 194 DCHECK(!term_string.empty()); 195 AutocompleteMatch match(this, relevance, true, 196 AutocompleteMatchType::HISTORY_TITLE); 197 match.destination_url = shortcut.url; 198 DCHECK(match.destination_url.is_valid()); 199 match.fill_into_edit = UTF8ToUTF16(shortcut.url.spec()); 200 match.contents = shortcut.contents; 201 match.contents_class = shortcut.contents_class; 202 match.description = shortcut.description; 203 match.description_class = shortcut.description_class; 204 match.RecordAdditionalInfo("number of hits", shortcut.number_of_hits); 205 match.RecordAdditionalInfo("last access time", shortcut.last_access_time); 206 match.RecordAdditionalInfo("original input text", UTF16ToUTF8(shortcut.text)); 207 208 // Try to mark pieces of the contents and description as matches if they 209 // appear in |term_string|. 210 WordMap terms_map(CreateWordMapForString(term_string)); 211 if (!terms_map.empty()) { 212 match.contents_class = ClassifyAllMatchesInString(term_string, terms_map, 213 match.contents, match.contents_class); 214 match.description_class = ClassifyAllMatchesInString(term_string, terms_map, 215 match.description, match.description_class); 216 } 217 return match; 218} 219 220// static 221ShortcutsProvider::WordMap ShortcutsProvider::CreateWordMapForString( 222 const string16& text) { 223 // First, convert |text| to a vector of the unique words in it. 224 WordMap word_map; 225 base::i18n::BreakIterator word_iter(text, 226 base::i18n::BreakIterator::BREAK_WORD); 227 if (!word_iter.Init()) 228 return word_map; 229 std::vector<string16> words; 230 while (word_iter.Advance()) { 231 if (word_iter.IsWord()) 232 words.push_back(word_iter.GetString()); 233 } 234 if (words.empty()) 235 return word_map; 236 std::sort(words.begin(), words.end()); 237 words.erase(std::unique(words.begin(), words.end()), words.end()); 238 239 // Now create a map from (first character) to (words beginning with that 240 // character). We insert in reverse lexicographical order and rely on the 241 // multimap preserving insertion order for values with the same key. (This 242 // is mandated in C++11, and part of that decision was based on a survey of 243 // existing implementations that found that it was already true everywhere.) 244 std::reverse(words.begin(), words.end()); 245 for (std::vector<string16>::const_iterator i(words.begin()); i != words.end(); 246 ++i) 247 word_map.insert(std::make_pair((*i)[0], *i)); 248 return word_map; 249} 250 251// static 252ACMatchClassifications ShortcutsProvider::ClassifyAllMatchesInString( 253 const string16& find_text, 254 const WordMap& find_words, 255 const string16& text, 256 const ACMatchClassifications& original_class) { 257 DCHECK(!find_text.empty()); 258 DCHECK(!find_words.empty()); 259 260 // The code below assumes |text| is nonempty and therefore the resulting 261 // classification vector should always be nonempty as well. Returning early 262 // if |text| is empty assures we'll return the (correct) empty vector rather 263 // than a vector with a single (0, NONE) match. 264 if (text.empty()) 265 return original_class; 266 267 // First check whether |text| begins with |find_text| and mark that whole 268 // section as a match if so. 269 string16 text_lowercase(base::i18n::ToLower(text)); 270 ACMatchClassifications match_class; 271 size_t last_position = 0; 272 if (StartsWith(text_lowercase, find_text, true)) { 273 match_class.push_back( 274 ACMatchClassification(0, ACMatchClassification::MATCH)); 275 last_position = find_text.length(); 276 // If |text_lowercase| is actually equal to |find_text|, we don't need to 277 // (and in fact shouldn't) put a trailing NONE classification after the end 278 // of the string. 279 if (last_position < text_lowercase.length()) { 280 match_class.push_back( 281 ACMatchClassification(last_position, ACMatchClassification::NONE)); 282 } 283 } else { 284 // |match_class| should start at position 0. If the first matching word is 285 // found at position 0, this will be popped from the vector further down. 286 match_class.push_back( 287 ACMatchClassification(0, ACMatchClassification::NONE)); 288 } 289 290 // Now, starting with |last_position|, check each character in 291 // |text_lowercase| to see if we have words starting with that character in 292 // |find_words|. If so, check each of them to see if they match the portion 293 // of |text_lowercase| beginning with |last_position|. Accept the first 294 // matching word found (which should be the longest possible match at this 295 // location, given the construction of |find_words|) and add a MATCH region to 296 // |match_class|, moving |last_position| to be after the matching word. If we 297 // found no matching words, move to the next character and repeat. 298 while (last_position < text_lowercase.length()) { 299 std::pair<WordMap::const_iterator, WordMap::const_iterator> range( 300 find_words.equal_range(text_lowercase[last_position])); 301 size_t next_character = last_position + 1; 302 for (WordMap::const_iterator i(range.first); i != range.second; ++i) { 303 const string16& word = i->second; 304 size_t word_end = last_position + word.length(); 305 if ((word_end <= text_lowercase.length()) && 306 !text_lowercase.compare(last_position, word.length(), word)) { 307 // Collapse adjacent ranges into one. 308 if (match_class.back().offset == last_position) 309 match_class.pop_back(); 310 311 AutocompleteMatch::AddLastClassificationIfNecessary(&match_class, 312 last_position, ACMatchClassification::MATCH); 313 if (word_end < text_lowercase.length()) { 314 match_class.push_back( 315 ACMatchClassification(word_end, ACMatchClassification::NONE)); 316 } 317 last_position = word_end; 318 break; 319 } 320 } 321 last_position = std::max(last_position, next_character); 322 } 323 324 return AutocompleteMatch::MergeClassifications(original_class, match_class); 325} 326 327history::ShortcutsBackend::ShortcutMap::const_iterator 328 ShortcutsProvider::FindFirstMatch(const string16& keyword, 329 history::ShortcutsBackend* backend) { 330 DCHECK(backend); 331 history::ShortcutsBackend::ShortcutMap::const_iterator it = 332 backend->shortcuts_map().lower_bound(keyword); 333 // Lower bound not necessarily matches the keyword, check for item pointed by 334 // the lower bound iterator to at least start with keyword. 335 return ((it == backend->shortcuts_map().end()) || 336 StartsWith(it->first, keyword, true)) ? it : 337 backend->shortcuts_map().end(); 338} 339 340int ShortcutsProvider::CalculateScore( 341 const string16& terms, 342 const history::ShortcutsBackend::Shortcut& shortcut, 343 int max_relevance) { 344 DCHECK(!terms.empty()); 345 DCHECK_LE(terms.length(), shortcut.text.length()); 346 347 // The initial score is based on how much of the shortcut the user has typed. 348 // Using the square root of the typed fraction boosts the base score rapidly 349 // as characters are typed, compared with simply using the typed fraction 350 // directly. This makes sense since the first characters typed are much more 351 // important for determining how likely it is a user wants a particular 352 // shortcut than are the remaining continued characters. 353 double base_score = max_relevance * 354 sqrt(static_cast<double>(terms.length()) / shortcut.text.length()); 355 356 // Then we decay this by half each week. 357 const double kLn2 = 0.6931471805599453; 358 base::TimeDelta time_passed = base::Time::Now() - shortcut.last_access_time; 359 // Clamp to 0 in case time jumps backwards (e.g. due to DST). 360 double decay_exponent = std::max(0.0, kLn2 * static_cast<double>( 361 time_passed.InMicroseconds()) / base::Time::kMicrosecondsPerWeek); 362 363 // We modulate the decay factor based on how many times the shortcut has been 364 // used. Newly created shortcuts decay at full speed; otherwise, decaying by 365 // half takes |n| times as much time, where n increases by 366 // (1.0 / each 5 additional hits), up to a maximum of 5x as long. 367 const double kMaxDecaySpeedDivisor = 5.0; 368 const double kNumUsesPerDecaySpeedDivisorIncrement = 5.0; 369 double decay_divisor = std::min(kMaxDecaySpeedDivisor, 370 (shortcut.number_of_hits + kNumUsesPerDecaySpeedDivisorIncrement - 1) / 371 kNumUsesPerDecaySpeedDivisorIncrement); 372 373 return static_cast<int>((base_score / exp(decay_exponent / decay_divisor)) + 374 0.5); 375} 376