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 "components/omnibox/shortcuts_provider.h"
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 "components/history/core/browser/history_service.h"
22 #include "components/metrics/proto/omnibox_input_type.pb.h"
23 #include "components/omnibox/autocomplete_input.h"
24 #include "components/omnibox/autocomplete_match.h"
25 #include "components/omnibox/autocomplete_provider_client.h"
26 #include "components/omnibox/autocomplete_result.h"
27 #include "components/omnibox/history_provider.h"
28 #include "components/omnibox/omnibox_field_trial.h"
29 #include "components/omnibox/url_prefix.h"
30 #include "components/url_fixer/url_fixer.h"
31 #include "url/third_party/mozilla/url_parse.h"
35 class DestinationURLEqualsURL
{
37 explicit DestinationURLEqualsURL(const GURL
& url
) : url_(url
) {}
38 bool operator()(const AutocompleteMatch
& match
) const {
39 return match
.destination_url
== url_
;
48 const int ShortcutsProvider::kShortcutsProviderDefaultMaxRelevance
= 1199;
50 ShortcutsProvider::ShortcutsProvider(AutocompleteProviderClient
* client
)
51 : AutocompleteProvider(AutocompleteProvider::TYPE_SHORTCUTS
),
53 languages_(client_
->GetAcceptLanguages()),
55 scoped_refptr
<ShortcutsBackend
> backend
= client_
->GetShortcutsBackend();
57 backend
->AddObserver(this);
58 if (backend
->initialized())
63 void ShortcutsProvider::Start(const AutocompleteInput
& input
,
64 bool minimal_changes
) {
67 if (input
.from_omnibox_focus() ||
68 (input
.type() == metrics::OmniboxInputType::INVALID
) ||
69 (input
.type() == metrics::OmniboxInputType::FORCED_QUERY
) ||
70 input
.text().empty() || !initialized_
)
73 base::TimeTicks start_time
= base::TimeTicks::Now();
75 if (input
.text().length() < 6) {
76 base::TimeTicks end_time
= base::TimeTicks::Now();
77 std::string name
= "ShortcutsProvider.QueryIndexTime." +
78 base::IntToString(input
.text().size());
79 base::HistogramBase
* counter
= base::Histogram::FactoryGet(
80 name
, 1, 1000, 50, base::Histogram::kUmaTargetedHistogramFlag
);
81 counter
->Add(static_cast<int>((end_time
- start_time
).InMilliseconds()));
85 void ShortcutsProvider::DeleteMatch(const AutocompleteMatch
& match
) {
86 // Copy the URL since deleting from |matches_| will invalidate |match|.
87 GURL
url(match
.destination_url
);
88 DCHECK(url
.is_valid());
90 // When a user deletes a match, he probably means for the URL to disappear out
91 // of history entirely. So nuke all shortcuts that map to this URL.
92 scoped_refptr
<ShortcutsBackend
> backend
=
93 client_
->GetShortcutsBackendIfExists();
94 if (backend
.get()) // Can be NULL in Incognito.
95 backend
->DeleteShortcutsWithURL(url
);
97 matches_
.erase(std::remove_if(matches_
.begin(), matches_
.end(),
98 DestinationURLEqualsURL(url
)),
100 // NOTE: |match| is now dead!
102 // Delete the match from the history DB. This will eventually result in a
103 // second call to DeleteShortcutsWithURL(), which is harmless.
104 history::HistoryService
* const history_service
= client_
->GetHistoryService();
105 DCHECK(history_service
);
106 history_service
->DeleteURL(url
);
109 ShortcutsProvider::~ShortcutsProvider() {
110 scoped_refptr
<ShortcutsBackend
> backend
=
111 client_
->GetShortcutsBackendIfExists();
113 backend
->RemoveObserver(this);
116 void ShortcutsProvider::OnShortcutsLoaded() {
120 void ShortcutsProvider::GetMatches(const AutocompleteInput
& input
) {
121 scoped_refptr
<ShortcutsBackend
> backend
=
122 client_
->GetShortcutsBackendIfExists();
125 // Get the URLs from the shortcuts database with keys that partially or
126 // completely match the search term.
127 base::string16
term_string(base::i18n::ToLower(input
.text()));
128 DCHECK(!term_string
.empty());
131 if (!OmniboxFieldTrial::ShortcutsScoringMaxRelevance(
132 input
.current_page_classification(), &max_relevance
))
133 max_relevance
= kShortcutsProviderDefaultMaxRelevance
;
134 TemplateURLService
* template_url_service
= client_
->GetTemplateURLService();
135 const base::string16
fixed_up_input(FixupUserInput(input
).second
);
136 for (ShortcutsBackend::ShortcutMap::const_iterator it
=
137 FindFirstMatch(term_string
, backend
.get());
138 it
!= backend
->shortcuts_map().end() &&
139 base::StartsWith(it
->first
, term_string
,
140 base::CompareCase::SENSITIVE
);
142 // Don't return shortcuts with zero relevance.
143 int relevance
= CalculateScore(term_string
, it
->second
, max_relevance
);
146 ShortcutToACMatch(it
->second
, relevance
, input
, fixed_up_input
));
147 matches_
.back().ComputeStrippedDestinationURL(
148 input
, client_
->GetAcceptLanguages(), template_url_service
);
151 // Remove duplicates. This is important because it's common to have multiple
152 // shortcuts pointing to the same URL, e.g., ma, mai, and mail all pointing
153 // to mail.google.com, so typing "m" will return them all. If we then simply
154 // clamp to kMaxMatches and let the AutocompleteResult take care of
155 // collapsing the duplicates, we'll effectively only be returning one match,
156 // instead of several possibilities.
158 // Note that while removing duplicates, we don't populate a match's
159 // |duplicate_matches| field--duplicates don't need to be preserved in the
160 // matches because they are only used for deletions, and this provider
161 // deletes matches based on the URL.
162 AutocompleteResult::DedupMatchesByDestination(
163 input
.current_page_classification(), false, &matches_
);
164 // Find best matches.
168 std::min(AutocompleteProvider::kMaxMatches
, matches_
.size()),
169 matches_
.end(), &AutocompleteMatch::MoreRelevant
);
170 if (matches_
.size() > AutocompleteProvider::kMaxMatches
) {
171 matches_
.erase(matches_
.begin() + AutocompleteProvider::kMaxMatches
,
174 // Guarantee that all scores are decreasing (but do not assign any scores
176 for (ACMatches::iterator it
= matches_
.begin(); it
!= matches_
.end(); ++it
) {
177 max_relevance
= std::min(max_relevance
, it
->relevance
);
178 it
->relevance
= max_relevance
;
179 if (max_relevance
> 1)
184 AutocompleteMatch
ShortcutsProvider::ShortcutToACMatch(
185 const ShortcutsDatabase::Shortcut
& shortcut
,
187 const AutocompleteInput
& input
,
188 const base::string16
& fixed_up_input_text
) {
189 DCHECK(!input
.text().empty());
190 AutocompleteMatch match
;
191 match
.provider
= this;
192 match
.relevance
= relevance
;
193 match
.deletable
= true;
194 match
.fill_into_edit
= shortcut
.match_core
.fill_into_edit
;
195 match
.destination_url
= shortcut
.match_core
.destination_url
;
196 DCHECK(match
.destination_url
.is_valid());
197 match
.contents
= shortcut
.match_core
.contents
;
198 match
.contents_class
= AutocompleteMatch::ClassificationsFromString(
199 shortcut
.match_core
.contents_class
);
200 match
.description
= shortcut
.match_core
.description
;
201 match
.description_class
= AutocompleteMatch::ClassificationsFromString(
202 shortcut
.match_core
.description_class
);
203 match
.transition
= ui::PageTransitionFromInt(shortcut
.match_core
.transition
);
204 match
.type
= static_cast<AutocompleteMatch::Type
>(shortcut
.match_core
.type
);
205 match
.keyword
= shortcut
.match_core
.keyword
;
206 match
.RecordAdditionalInfo("number of hits", shortcut
.number_of_hits
);
207 match
.RecordAdditionalInfo("last access time", shortcut
.last_access_time
);
208 match
.RecordAdditionalInfo("original input text",
209 base::UTF16ToUTF8(shortcut
.text
));
211 // Set |inline_autocompletion| and |allowed_to_be_default_match| if possible.
212 // If the match is a search query this is easy: simply check whether the
213 // user text is a prefix of the query. If the match is a navigation, we
214 // assume the fill_into_edit looks something like a URL, so we use
215 // URLPrefix::GetInlineAutocompleteOffset() to try and strip off any prefixes
216 // that the user might not think would change the meaning, but would
217 // otherwise prevent inline autocompletion. This allows, for example, the
218 // input of "foo.c" to autocomplete to "foo.com" for a fill_into_edit of
220 if (AutocompleteMatch::IsSearchType(match
.type
)) {
221 if (base::StartsWith(base::i18n::ToLower(match
.fill_into_edit
),
222 base::i18n::ToLower(input
.text()),
223 base::CompareCase::SENSITIVE
)) {
224 match
.inline_autocompletion
=
225 match
.fill_into_edit
.substr(input
.text().length());
226 match
.allowed_to_be_default_match
=
227 !input
.prevent_inline_autocomplete() ||
228 match
.inline_autocompletion
.empty();
231 const size_t inline_autocomplete_offset
=
232 URLPrefix::GetInlineAutocompleteOffset(
233 input
.text(), fixed_up_input_text
, true, match
.fill_into_edit
);
234 if (inline_autocomplete_offset
!= base::string16::npos
) {
235 match
.inline_autocompletion
=
236 match
.fill_into_edit
.substr(inline_autocomplete_offset
);
237 match
.allowed_to_be_default_match
=
238 !HistoryProvider::PreventInlineAutocomplete(input
) ||
239 match
.inline_autocompletion
.empty();
242 match
.EnsureUWYTIsAllowedToBeDefault(input
,
243 client_
->GetAcceptLanguages(),
244 client_
->GetTemplateURLService());
246 // Try to mark pieces of the contents and description as matches if they
247 // appear in |input.text()|.
248 const base::string16 term_string
= base::i18n::ToLower(input
.text());
249 WordMap
terms_map(CreateWordMapForString(term_string
));
250 if (!terms_map
.empty()) {
251 match
.contents_class
= ClassifyAllMatchesInString(
252 term_string
, terms_map
, match
.contents
, match
.contents_class
);
253 match
.description_class
= ClassifyAllMatchesInString(
254 term_string
, terms_map
, match
.description
, match
.description_class
);
260 ShortcutsProvider::WordMap
ShortcutsProvider::CreateWordMapForString(
261 const base::string16
& text
) {
262 // First, convert |text| to a vector of the unique words in it.
264 base::i18n::BreakIterator
word_iter(text
,
265 base::i18n::BreakIterator::BREAK_WORD
);
266 if (!word_iter
.Init())
268 std::vector
<base::string16
> words
;
269 while (word_iter
.Advance()) {
270 if (word_iter
.IsWord())
271 words
.push_back(word_iter
.GetString());
275 std::sort(words
.begin(), words
.end());
276 words
.erase(std::unique(words
.begin(), words
.end()), words
.end());
278 // Now create a map from (first character) to (words beginning with that
279 // character). We insert in reverse lexicographical order and rely on the
280 // multimap preserving insertion order for values with the same key. (This
281 // is mandated in C++11, and part of that decision was based on a survey of
282 // existing implementations that found that it was already true everywhere.)
283 std::reverse(words
.begin(), words
.end());
284 for (std::vector
<base::string16
>::const_iterator
i(words
.begin());
285 i
!= words
.end(); ++i
)
286 word_map
.insert(std::make_pair((*i
)[0], *i
));
291 ACMatchClassifications
ShortcutsProvider::ClassifyAllMatchesInString(
292 const base::string16
& find_text
,
293 const WordMap
& find_words
,
294 const base::string16
& text
,
295 const ACMatchClassifications
& original_class
) {
296 DCHECK(!find_text
.empty());
297 DCHECK(!find_words
.empty());
299 // The code below assumes |text| is nonempty and therefore the resulting
300 // classification vector should always be nonempty as well. Returning early
301 // if |text| is empty assures we'll return the (correct) empty vector rather
302 // than a vector with a single (0, NONE) match.
304 return original_class
;
306 // First check whether |text| begins with |find_text| and mark that whole
307 // section as a match if so.
308 base::string16
text_lowercase(base::i18n::ToLower(text
));
309 ACMatchClassifications match_class
;
310 size_t last_position
= 0;
311 if (base::StartsWith(text_lowercase
, find_text
,
312 base::CompareCase::SENSITIVE
)) {
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
319 if (last_position
< text_lowercase
.length()) {
320 match_class
.push_back(
321 ACMatchClassification(last_position
, ACMatchClassification::NONE
));
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
));
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();
351 AutocompleteMatch::AddLastClassificationIfNecessary(
352 &match_class
, last_position
, ACMatchClassification::MATCH
);
353 if (word_end
< text_lowercase
.length()) {
354 match_class
.push_back(
355 ACMatchClassification(word_end
, ACMatchClassification::NONE
));
357 last_position
= word_end
;
361 last_position
= std::max(last_position
, next_character
);
364 return AutocompleteMatch::MergeClassifications(original_class
, match_class
);
367 ShortcutsBackend::ShortcutMap::const_iterator
ShortcutsProvider::FindFirstMatch(
368 const base::string16
& keyword
,
369 ShortcutsBackend
* 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 base::StartsWith(it
->first
, keyword
, base::CompareCase::SENSITIVE
))
378 : backend
->shortcuts_map().end();
381 int ShortcutsProvider::CalculateScore(
382 const base::string16
& terms
,
383 const ShortcutsDatabase::Shortcut
& shortcut
,
385 DCHECK(!terms
.empty());
386 DCHECK_LE(terms
.length(), shortcut
.text
.length());
388 // The initial score is based on how much of the shortcut the user has typed.
389 // Using the square root of the typed fraction boosts the base score rapidly
390 // as characters are typed, compared with simply using the typed fraction
391 // directly. This makes sense since the first characters typed are much more
392 // important for determining how likely it is a user wants a particular
393 // shortcut than are the remaining continued characters.
394 double base_score
= max_relevance
* sqrt(static_cast<double>(terms
.length()) /
395 shortcut
.text
.length());
397 // Then we decay this by half each week.
398 const double kLn2
= 0.6931471805599453;
399 base::TimeDelta time_passed
= base::Time::Now() - shortcut
.last_access_time
;
400 // Clamp to 0 in case time jumps backwards (e.g. due to DST).
401 double decay_exponent
=
402 std::max(0.0, kLn2
* static_cast<double>(time_passed
.InMicroseconds()) /
403 base::Time::kMicrosecondsPerWeek
);
405 // We modulate the decay factor based on how many times the shortcut has been
406 // used. Newly created shortcuts decay at full speed; otherwise, decaying by
407 // half takes |n| times as much time, where n increases by
408 // (1.0 / each 5 additional hits), up to a maximum of 5x as long.
409 const double kMaxDecaySpeedDivisor
= 5.0;
410 const double kNumUsesPerDecaySpeedDivisorIncrement
= 5.0;
411 double decay_divisor
= std::min(
412 kMaxDecaySpeedDivisor
,
413 (shortcut
.number_of_hits
+ kNumUsesPerDecaySpeedDivisorIncrement
- 1) /
414 kNumUsesPerDecaySpeedDivisorIncrement
);
416 return static_cast<int>((base_score
/ exp(decay_exponent
/ decay_divisor
)) +