Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(111)

Side by Side Diff: chrome/browser/autocomplete/bookmark_provider.cc

Issue 10913262: Implement Bookmark Autocomplete Provider (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: Fixed match position coalescing. Created 8 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
Property Changes:
Added: svn:eol-style
+ LF
OLDNEW
(Empty)
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/bookmark_provider.h"
6
7 #include <algorithm>
8 #include <functional>
9 #include <vector>
10
11 #include "base/metrics/histogram.h"
12 #include "base/time.h"
13 #include "chrome/browser/autocomplete/autocomplete_result.h"
14 #include "chrome/browser/bookmarks/bookmark_model.h"
15 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
16 #include "chrome/browser/prefs/pref_service.h"
17 #include "chrome/browser/profiles/profile.h"
18 #include "chrome/common/pref_names.h"
19 #include "net/base/net_util.h"
20
21 typedef std::vector<bookmark_utils::TitleMatch> TitleMatches;
22
23 // BookmarkProvider ------------------------------------------------------------
24
25 BookmarkProvider::BookmarkProvider(
26 AutocompleteProviderListener* listener,
27 Profile* profile)
28 : AutocompleteProvider(listener, profile,
29 AutocompleteProvider::TYPE_BOOKMARK),
30 bookmark_model_(NULL) {
31 if (profile) {
32 bookmark_model_ = BookmarkModelFactory::GetForProfile(profile);
33 languages_ = profile_->GetPrefs()->GetString(prefs::kAcceptLanguages);
34 }
35 }
36
37 void BookmarkProvider::Start(const AutocompleteInput& input,
38 bool minimal_changes) {
39 if (minimal_changes)
40 return;
41 matches_.clear();
42
43 // Short-circuit any matching when inline autocompletion is disabled because
44 // none of the BookmarkProvider's matches can score high enough to qualify.
Peter Kasting 2012/10/15 22:17:22 Nit: This comment is not actually technically accu
mrossetti 2012/10/16 16:38:05 Ah, but of course.
45 if (input.text().empty() ||
46 ((input.type() != AutocompleteInput::UNKNOWN) &&
47 (input.type() != AutocompleteInput::REQUESTED_URL) &&
48 (input.type() != AutocompleteInput::QUERY)) ||
49 ((input.matches_requested() == AutocompleteInput::BEST_MATCH) &&
50 input.prevent_inline_autocomplete()))
51 return;
52
53 base::TimeTicks start_time = base::TimeTicks::Now();
54 DoAutocomplete(input,
55 input.matches_requested() == AutocompleteInput::BEST_MATCH);
56 UMA_HISTOGRAM_TIMES("Autocomplete.BookmarkProviderMatchTime",
57 base::TimeTicks::Now() - start_time);
58 }
59
60 BookmarkProvider::~BookmarkProvider() {}
61
62 void BookmarkProvider::DoAutocomplete(const AutocompleteInput& input,
63 bool best_match) {
64 // We may not have a bookmark model for some unit tests.
65 if (!bookmark_model_)
66 return;
67
68 TitleMatches matches;
69 // Retrieve enough bookmarks so that we have a reasonable probability of
70 // suggesting the one that the user desires.
71 const size_t kMaxBookmarkMatches = 50;
72
73 // GetBookmarksWithTitlesMatching returns bookmarks matching the user's
74 // search terms using the following rules:
75 // - The search text is broken up into search terms. Each term is searched
76 // for separately.
77 // - Term matches are always performed against the start of a word. 'def'
78 // will match against 'define' but not against 'indefinite'.
79 // - Terms must be at least three characters in length in order to perform
80 // partial word matches. Any term of lesser length will only be used as an
81 // exact match. 'def' will match against 'define' but 'de' will not match.
82 // - A search containing multiple terms will return results with those words
83 // occuring in any order.
84 // - Terms enclosed in quotes comprises a phrase that must match exactly.
85 // - Multiple terms enclosed in quotes will require those exact words in that
86 // exact order to match.
87 //
88 // Note: GetBookmarksWithTitlesMatching() will never return a match span
89 // greater than the length of the title against which it is being matched,
90 // nor can those spans ever overlap because the match spans are coalesced
91 // for all matched terms.
92 //
93 // Please refer to the code for BookmarkIndex::GetBookmarksWithTitlesMatching
94 // for complete details of how title searches are performed against the user's
95 // bookmarks.
96 bookmark_model_->GetBookmarksWithTitlesMatching(input.text(),
97 kMaxBookmarkMatches,
98 &matches);
99 if (matches.empty())
100 return; // There were no matches.
101 for (TitleMatches::const_iterator i = matches.begin(); i != matches.end();
102 ++i) {
103 AutocompleteMatch match(TitleMatchToACMatch(*i));
104 if (match.relevance > 0)
105 matches_.push_back(match);
106 }
107
108 // Sort and clip the resulting matches.
109 size_t max_matches = best_match ? 1 : AutocompleteProvider::kMaxMatches;
110 if (matches_.size() > max_matches) {
111 std::partial_sort(matches_.begin(), matches_.end(),
112 matches_.begin() + max_matches,
113 AutocompleteMatch::MoreRelevant);
114 matches_.resize(max_matches);
115 } else {
116 std::sort(matches_.begin(), matches_.end(),
117 AutocompleteMatch::MoreRelevant);
118 }
119 }
120
121 namespace {
122
123 // for_each helper functor that calculates a match factor for each query term
124 // when calculating the final score.
125 //
126 // Calculate a 'factor' from 0.0 to 1.0 based on 1) how much of the bookmark's
127 // title the term matches, and 2) where the match is positioned within the
128 // bookmark's title. A full length match earns a 1.0. A half-length match earns
129 // at most a 0.5 and at least a 0.25. A single character match against a title
130 // that is 100 characters long where the match is at the first character will
131 // earn a 0.01 and at the last character will earn a 0.0001.
132 class ScoringFunctor {
133 public:
134 // |title_length| is the length of the bookmark title against which this
135 // match will be scored.
136 explicit ScoringFunctor(size_t title_length)
137 : title_length_(static_cast<double>(title_length)),
138 scoring_factor_(0.0) {
139 }
140
141 void operator()(const Snippet::MatchPosition& match) {
142 double term_length = static_cast<double>(match.second - match.first);
143 scoring_factor_ += term_length / title_length_ *
144 (title_length_ - match.first) / title_length_;
145 }
146
147 double ScoringFactor() { return scoring_factor_; }
148
149 private:
150 double title_length_;
151 double scoring_factor_;
152 };
153
154 } // namespace
155
156 AutocompleteMatch BookmarkProvider::TitleMatchToACMatch(
157 const bookmark_utils::TitleMatch& title_match) {
158 // Compose a match that has 1) the URL of the bookmark, and 2) the bookmark's
159 // title, not the URL's page title, as the description. The match will be
160 // discarded if its relevance is never increased from 0. We always pass false
161 // for the |deletable| parameter in the following constructor to indicate
162 // that the AutocompleteMatch we construct is non-deletable because the only
Peter Kasting 2012/10/15 22:17:22 Nit: For clarity, I'd remove everything in this se
mrossetti 2012/10/16 16:38:05 Sounds good.
163 // way to support this would be to delete the underlying bookmark, which is
164 // unlikely to be what the user intends.
165 AutocompleteMatch match(this, 0, false, AutocompleteMatch::BOOKMARK_TITLE);
166 const string16& title(title_match.node->GetTitle());
167 DCHECK(!title.empty());
168 const GURL& url(title_match.node->url());
169 match.destination_url = url;
170 match.contents = net::FormatUrl(url, languages_,
171 net::kFormatUrlOmitAll & net::kFormatUrlOmitHTTP,
172 net::UnescapeRule::SPACES, NULL, NULL, NULL);
173 match.contents_class.push_back(
174 ACMatchClassification(0, ACMatchClassification::NONE));
175 match.fill_into_edit =
176 AutocompleteInput::FormattedStringWithEquivalentMeaning(url,
177 match.contents);
178 match.description = title;
179 match.description_class =
180 ClassificationsFromMatch(title_match.match_positions,
181 match.description.size());
182 match.starred = true;
183
184 // Summary on how a relevance score is determined for the match:
185 //
186 // For each term matching within the bookmark's title (as given by the set of
187 // Snippet::MatchPositions) calculate a 'factor', sum up those factors, then
188 // use the sum to figure out a value between the base score and the maximum
189 // score.
190 //
191 // The factor for each term is calculated based on:
192 //
193 // 1) how much of the bookmark's title has been matched by the term:
194 // (term length / title length).
195 //
196 // Example: Given a bookmark title of 'abcde fghijklm' and two different
197 // search terms, 'abcde' and 'fghijklm', 'fghijklm' will score higher
198 // (with a partial factor of 8/14 = 0.571) than 'abcde' (5/14 = 0.357).
199 //
200 // 2) where the term match occurs within the bookmark's title, giving more
201 // points for matches that appear earlier in the title:
202 // ((title length - position of match start) / title_length).
203 //
204 // Example: Given a bookmark title of 'abcde fghijklm' and two different
205 // search terms, 'abcde' and 'fghij', 'abcde' will score higher (with a
206 // match start position of 0 giving a partial factor of
207 // (14-0)/14 = 1.000 ) than 'fghij' (with a match start position of 6
208 // giving (14-6)/14 = 0.571 ).
209 //
210 // Once all term factors have been calculated they are summed. The resulting
211 // sum will never be greater than 1.0. This sum is then multiplied against
212 // the scoring range available, which is 299. The 299 is calculated by
213 // subtracting the minimum possible score, 900, from the maximum possible
214 // score, 1199. This product, ranging from 0 to 299, is added to the minimum
215 // possible score, 900, giving the preliminary score.
216 //
217 // If the preliminary score is less than the maximum possible score, 1199,
218 // it can be boosted if the URL referenced by the bookmark is also referenced
219 // by any of the user's other bookmarks. A count of how many times the
220 // bookmark's URL is referenced is determined and for each additional
221 // reference beyond the one for the bookmark being scored up to a maximum
222 // of three, the score is boosted by a fixed amount given by |kURLCountBoost|,
223 // below. As it is possible for this boost to cause the score to exceed the
224 // maximum possible score, the score is capped to that maximum possible.
225 //
226 ScoringFunctor position_functor =
227 for_each(title_match.match_positions.begin(),
228 title_match.match_positions.end(), ScoringFunctor(title.size()));
229 const int kBaseBookmarkScore = 900;
230 const int kMaxBookmarkScore = AutocompleteResult::kLowestDefaultScore - 1;
231 const double kBookmarkScoreRange =
232 static_cast<double>(kMaxBookmarkScore - kBaseBookmarkScore);
233 // It's not likely that GetBookmarksWithTitlesMatching will return overlapping
234 // matches but let's play it safe.
235 match.relevance = std::min(kMaxBookmarkScore,
236 static_cast<int>(position_functor.ScoringFactor() * kBookmarkScoreRange) +
237 kBaseBookmarkScore);
238 // Don't waste any time searching for additional referenced URLs if we
239 // already have a perfect title match.
240 if (match.relevance >= kMaxBookmarkScore)
241 return match;
242 // Boost the score if the bookmark's URL is referenced by other bookmarks.
243 const int kURLCountBoost[4] = { 0, 75, 125, 150 };
244 std::vector<const BookmarkNode*> nodes;
245 bookmark_model_->GetNodesByURL(url, &nodes);
246 DCHECK_GE(std::min(arraysize(kURLCountBoost), nodes.size()), 1U);
247 match.relevance +=
248 kURLCountBoost[std::min(arraysize(kURLCountBoost), nodes.size()) - 1];
249 match.relevance = std::min(kMaxBookmarkScore, match.relevance);
250 return match;
251 }
252
253 // static
254 ACMatchClassifications BookmarkProvider::ClassificationsFromMatch(
255 const Snippet::MatchPositions& positions,
256 size_t text_length) {
257 ACMatchClassifications classifications;
258 if (positions.empty()) {
259 classifications.push_back(
260 ACMatchClassification(0, ACMatchClassification::NONE));
261 return classifications;
262 }
263
264 for (Snippet::MatchPositions::const_iterator i = positions.begin();
265 i != positions.end(); ++i) {
266 AutocompleteMatch::ACMatchClassifications new_class;
267 AutocompleteMatch::ClassifyLocationInString(i->first, i->second - i->first,
268 text_length, 0, &new_class);
269 classifications = AutocompleteMatch::MergeClassifications(
270 classifications, new_class);
271 }
272 return classifications;
273 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698