shortcuts_provider.cc revision 23730a6e56a168d1879203e4b3819bb36e3d8f1f
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_match.h"
23#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
24#include "chrome/browser/autocomplete/autocomplete_result.h"
25#include "chrome/browser/autocomplete/history_provider.h"
26#include "chrome/browser/autocomplete/shortcuts_backend_factory.h"
27#include "chrome/browser/autocomplete/url_prefix.h"
28#include "chrome/browser/history/history_notifications.h"
29#include "chrome/browser/history/history_service.h"
30#include "chrome/browser/history/history_service_factory.h"
31#include "chrome/browser/omnibox/omnibox_field_trial.h"
32#include "chrome/browser/profiles/profile.h"
33#include "chrome/common/net/url_fixer_upper.h"
34#include "chrome/common/pref_names.h"
35#include "chrome/common/url_constants.h"
36#include "url/url_parse.h"
37
38namespace {
39
40class DestinationURLEqualsURL {
41 public:
42  explicit DestinationURLEqualsURL(const GURL& url) : url_(url) {}
43  bool operator()(const AutocompleteMatch& match) const {
44    return match.destination_url == url_;
45  }
46 private:
47  const GURL url_;
48};
49
50// Like URLPrefix::BestURLPrefix() except also handles the prefix of
51// "www.".  This is needed because sometimes the string we're matching
52// against here (which comes from |fill_into_edit|) can start with
53// "www." without having a protocol at the beginning.  Because "www."
54// is not on the default prefix list, we test for it explicitly here
55// and use that match if the default list didn't have a match or the
56// default list's match was shorter than it could've been.
57const URLPrefix* BestURLPrefixWithWWWCase(
58    const base::string16& text,
59    const base::string16& prefix_suffix) {
60  CR_DEFINE_STATIC_LOCAL(URLPrefix, www_prefix,
61                         (base::ASCIIToUTF16("www."), 1));
62  const URLPrefix* best_prefix = URLPrefix::BestURLPrefix(text, prefix_suffix);
63  if ((best_prefix == NULL) ||
64      (best_prefix->num_components < www_prefix.num_components)) {
65    if (URLPrefix::PrefixMatch(www_prefix, text, prefix_suffix))
66      best_prefix = &www_prefix;
67  }
68  return best_prefix;
69}
70
71}  // namespace
72
73ShortcutsProvider::ShortcutsProvider(AutocompleteProviderListener* listener,
74                                     Profile* profile)
75    : AutocompleteProvider(listener, profile,
76          AutocompleteProvider::TYPE_SHORTCUTS),
77      languages_(profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)),
78      initialized_(false) {
79  scoped_refptr<ShortcutsBackend> backend =
80      ShortcutsBackendFactory::GetForProfile(profile_);
81  if (backend.get()) {
82    backend->AddObserver(this);
83    if (backend->initialized())
84      initialized_ = true;
85  }
86}
87
88void ShortcutsProvider::Start(const AutocompleteInput& input,
89                              bool minimal_changes) {
90  matches_.clear();
91
92  if ((input.type() == AutocompleteInput::INVALID) ||
93      (input.type() == AutocompleteInput::FORCED_QUERY))
94    return;
95
96  if (input.text().empty())
97    return;
98
99  if (!initialized_)
100    return;
101
102  base::TimeTicks start_time = base::TimeTicks::Now();
103  GetMatches(input);
104  if (input.text().length() < 6) {
105    base::TimeTicks end_time = base::TimeTicks::Now();
106    std::string name = "ShortcutsProvider.QueryIndexTime." +
107        base::IntToString(input.text().size());
108    base::HistogramBase* counter = base::Histogram::FactoryGet(
109        name, 1, 1000, 50, base::Histogram::kUmaTargetedHistogramFlag);
110    counter->Add(static_cast<int>((end_time - start_time).InMilliseconds()));
111  }
112  UpdateStarredStateOfMatches();
113}
114
115void ShortcutsProvider::DeleteMatch(const AutocompleteMatch& match) {
116  // Copy the URL since deleting from |matches_| will invalidate |match|.
117  GURL url(match.destination_url);
118  DCHECK(url.is_valid());
119
120  // When a user deletes a match, he probably means for the URL to disappear out
121  // of history entirely. So nuke all shortcuts that map to this URL.
122  scoped_refptr<ShortcutsBackend> backend =
123      ShortcutsBackendFactory::GetForProfileIfExists(profile_);
124  if (backend) // Can be NULL in Incognito.
125    backend->DeleteShortcutsWithURL(url);
126
127  matches_.erase(std::remove_if(matches_.begin(), matches_.end(),
128                                DestinationURLEqualsURL(url)),
129                 matches_.end());
130  // NOTE: |match| is now dead!
131
132  // Delete the match from the history DB. This will eventually result in a
133  // second call to DeleteShortcutsWithURL(), which is harmless.
134  HistoryService* const history_service =
135      HistoryServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
136  DCHECK(history_service);
137  history_service->DeleteURL(url);
138}
139
140ShortcutsProvider::~ShortcutsProvider() {
141  scoped_refptr<ShortcutsBackend> backend =
142      ShortcutsBackendFactory::GetForProfileIfExists(profile_);
143  if (backend.get())
144    backend->RemoveObserver(this);
145}
146
147void ShortcutsProvider::OnShortcutsLoaded() {
148  initialized_ = true;
149}
150
151void ShortcutsProvider::GetMatches(const AutocompleteInput& input) {
152  scoped_refptr<ShortcutsBackend> backend =
153      ShortcutsBackendFactory::GetForProfileIfExists(profile_);
154  if (!backend.get())
155    return;
156  // Get the URLs from the shortcuts database with keys that partially or
157  // completely match the search term.
158  base::string16 term_string(base::i18n::ToLower(input.text()));
159  DCHECK(!term_string.empty());
160
161  base::string16 fixed_up_term_string(term_string);
162  AutocompleteInput fixed_up_input(input);
163  if (FixupUserInput(&fixed_up_input))
164    fixed_up_term_string = fixed_up_input.text();
165
166  int max_relevance;
167  if (!OmniboxFieldTrial::ShortcutsScoringMaxRelevance(
168      input.current_page_classification(), &max_relevance))
169    max_relevance = AutocompleteResult::kLowestDefaultScore - 1;
170
171  for (ShortcutsBackend::ShortcutMap::const_iterator it =
172           FindFirstMatch(term_string, backend.get());
173       it != backend->shortcuts_map().end() &&
174           StartsWith(it->first, term_string, true); ++it) {
175    // Don't return shortcuts with zero relevance.
176    int relevance = CalculateScore(term_string, it->second, max_relevance);
177    if (relevance) {
178      matches_.push_back(ShortcutToACMatch(
179          it->second, relevance, term_string, fixed_up_term_string,
180          input.prevent_inline_autocomplete()));
181      matches_.back().ComputeStrippedDestinationURL(profile_);
182    }
183  }
184  // Remove duplicates.
185  std::sort(matches_.begin(), matches_.end(),
186            &AutocompleteMatch::DestinationSortFunc);
187  matches_.erase(std::unique(matches_.begin(), matches_.end(),
188                             &AutocompleteMatch::DestinationsEqual),
189                 matches_.end());
190  // Find best matches.
191  std::partial_sort(matches_.begin(),
192      matches_.begin() +
193          std::min(AutocompleteProvider::kMaxMatches, matches_.size()),
194      matches_.end(), &AutocompleteMatch::MoreRelevant);
195  if (matches_.size() > AutocompleteProvider::kMaxMatches) {
196    matches_.erase(matches_.begin() + AutocompleteProvider::kMaxMatches,
197                   matches_.end());
198  }
199  // Reset relevance scores to guarantee no match is given a score that may
200  // allow it to become the highest ranked match (i.e., the default match)
201  // unless either it is a legal default match (i.e., inlineable) or the
202  // omnibox will reorder matches as necessary to correct the problem.  In
203  // the process of resetting scores, guarantee that all scores are decreasing
204  // (but do not assign any scores below 1).
205  if (!OmniboxFieldTrial::ReorderForLegalDefaultMatch(
206          input.current_page_classification()) &&
207      (matches_.empty() || !matches_.front().allowed_to_be_default_match)) {
208    max_relevance = std::min(max_relevance,
209                             AutocompleteResult::kLowestDefaultScore - 1);
210  }
211  for (ACMatches::iterator it = matches_.begin(); it != matches_.end(); ++it) {
212    max_relevance = std::min(max_relevance, it->relevance);
213    it->relevance = max_relevance;
214    if (max_relevance > 1)
215      --max_relevance;
216  }
217}
218
219AutocompleteMatch ShortcutsProvider::ShortcutToACMatch(
220    const history::ShortcutsDatabase::Shortcut& shortcut,
221    int relevance,
222    const base::string16& term_string,
223    const base::string16& fixed_up_term_string,
224    const bool prevent_inline_autocomplete) {
225  DCHECK(!term_string.empty());
226  AutocompleteMatch match;
227  match.provider = this;
228  match.relevance = relevance;
229  match.deletable = true;
230  match.fill_into_edit = shortcut.match_core.fill_into_edit;
231  match.destination_url = shortcut.match_core.destination_url;
232  DCHECK(match.destination_url.is_valid());
233  match.contents = shortcut.match_core.contents;
234  match.contents_class = AutocompleteMatch::ClassificationsFromString(
235      shortcut.match_core.contents_class);
236  match.description = shortcut.match_core.description;
237  match.description_class = AutocompleteMatch::ClassificationsFromString(
238      shortcut.match_core.description_class);
239  match.transition =
240      static_cast<content::PageTransition>(shortcut.match_core.transition);
241  match.type = static_cast<AutocompleteMatch::Type>(shortcut.match_core.type);
242  match.keyword = shortcut.match_core.keyword;
243  match.RecordAdditionalInfo("number of hits", shortcut.number_of_hits);
244  match.RecordAdditionalInfo("last access time", shortcut.last_access_time);
245  match.RecordAdditionalInfo("original input text",
246                             base::UTF16ToUTF8(shortcut.text));
247
248  // Set |inline_autocompletion| and |allowed_to_be_default_match| if possible.
249  // If the match is a search query this is easy: simply check whether the
250  // user text is a prefix of the query.  If the match is a navigation, we
251  // assume the fill_into_edit looks something like a URL, so we use
252  // BestURLPrefix() to try and strip off any prefixes that the user might
253  // not think would change the meaning, but would otherwise prevent inline
254  // autocompletion.  This allows, for example, the input of "foo.c" to
255  // autocomplete to "foo.com" for a fill_into_edit of "http://foo.com".
256  if (AutocompleteMatch::IsSearchType(match.type)) {
257    if (StartsWith(match.fill_into_edit, term_string, false)) {
258      match.inline_autocompletion =
259          match.fill_into_edit.substr(term_string.length());
260      match.allowed_to_be_default_match =
261          !prevent_inline_autocomplete || match.inline_autocompletion.empty();
262    }
263  } else {
264    const URLPrefix* best_prefix =
265        BestURLPrefixWithWWWCase(match.fill_into_edit, term_string);
266    const base::string16* matching_string = &term_string;
267    // If we failed to find a best_prefix initially, try again using a
268    // fixed-up version of the user input.  This is especially useful to
269    // get about: URLs to inline against chrome:// shortcuts.  (about:
270    // URLs are fixed up to the chrome:// scheme.)
271    if ((best_prefix == NULL) && !fixed_up_term_string.empty() &&
272        (fixed_up_term_string != term_string)) {
273        best_prefix = BestURLPrefixWithWWWCase(
274            match.fill_into_edit, fixed_up_term_string);
275        matching_string = &fixed_up_term_string;
276    }
277    if (best_prefix != NULL) {
278      match.inline_autocompletion = match.fill_into_edit.substr(
279          best_prefix->prefix.length() + matching_string->length());
280      match.allowed_to_be_default_match =
281          !prevent_inline_autocomplete || match.inline_autocompletion.empty();
282    }
283  }
284
285  // Try to mark pieces of the contents and description as matches if they
286  // appear in |term_string|.
287  WordMap terms_map(CreateWordMapForString(term_string));
288  if (!terms_map.empty()) {
289    match.contents_class = ClassifyAllMatchesInString(term_string, terms_map,
290        match.contents, match.contents_class);
291    match.description_class = ClassifyAllMatchesInString(term_string, terms_map,
292        match.description, match.description_class);
293  }
294  return match;
295}
296
297// static
298ShortcutsProvider::WordMap ShortcutsProvider::CreateWordMapForString(
299    const base::string16& text) {
300  // First, convert |text| to a vector of the unique words in it.
301  WordMap word_map;
302  base::i18n::BreakIterator word_iter(text,
303                                      base::i18n::BreakIterator::BREAK_WORD);
304  if (!word_iter.Init())
305    return word_map;
306  std::vector<base::string16> words;
307  while (word_iter.Advance()) {
308    if (word_iter.IsWord())
309      words.push_back(word_iter.GetString());
310  }
311  if (words.empty())
312    return word_map;
313  std::sort(words.begin(), words.end());
314  words.erase(std::unique(words.begin(), words.end()), words.end());
315
316  // Now create a map from (first character) to (words beginning with that
317  // character).  We insert in reverse lexicographical order and rely on the
318  // multimap preserving insertion order for values with the same key.  (This
319  // is mandated in C++11, and part of that decision was based on a survey of
320  // existing implementations that found that it was already true everywhere.)
321  std::reverse(words.begin(), words.end());
322  for (std::vector<base::string16>::const_iterator i(words.begin());
323       i != words.end(); ++i)
324    word_map.insert(std::make_pair((*i)[0], *i));
325  return word_map;
326}
327
328// static
329ACMatchClassifications ShortcutsProvider::ClassifyAllMatchesInString(
330    const base::string16& find_text,
331    const WordMap& find_words,
332    const base::string16& text,
333    const ACMatchClassifications& original_class) {
334  DCHECK(!find_text.empty());
335  DCHECK(!find_words.empty());
336
337  // The code below assumes |text| is nonempty and therefore the resulting
338  // classification vector should always be nonempty as well.  Returning early
339  // if |text| is empty assures we'll return the (correct) empty vector rather
340  // than a vector with a single (0, NONE) match.
341  if (text.empty())
342    return original_class;
343
344  // First check whether |text| begins with |find_text| and mark that whole
345  // section as a match if so.
346  base::string16 text_lowercase(base::i18n::ToLower(text));
347  ACMatchClassifications match_class;
348  size_t last_position = 0;
349  if (StartsWith(text_lowercase, find_text, true)) {
350    match_class.push_back(
351        ACMatchClassification(0, ACMatchClassification::MATCH));
352    last_position = find_text.length();
353    // If |text_lowercase| is actually equal to |find_text|, we don't need to
354    // (and in fact shouldn't) put a trailing NONE classification after the end
355    // of the string.
356    if (last_position < text_lowercase.length()) {
357      match_class.push_back(
358          ACMatchClassification(last_position, ACMatchClassification::NONE));
359    }
360  } else {
361    // |match_class| should start at position 0.  If the first matching word is
362    // found at position 0, this will be popped from the vector further down.
363    match_class.push_back(
364        ACMatchClassification(0, ACMatchClassification::NONE));
365  }
366
367  // Now, starting with |last_position|, check each character in
368  // |text_lowercase| to see if we have words starting with that character in
369  // |find_words|.  If so, check each of them to see if they match the portion
370  // of |text_lowercase| beginning with |last_position|.  Accept the first
371  // matching word found (which should be the longest possible match at this
372  // location, given the construction of |find_words|) and add a MATCH region to
373  // |match_class|, moving |last_position| to be after the matching word.  If we
374  // found no matching words, move to the next character and repeat.
375  while (last_position < text_lowercase.length()) {
376    std::pair<WordMap::const_iterator, WordMap::const_iterator> range(
377        find_words.equal_range(text_lowercase[last_position]));
378    size_t next_character = last_position + 1;
379    for (WordMap::const_iterator i(range.first); i != range.second; ++i) {
380      const base::string16& word = i->second;
381      size_t word_end = last_position + word.length();
382      if ((word_end <= text_lowercase.length()) &&
383          !text_lowercase.compare(last_position, word.length(), word)) {
384        // Collapse adjacent ranges into one.
385        if (match_class.back().offset == last_position)
386          match_class.pop_back();
387
388        AutocompleteMatch::AddLastClassificationIfNecessary(&match_class,
389            last_position, ACMatchClassification::MATCH);
390        if (word_end < text_lowercase.length()) {
391          match_class.push_back(
392              ACMatchClassification(word_end, ACMatchClassification::NONE));
393        }
394        last_position = word_end;
395        break;
396      }
397    }
398    last_position = std::max(last_position, next_character);
399  }
400
401  return AutocompleteMatch::MergeClassifications(original_class, match_class);
402}
403
404ShortcutsBackend::ShortcutMap::const_iterator
405    ShortcutsProvider::FindFirstMatch(const base::string16& keyword,
406                                      ShortcutsBackend* backend) {
407  DCHECK(backend);
408  ShortcutsBackend::ShortcutMap::const_iterator it =
409      backend->shortcuts_map().lower_bound(keyword);
410  // Lower bound not necessarily matches the keyword, check for item pointed by
411  // the lower bound iterator to at least start with keyword.
412  return ((it == backend->shortcuts_map().end()) ||
413    StartsWith(it->first, keyword, true)) ? it :
414    backend->shortcuts_map().end();
415}
416
417int ShortcutsProvider::CalculateScore(
418    const base::string16& terms,
419    const history::ShortcutsDatabase::Shortcut& shortcut,
420    int max_relevance) {
421  DCHECK(!terms.empty());
422  DCHECK_LE(terms.length(), shortcut.text.length());
423
424  // The initial score is based on how much of the shortcut the user has typed.
425  // Using the square root of the typed fraction boosts the base score rapidly
426  // as characters are typed, compared with simply using the typed fraction
427  // directly. This makes sense since the first characters typed are much more
428  // important for determining how likely it is a user wants a particular
429  // shortcut than are the remaining continued characters.
430  double base_score = max_relevance *
431      sqrt(static_cast<double>(terms.length()) / shortcut.text.length());
432
433  // Then we decay this by half each week.
434  const double kLn2 = 0.6931471805599453;
435  base::TimeDelta time_passed = base::Time::Now() - shortcut.last_access_time;
436  // Clamp to 0 in case time jumps backwards (e.g. due to DST).
437  double decay_exponent = std::max(0.0, kLn2 * static_cast<double>(
438      time_passed.InMicroseconds()) / base::Time::kMicrosecondsPerWeek);
439
440  // We modulate the decay factor based on how many times the shortcut has been
441  // used. Newly created shortcuts decay at full speed; otherwise, decaying by
442  // half takes |n| times as much time, where n increases by
443  // (1.0 / each 5 additional hits), up to a maximum of 5x as long.
444  const double kMaxDecaySpeedDivisor = 5.0;
445  const double kNumUsesPerDecaySpeedDivisorIncrement = 5.0;
446  double decay_divisor = std::min(kMaxDecaySpeedDivisor,
447      (shortcut.number_of_hits + kNumUsesPerDecaySpeedDivisorIncrement - 1) /
448      kNumUsesPerDecaySpeedDivisorIncrement);
449
450  return static_cast<int>((base_score / exp(decay_exponent / decay_divisor)) +
451      0.5);
452}
453