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/bookmark_provider.h"
11 #include "base/prefs/pref_service.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
15 #include "chrome/browser/autocomplete/history_provider.h"
16 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
17 #include "chrome/browser/profiles/profile.h"
18 #include "chrome/common/pref_names.h"
19 #include "components/bookmarks/browser/bookmark_match.h"
20 #include "components/bookmarks/browser/bookmark_model.h"
21 #include "components/metrics/proto/omnibox_input_type.pb.h"
22 #include "components/omnibox/autocomplete_result.h"
23 #include "components/omnibox/url_prefix.h"
24 #include "net/base/net_util.h"
25 #include "url/url_constants.h"
27 using bookmarks::BookmarkMatch
;
28 using bookmarks::BookmarkNode
;
30 typedef std::vector
<BookmarkMatch
> BookmarkMatches
;
34 // Removes leading spaces from |title| before displaying, otherwise it looks
35 // funny. In the process, corrects |title_match_positions| so the correct
36 // characters are highlighted.
37 void CorrectTitleAndMatchPositions(
38 base::string16
* title
,
39 BookmarkMatch::MatchPositions
* title_match_positions
) {
40 size_t leading_whitespace_chars
= title
->length();
41 base::TrimWhitespace(*title
, base::TRIM_LEADING
, title
);
42 leading_whitespace_chars
-= title
->length();
43 if (leading_whitespace_chars
== 0)
45 for (query_parser::Snippet::MatchPositions::iterator it
=
46 title_match_positions
->begin();
47 it
!= title_match_positions
->end(); ++it
) {
48 (*it
) = query_parser::Snippet::MatchPosition(
49 it
->first
- leading_whitespace_chars
,
50 it
->second
- leading_whitespace_chars
);
56 // BookmarkProvider ------------------------------------------------------------
58 BookmarkProvider::BookmarkProvider(Profile
* profile
)
59 : AutocompleteProvider(AutocompleteProvider::TYPE_BOOKMARK
),
61 bookmark_model_(NULL
) {
63 bookmark_model_
= BookmarkModelFactory::GetForProfile(profile
);
64 languages_
= profile_
->GetPrefs()->GetString(prefs::kAcceptLanguages
);
68 void BookmarkProvider::Start(const AutocompleteInput
& input
,
70 bool called_due_to_focus
) {
75 if (called_due_to_focus
|| input
.text().empty() ||
76 (input
.type() == metrics::OmniboxInputType::FORCED_QUERY
))
79 DoAutocomplete(input
);
82 BookmarkProvider::~BookmarkProvider() {}
84 void BookmarkProvider::DoAutocomplete(const AutocompleteInput
& input
) {
85 // We may not have a bookmark model for some unit tests.
89 BookmarkMatches matches
;
90 // Retrieve enough bookmarks so that we have a reasonable probability of
91 // suggesting the one that the user desires.
92 const size_t kMaxBookmarkMatches
= 50;
94 // GetBookmarksMatching returns bookmarks matching the user's
95 // search terms using the following rules:
96 // - The search text is broken up into search terms. Each term is searched
98 // - Term matches are always performed against the start of a word. 'def'
99 // will match against 'define' but not against 'indefinite'.
100 // - Terms must be at least three characters in length in order to perform
101 // partial word matches. Any term of lesser length will only be used as an
102 // exact match. 'def' will match against 'define' but 'de' will not match.
103 // - A search containing multiple terms will return results with those words
104 // occuring in any order.
105 // - Terms enclosed in quotes comprises a phrase that must match exactly.
106 // - Multiple terms enclosed in quotes will require those exact words in that
107 // exact order to match.
109 // Please refer to the code for BookmarkIndex::GetBookmarksMatching for
110 // complete details of how searches are performed against the user's
112 bookmark_model_
->GetBookmarksMatching(input
.text(),
116 return; // There were no matches.
117 const base::string16
fixed_up_input(FixupUserInput(input
).second
);
118 for (BookmarkMatches::const_iterator i
= matches
.begin(); i
!= matches
.end();
120 // Create and score the AutocompleteMatch. If its score is 0 then the
121 // match is discarded.
122 AutocompleteMatch
match(BookmarkMatchToACMatch(input
, fixed_up_input
, *i
));
123 if (match
.relevance
> 0)
124 matches_
.push_back(match
);
127 // Sort and clip the resulting matches.
129 std::min(matches_
.size(), AutocompleteProvider::kMaxMatches
);
130 std::partial_sort(matches_
.begin(), matches_
.begin() + num_matches
,
131 matches_
.end(), AutocompleteMatch::MoreRelevant
);
132 matches_
.resize(num_matches
);
137 // for_each helper functor that calculates a match factor for each query term
138 // when calculating the final score.
140 // Calculate a 'factor' from 0 to the bookmark's title length for a match
141 // based on 1) how many characters match and 2) where the match is positioned.
142 class ScoringFunctor
{
144 // |title_length| is the length of the bookmark title against which this
145 // match will be scored.
146 explicit ScoringFunctor(size_t title_length
)
147 : title_length_(static_cast<double>(title_length
)),
148 scoring_factor_(0.0) {
151 void operator()(const query_parser::Snippet::MatchPosition
& match
) {
152 double term_length
= static_cast<double>(match
.second
- match
.first
);
153 scoring_factor_
+= term_length
*
154 (title_length_
- match
.first
) / title_length_
;
157 double ScoringFactor() { return scoring_factor_
; }
160 double title_length_
;
161 double scoring_factor_
;
166 AutocompleteMatch
BookmarkProvider::BookmarkMatchToACMatch(
167 const AutocompleteInput
& input
,
168 const base::string16
& fixed_up_input_text
,
169 const BookmarkMatch
& bookmark_match
) {
170 // The AutocompleteMatch we construct is non-deletable because the only
171 // way to support this would be to delete the underlying bookmark, which is
172 // unlikely to be what the user intends.
173 AutocompleteMatch
match(this, 0, false,
174 AutocompleteMatchType::BOOKMARK_TITLE
);
175 base::string16
title(bookmark_match
.node
->GetTitle());
176 BookmarkMatch::MatchPositions new_title_match_positions
=
177 bookmark_match
.title_match_positions
;
178 CorrectTitleAndMatchPositions(&title
, &new_title_match_positions
);
179 const GURL
& url(bookmark_match
.node
->url());
180 const base::string16
& url_utf16
= base::UTF8ToUTF16(url
.spec());
181 size_t inline_autocomplete_offset
= URLPrefix::GetInlineAutocompleteOffset(
182 input
.text(), fixed_up_input_text
, false, url_utf16
);
183 match
.destination_url
= url
;
184 const size_t match_start
= bookmark_match
.url_match_positions
.empty() ?
185 0 : bookmark_match
.url_match_positions
[0].first
;
186 const bool trim_http
= !AutocompleteInput::HasHTTPScheme(input
.text()) &&
187 ((match_start
== base::string16::npos
) || (match_start
!= 0));
188 std::vector
<size_t> offsets
= BookmarkMatch::OffsetsFromMatchPositions(
189 bookmark_match
.url_match_positions
);
190 // In addition to knowing how |offsets| is transformed, we need to know how
191 // |inline_autocomplete_offset| is transformed. We add it to the end of
192 // |offsets|, compute how everything is transformed, then remove it from the
194 offsets
.push_back(inline_autocomplete_offset
);
195 match
.contents
= net::FormatUrlWithOffsets(url
, languages_
,
196 net::kFormatUrlOmitAll
& ~(trim_http
? 0 : net::kFormatUrlOmitHTTP
),
197 net::UnescapeRule::SPACES
, NULL
, NULL
, &offsets
);
198 inline_autocomplete_offset
= offsets
.back();
200 BookmarkMatch::MatchPositions new_url_match_positions
=
201 BookmarkMatch::ReplaceOffsetsInMatchPositions(
202 bookmark_match
.url_match_positions
, offsets
);
203 match
.contents_class
=
204 ClassificationsFromMatch(new_url_match_positions
,
205 match
.contents
.size(),
207 match
.fill_into_edit
=
208 AutocompleteInput::FormattedStringWithEquivalentMeaning(
209 url
, match
.contents
, ChromeAutocompleteSchemeClassifier(profile_
));
210 if (inline_autocomplete_offset
!= base::string16::npos
) {
211 // |inline_autocomplete_offset| may be beyond the end of the
212 // |fill_into_edit| if the user has typed an URL with a scheme and the
213 // last character typed is a slash. That slash is removed by the
214 // FormatURLWithOffsets call above.
215 if (inline_autocomplete_offset
< match
.fill_into_edit
.length()) {
216 match
.inline_autocompletion
=
217 match
.fill_into_edit
.substr(inline_autocomplete_offset
);
219 match
.allowed_to_be_default_match
= match
.inline_autocompletion
.empty() ||
220 !HistoryProvider::PreventInlineAutocomplete(input
);
222 match
.description
= title
;
223 match
.description_class
=
224 ClassificationsFromMatch(bookmark_match
.title_match_positions
,
225 match
.description
.size(),
228 // Summary on how a relevance score is determined for the match:
230 // For each match within the bookmark's title or URL (or both), calculate a
231 // 'factor', sum up those factors, then use the sum to figure out a value
232 // between the base score and the maximum score.
234 // The factor for each match is the product of:
236 // 1) how many characters in the bookmark's title/URL are part of this match.
237 // This is capped at the length of the bookmark's title
238 // to prevent terms that match in both the title and the URL from
239 // scoring too strongly.
241 // 2) where the match occurs within the bookmark's title or URL,
242 // giving more points for matches that appear earlier in the string:
243 // ((string_length - position of match start) / string_length).
245 // Example: Given a bookmark title of 'abcde fghijklm', with a title length
246 // of 14, and two different search terms, 'abcde' and 'fghij', with
247 // start positions of 0 and 6, respectively, 'abcde' will score higher
248 // (with a a partial factor of (14-0)/14 = 1.000 ) than 'fghij' (with
249 // a partial factor of (14-6)/14 = 0.571 ). (In this example neither
250 // term matches in the URL.)
252 // Once all match factors have been calculated they are summed. If there
253 // are no URL matches, the resulting sum will never be greater than the
254 // length of the bookmark title because of the way the bookmark model matches
255 // and removes overlaps. (In particular, the bookmark model only
256 // matches terms to the beginning of words and it removes all overlapping
257 // matches, keeping only the longest. Together these mean that each
258 // character is included in at most one match.) If there are matches in the
259 // URL, the sum can be greater.
261 // This sum is then normalized by the length of the bookmark title + 10
262 // and capped at 1.0. The +10 is to expand the scoring range so fewer
263 // bookmarks will hit the 1.0 cap and hence lose all ability to distinguish
264 // between these high-quality bookmarks.
266 // The normalized value is multiplied against the scoring range available,
267 // which is the difference between the minimum possible score and the maximum
268 // possible score. This product is added to the minimum possible score to
269 // give the preliminary score.
271 // If the preliminary score is less than the maximum possible score, 1199,
272 // it can be boosted up to that maximum possible score if the URL referenced
273 // by the bookmark is also referenced by any of the user's other bookmarks.
274 // A count of how many times the bookmark's URL is referenced is determined
275 // and, for each additional reference beyond the one for the bookmark being
276 // scored up to a maximum of three, the score is boosted by a fixed amount
277 // given by |kURLCountBoost|, below.
280 // Pretend empty titles are identical to the URL.
282 title
= base::ASCIIToUTF16(url
.spec());
283 ScoringFunctor title_position_functor
=
284 for_each(bookmark_match
.title_match_positions
.begin(),
285 bookmark_match
.title_match_positions
.end(),
286 ScoringFunctor(title
.size()));
287 ScoringFunctor url_position_functor
=
288 for_each(bookmark_match
.url_match_positions
.begin(),
289 bookmark_match
.url_match_positions
.end(),
290 ScoringFunctor(bookmark_match
.node
->url().spec().length()));
291 const double title_match_strength
= title_position_functor
.ScoringFactor();
292 const double summed_factors
= title_match_strength
+
293 url_position_functor
.ScoringFactor();
294 const double normalized_sum
=
295 std::min(summed_factors
/ (title
.size() + 10), 1.0);
296 // Bookmarks with javascript scheme ("bookmarklets") that do not have title
297 // matches get a lower base and lower maximum score because returning them
298 // for matches in their (often very long) URL looks stupid and is often not
299 // intended by the user.
300 const bool bookmarklet_without_title_match
=
301 url
.SchemeIs(url::kJavaScriptScheme
) && (title_match_strength
== 0.0);
302 const int kBaseBookmarkScore
= bookmarklet_without_title_match
? 400 : 900;
303 const int kMaxBookmarkScore
= bookmarklet_without_title_match
? 799 : 1199;
304 const double kBookmarkScoreRange
=
305 static_cast<double>(kMaxBookmarkScore
- kBaseBookmarkScore
);
306 match
.relevance
= static_cast<int>(normalized_sum
* kBookmarkScoreRange
) +
308 // Don't waste any time searching for additional referenced URLs if we
309 // already have a perfect title match.
310 if (match
.relevance
>= kMaxBookmarkScore
)
312 // Boost the score if the bookmark's URL is referenced by other bookmarks.
313 const int kURLCountBoost
[4] = { 0, 75, 125, 150 };
314 std::vector
<const BookmarkNode
*> nodes
;
315 bookmark_model_
->GetNodesByURL(url
, &nodes
);
316 DCHECK_GE(std::min(arraysize(kURLCountBoost
), nodes
.size()), 1U);
318 kURLCountBoost
[std::min(arraysize(kURLCountBoost
), nodes
.size()) - 1];
319 match
.relevance
= std::min(kMaxBookmarkScore
, match
.relevance
);
324 ACMatchClassifications
BookmarkProvider::ClassificationsFromMatch(
325 const query_parser::Snippet::MatchPositions
& positions
,
328 ACMatchClassification::Style url_style
=
329 is_url
? ACMatchClassification::URL
: ACMatchClassification::NONE
;
330 ACMatchClassifications classifications
;
331 if (positions
.empty()) {
333 classifications
.push_back(ACMatchClassification(0, url_style
));
334 return classifications
;
337 for (query_parser::Snippet::MatchPositions::const_iterator i
=
339 i
!= positions
.end();
341 AutocompleteMatch::ACMatchClassifications new_class
;
342 AutocompleteMatch::ClassifyLocationInString(i
->first
, i
->second
- i
->first
,
343 text_length
, url_style
, &new_class
);
344 classifications
= AutocompleteMatch::MergeClassifications(
345 classifications
, new_class
);
347 return classifications
;