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