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