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
, true);
141 // Don't return shortcuts with zero relevance.
142 int relevance
= CalculateScore(term_string
, it
->second
, max_relevance
);
145 ShortcutToACMatch(it
->second
, relevance
, input
, fixed_up_input
));
146 matches_
.back().ComputeStrippedDestinationURL(template_url_service
);
149 // Remove duplicates. Duplicates don't need to be preserved in the matches
150 // because they are only used for deletions, and shortcuts deletes matches
152 AutocompleteResult::DedupMatchesByDestination(
153 input
.current_page_classification(), false, &matches_
);
154 // Find best matches.
158 std::min(AutocompleteProvider::kMaxMatches
, matches_
.size()),
159 matches_
.end(), &AutocompleteMatch::MoreRelevant
);
160 if (matches_
.size() > AutocompleteProvider::kMaxMatches
) {
161 matches_
.erase(matches_
.begin() + AutocompleteProvider::kMaxMatches
,
164 // Guarantee that all scores are decreasing (but do not assign any scores
166 for (ACMatches::iterator it
= matches_
.begin(); it
!= matches_
.end(); ++it
) {
167 max_relevance
= std::min(max_relevance
, it
->relevance
);
168 it
->relevance
= max_relevance
;
169 if (max_relevance
> 1)
174 AutocompleteMatch
ShortcutsProvider::ShortcutToACMatch(
175 const ShortcutsDatabase::Shortcut
& shortcut
,
177 const AutocompleteInput
& input
,
178 const base::string16
& fixed_up_input_text
) {
179 DCHECK(!input
.text().empty());
180 AutocompleteMatch match
;
181 match
.provider
= this;
182 match
.relevance
= relevance
;
183 match
.deletable
= true;
184 match
.fill_into_edit
= shortcut
.match_core
.fill_into_edit
;
185 match
.destination_url
= shortcut
.match_core
.destination_url
;
186 DCHECK(match
.destination_url
.is_valid());
187 match
.contents
= shortcut
.match_core
.contents
;
188 match
.contents_class
= AutocompleteMatch::ClassificationsFromString(
189 shortcut
.match_core
.contents_class
);
190 match
.description
= shortcut
.match_core
.description
;
191 match
.description_class
= AutocompleteMatch::ClassificationsFromString(
192 shortcut
.match_core
.description_class
);
193 match
.transition
= ui::PageTransitionFromInt(shortcut
.match_core
.transition
);
194 match
.type
= static_cast<AutocompleteMatch::Type
>(shortcut
.match_core
.type
);
195 match
.keyword
= shortcut
.match_core
.keyword
;
196 match
.RecordAdditionalInfo("number of hits", shortcut
.number_of_hits
);
197 match
.RecordAdditionalInfo("last access time", shortcut
.last_access_time
);
198 match
.RecordAdditionalInfo("original input text",
199 base::UTF16ToUTF8(shortcut
.text
));
201 // Set |inline_autocompletion| and |allowed_to_be_default_match| if possible.
202 // If the match is a search query this is easy: simply check whether the
203 // user text is a prefix of the query. If the match is a navigation, we
204 // assume the fill_into_edit looks something like a URL, so we use
205 // URLPrefix::GetInlineAutocompleteOffset() to try and strip off any prefixes
206 // that the user might not think would change the meaning, but would
207 // otherwise prevent inline autocompletion. This allows, for example, the
208 // input of "foo.c" to autocomplete to "foo.com" for a fill_into_edit of
210 if (AutocompleteMatch::IsSearchType(match
.type
)) {
211 if (base::StartsWith(match
.fill_into_edit
, input
.text(), false)) {
212 match
.inline_autocompletion
=
213 match
.fill_into_edit
.substr(input
.text().length());
214 match
.allowed_to_be_default_match
=
215 !input
.prevent_inline_autocomplete() ||
216 match
.inline_autocompletion
.empty();
219 const size_t inline_autocomplete_offset
=
220 URLPrefix::GetInlineAutocompleteOffset(
221 input
.text(), fixed_up_input_text
, true, match
.fill_into_edit
);
222 if (inline_autocomplete_offset
!= base::string16::npos
) {
223 match
.inline_autocompletion
=
224 match
.fill_into_edit
.substr(inline_autocomplete_offset
);
225 match
.allowed_to_be_default_match
=
226 !HistoryProvider::PreventInlineAutocomplete(input
) ||
227 match
.inline_autocompletion
.empty();
230 match
.EnsureUWYTIsAllowedToBeDefault(input
.canonicalized_url(),
231 client_
->GetTemplateURLService());
233 // Try to mark pieces of the contents and description as matches if they
234 // appear in |input.text()|.
235 const base::string16 term_string
= base::i18n::ToLower(input
.text());
236 WordMap
terms_map(CreateWordMapForString(term_string
));
237 if (!terms_map
.empty()) {
238 match
.contents_class
= ClassifyAllMatchesInString(
239 term_string
, terms_map
, match
.contents
, match
.contents_class
);
240 match
.description_class
= ClassifyAllMatchesInString(
241 term_string
, terms_map
, match
.description
, match
.description_class
);
247 ShortcutsProvider::WordMap
ShortcutsProvider::CreateWordMapForString(
248 const base::string16
& text
) {
249 // First, convert |text| to a vector of the unique words in it.
251 base::i18n::BreakIterator
word_iter(text
,
252 base::i18n::BreakIterator::BREAK_WORD
);
253 if (!word_iter
.Init())
255 std::vector
<base::string16
> words
;
256 while (word_iter
.Advance()) {
257 if (word_iter
.IsWord())
258 words
.push_back(word_iter
.GetString());
262 std::sort(words
.begin(), words
.end());
263 words
.erase(std::unique(words
.begin(), words
.end()), words
.end());
265 // Now create a map from (first character) to (words beginning with that
266 // character). We insert in reverse lexicographical order and rely on the
267 // multimap preserving insertion order for values with the same key. (This
268 // is mandated in C++11, and part of that decision was based on a survey of
269 // existing implementations that found that it was already true everywhere.)
270 std::reverse(words
.begin(), words
.end());
271 for (std::vector
<base::string16
>::const_iterator
i(words
.begin());
272 i
!= words
.end(); ++i
)
273 word_map
.insert(std::make_pair((*i
)[0], *i
));
278 ACMatchClassifications
ShortcutsProvider::ClassifyAllMatchesInString(
279 const base::string16
& find_text
,
280 const WordMap
& find_words
,
281 const base::string16
& text
,
282 const ACMatchClassifications
& original_class
) {
283 DCHECK(!find_text
.empty());
284 DCHECK(!find_words
.empty());
286 // The code below assumes |text| is nonempty and therefore the resulting
287 // classification vector should always be nonempty as well. Returning early
288 // if |text| is empty assures we'll return the (correct) empty vector rather
289 // than a vector with a single (0, NONE) match.
291 return original_class
;
293 // First check whether |text| begins with |find_text| and mark that whole
294 // section as a match if so.
295 base::string16
text_lowercase(base::i18n::ToLower(text
));
296 ACMatchClassifications match_class
;
297 size_t last_position
= 0;
298 if (base::StartsWith(text_lowercase
, find_text
, true)) {
299 match_class
.push_back(
300 ACMatchClassification(0, ACMatchClassification::MATCH
));
301 last_position
= find_text
.length();
302 // If |text_lowercase| is actually equal to |find_text|, we don't need to
303 // (and in fact shouldn't) put a trailing NONE classification after the end
305 if (last_position
< text_lowercase
.length()) {
306 match_class
.push_back(
307 ACMatchClassification(last_position
, ACMatchClassification::NONE
));
310 // |match_class| should start at position 0. If the first matching word is
311 // found at position 0, this will be popped from the vector further down.
312 match_class
.push_back(
313 ACMatchClassification(0, ACMatchClassification::NONE
));
316 // Now, starting with |last_position|, check each character in
317 // |text_lowercase| to see if we have words starting with that character in
318 // |find_words|. If so, check each of them to see if they match the portion
319 // of |text_lowercase| beginning with |last_position|. Accept the first
320 // matching word found (which should be the longest possible match at this
321 // location, given the construction of |find_words|) and add a MATCH region to
322 // |match_class|, moving |last_position| to be after the matching word. If we
323 // found no matching words, move to the next character and repeat.
324 while (last_position
< text_lowercase
.length()) {
325 std::pair
<WordMap::const_iterator
, WordMap::const_iterator
> range(
326 find_words
.equal_range(text_lowercase
[last_position
]));
327 size_t next_character
= last_position
+ 1;
328 for (WordMap::const_iterator
i(range
.first
); i
!= range
.second
; ++i
) {
329 const base::string16
& word
= i
->second
;
330 size_t word_end
= last_position
+ word
.length();
331 if ((word_end
<= text_lowercase
.length()) &&
332 !text_lowercase
.compare(last_position
, word
.length(), word
)) {
333 // Collapse adjacent ranges into one.
334 if (match_class
.back().offset
== last_position
)
335 match_class
.pop_back();
337 AutocompleteMatch::AddLastClassificationIfNecessary(
338 &match_class
, last_position
, ACMatchClassification::MATCH
);
339 if (word_end
< text_lowercase
.length()) {
340 match_class
.push_back(
341 ACMatchClassification(word_end
, ACMatchClassification::NONE
));
343 last_position
= word_end
;
347 last_position
= std::max(last_position
, next_character
);
350 return AutocompleteMatch::MergeClassifications(original_class
, match_class
);
353 ShortcutsBackend::ShortcutMap::const_iterator
ShortcutsProvider::FindFirstMatch(
354 const base::string16
& keyword
,
355 ShortcutsBackend
* backend
) {
357 ShortcutsBackend::ShortcutMap::const_iterator it
=
358 backend
->shortcuts_map().lower_bound(keyword
);
359 // Lower bound not necessarily matches the keyword, check for item pointed by
360 // the lower bound iterator to at least start with keyword.
361 return ((it
== backend
->shortcuts_map().end()) ||
362 base::StartsWith(it
->first
, keyword
, true))
364 : backend
->shortcuts_map().end();
367 int ShortcutsProvider::CalculateScore(
368 const base::string16
& terms
,
369 const ShortcutsDatabase::Shortcut
& shortcut
,
371 DCHECK(!terms
.empty());
372 DCHECK_LE(terms
.length(), shortcut
.text
.length());
374 // The initial score is based on how much of the shortcut the user has typed.
375 // Using the square root of the typed fraction boosts the base score rapidly
376 // as characters are typed, compared with simply using the typed fraction
377 // directly. This makes sense since the first characters typed are much more
378 // important for determining how likely it is a user wants a particular
379 // shortcut than are the remaining continued characters.
380 double base_score
= max_relevance
* sqrt(static_cast<double>(terms
.length()) /
381 shortcut
.text
.length());
383 // Then we decay this by half each week.
384 const double kLn2
= 0.6931471805599453;
385 base::TimeDelta time_passed
= base::Time::Now() - shortcut
.last_access_time
;
386 // Clamp to 0 in case time jumps backwards (e.g. due to DST).
387 double decay_exponent
=
388 std::max(0.0, kLn2
* static_cast<double>(time_passed
.InMicroseconds()) /
389 base::Time::kMicrosecondsPerWeek
);
391 // We modulate the decay factor based on how many times the shortcut has been
392 // used. Newly created shortcuts decay at full speed; otherwise, decaying by
393 // half takes |n| times as much time, where n increases by
394 // (1.0 / each 5 additional hits), up to a maximum of 5x as long.
395 const double kMaxDecaySpeedDivisor
= 5.0;
396 const double kNumUsesPerDecaySpeedDivisorIncrement
= 5.0;
397 double decay_divisor
= std::min(
398 kMaxDecaySpeedDivisor
,
399 (shortcut
.number_of_hits
+ kNumUsesPerDecaySpeedDivisorIncrement
- 1) /
400 kNumUsesPerDecaySpeedDivisorIncrement
);
402 return static_cast<int>((base_score
/ exp(decay_exponent
/ decay_divisor
)) +