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

Side by Side Diff: chrome/browser/bookmarks/bookmark_index.cc

Issue 253753005: Move bookmarks' production code to components/bookmarks (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@367656
Patch Set: Fix dependencies & includes Created 6 years, 7 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
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/bookmarks/bookmark_index.h"
6
7 #include <algorithm>
8 #include <functional>
9 #include <iterator>
10 #include <list>
11
12 #include "base/i18n/case_conversion.h"
13 #include "base/logging.h"
14 #include "base/strings/string16.h"
15 #include "chrome/browser/bookmarks/bookmark_utils.h"
16 #include "components/bookmarks/core/browser/bookmark_client.h"
17 #include "components/bookmarks/core/browser/bookmark_match.h"
18 #include "components/bookmarks/core/browser/bookmark_node.h"
19 #include "components/query_parser/query_parser.h"
20 #include "components/query_parser/snippet.h"
21 #include "third_party/icu/source/common/unicode/normalizer2.h"
22
23 typedef BookmarkClient::NodeTypedCountPair NodeTypedCountPair;
24 typedef BookmarkClient::NodeTypedCountPairs NodeTypedCountPairs;
25
26 namespace {
27
28 // Returns a normalized version of the UTF16 string |text|. If it fails to
29 // normalize the string, returns |text| itself as a best-effort.
30 base::string16 Normalize(const base::string16& text) {
31 UErrorCode status = U_ZERO_ERROR;
32 const icu::Normalizer2* normalizer2 =
33 icu::Normalizer2::getInstance(NULL, "nfkc", UNORM2_COMPOSE, status);
34 icu::UnicodeString unicode_text(text.data(), text.length());
35 icu::UnicodeString unicode_normalized_text;
36 normalizer2->normalize(unicode_text, unicode_normalized_text, status);
37 if (U_FAILURE(status))
38 return text;
39 return base::string16(unicode_normalized_text.getBuffer(),
40 unicode_normalized_text.length());
41 }
42
43 // Sort functor for NodeTypedCountPairs. We sort in decreasing order of typed
44 // count so that the best matches will always be added to the results.
45 struct NodeTypedCountPairSortFunctor
46 : std::binary_function<NodeTypedCountPair, NodeTypedCountPair, bool> {
47 bool operator()(const NodeTypedCountPair& a,
48 const NodeTypedCountPair& b) const {
49 return a.second > b.second;
50 }
51 };
52
53 // Extract the const Node* stored in a BookmarkClient::NodeTypedCountPair.
54 struct NodeTypedCountPairExtractNodeFunctor
55 : std::unary_function<NodeTypedCountPair, const BookmarkNode*> {
56 const BookmarkNode* operator()(const NodeTypedCountPair& pair) const {
57 return pair.first;
58 }
59 };
60
61 } // namespace
62
63 // Used when finding the set of bookmarks that match a query. Each match
64 // represents a set of terms (as an interator into the Index) matching the
65 // query as well as the set of nodes that contain those terms in their titles.
66 struct BookmarkIndex::Match {
67 // List of terms matching the query.
68 std::list<Index::const_iterator> terms;
69
70 // The set of nodes matching the terms. As an optimization this is empty
71 // when we match only one term, and is filled in when we get more than one
72 // term. We can do this as when we have only one matching term we know
73 // the set of matching nodes is terms.front()->second.
74 //
75 // Use nodes_begin() and nodes_end() to get an iterator over the set as
76 // it handles the necessary switching between nodes and terms.front().
77 NodeSet nodes;
78
79 // Returns an iterator to the beginning of the matching nodes. See
80 // description of nodes for why this should be used over nodes.begin().
81 NodeSet::const_iterator nodes_begin() const;
82
83 // Returns an iterator to the beginning of the matching nodes. See
84 // description of nodes for why this should be used over nodes.end().
85 NodeSet::const_iterator nodes_end() const;
86 };
87
88 BookmarkIndex::NodeSet::const_iterator
89 BookmarkIndex::Match::nodes_begin() const {
90 return nodes.empty() ? terms.front()->second.begin() : nodes.begin();
91 }
92
93 BookmarkIndex::NodeSet::const_iterator BookmarkIndex::Match::nodes_end() const {
94 return nodes.empty() ? terms.front()->second.end() : nodes.end();
95 }
96
97 BookmarkIndex::BookmarkIndex(BookmarkClient* client,
98 bool index_urls,
99 const std::string& languages)
100 : client_(client),
101 languages_(languages),
102 index_urls_(index_urls) {
103 DCHECK(client_);
104 }
105
106 BookmarkIndex::~BookmarkIndex() {
107 }
108
109 void BookmarkIndex::Add(const BookmarkNode* node) {
110 if (!node->is_url())
111 return;
112 std::vector<base::string16> terms =
113 ExtractQueryWords(Normalize(node->GetTitle()));
114 for (size_t i = 0; i < terms.size(); ++i)
115 RegisterNode(terms[i], node);
116 if (index_urls_) {
117 terms = ExtractQueryWords(
118 bookmark_utils::CleanUpUrlForMatching(node->url(), languages_));
119 for (size_t i = 0; i < terms.size(); ++i)
120 RegisterNode(terms[i], node);
121 }
122 }
123
124 void BookmarkIndex::Remove(const BookmarkNode* node) {
125 if (!node->is_url())
126 return;
127
128 std::vector<base::string16> terms =
129 ExtractQueryWords(Normalize(node->GetTitle()));
130 for (size_t i = 0; i < terms.size(); ++i)
131 UnregisterNode(terms[i], node);
132 if (index_urls_) {
133 terms = ExtractQueryWords(
134 bookmark_utils::CleanUpUrlForMatching(node->url(), languages_));
135 for (size_t i = 0; i < terms.size(); ++i)
136 UnregisterNode(terms[i], node);
137 }
138 }
139
140 void BookmarkIndex::GetBookmarksMatching(const base::string16& input_query,
141 size_t max_count,
142 std::vector<BookmarkMatch>* results) {
143 const base::string16 query = Normalize(input_query);
144 std::vector<base::string16> terms = ExtractQueryWords(query);
145 if (terms.empty())
146 return;
147
148 Matches matches;
149 for (size_t i = 0; i < terms.size(); ++i) {
150 if (!GetBookmarksMatchingTerm(terms[i], i == 0, &matches))
151 return;
152 }
153
154 Nodes sorted_nodes;
155 SortMatches(matches, &sorted_nodes);
156
157 // We use a QueryParser to fill in match positions for us. It's not the most
158 // efficient way to go about this, but by the time we get here we know what
159 // matches and so this shouldn't be performance critical.
160 query_parser::QueryParser parser;
161 ScopedVector<query_parser::QueryNode> query_nodes;
162 parser.ParseQueryNodes(query, &query_nodes.get());
163
164 // The highest typed counts should be at the beginning of the results vector
165 // so that the best matches will always be included in the results. The loop
166 // that calculates result relevance in HistoryContentsProvider::ConvertResults
167 // will run backwards to assure higher relevance will be attributed to the
168 // best matches.
169 for (Nodes::const_iterator i = sorted_nodes.begin();
170 i != sorted_nodes.end() && results->size() < max_count;
171 ++i)
172 AddMatchToResults(*i, &parser, query_nodes.get(), results);
173 }
174
175 void BookmarkIndex::SortMatches(const Matches& matches,
176 Nodes* sorted_nodes) const {
177 NodeSet nodes;
178 for (Matches::const_iterator i = matches.begin(); i != matches.end(); ++i) {
179 #if !defined(OS_ANDROID)
180 nodes.insert(i->nodes_begin(), i->nodes_end());
181 #else
182 // Work around a bug in the implementation of std::set::insert in the STL
183 // used on android (http://crbug.com/367050).
184 for (NodeSet::const_iterator n = i->nodes_begin(); n != i->nodes_end(); ++n)
185 nodes.insert(nodes.end(), *n);
186 #endif
187 }
188 sorted_nodes->reserve(sorted_nodes->size() + nodes.size());
189 if (client_->SupportsTypedCountForNodes()) {
190 NodeTypedCountPairs node_typed_counts;
191 client_->GetTypedCountForNodes(nodes, &node_typed_counts);
192 std::sort(node_typed_counts.begin(),
193 node_typed_counts.end(),
194 NodeTypedCountPairSortFunctor());
195 std::transform(node_typed_counts.begin(),
196 node_typed_counts.end(),
197 std::back_inserter(*sorted_nodes),
198 NodeTypedCountPairExtractNodeFunctor());
199 } else {
200 sorted_nodes->insert(sorted_nodes->end(), nodes.begin(), nodes.end());
201 }
202 }
203
204 void BookmarkIndex::AddMatchToResults(
205 const BookmarkNode* node,
206 query_parser::QueryParser* parser,
207 const query_parser::QueryNodeStarVector& query_nodes,
208 std::vector<BookmarkMatch>* results) {
209 // Check that the result matches the query. The previous search
210 // was a simple per-word search, while the more complex matching
211 // of QueryParser may filter it out. For example, the query
212 // ["thi"] will match the bookmark titled [Thinking], but since
213 // ["thi"] is quoted we don't want to do a prefix match.
214 query_parser::QueryWordVector title_words, url_words;
215 const base::string16 lower_title =
216 base::i18n::ToLower(Normalize(node->GetTitle()));
217 parser->ExtractQueryWords(lower_title, &title_words);
218 if (index_urls_) {
219 parser->ExtractQueryWords(
220 bookmark_utils::CleanUpUrlForMatching(node->url(), languages_),
221 &url_words);
222 }
223 query_parser::Snippet::MatchPositions title_matches, url_matches;
224 for (size_t i = 0; i < query_nodes.size(); ++i) {
225 const bool has_title_matches =
226 query_nodes[i]->HasMatchIn(title_words, &title_matches);
227 const bool has_url_matches = index_urls_ &&
228 query_nodes[i]->HasMatchIn(url_words, &url_matches);
229 if (!has_title_matches && !has_url_matches)
230 return;
231 query_parser::QueryParser::SortAndCoalesceMatchPositions(&title_matches);
232 if (index_urls_)
233 query_parser::QueryParser::SortAndCoalesceMatchPositions(&url_matches);
234 }
235 BookmarkMatch match;
236 if (lower_title.length() == node->GetTitle().length()) {
237 // Only use title matches if the lowercase string is the same length
238 // as the original string, otherwise the matches are meaningless.
239 // TODO(mpearson): revise match positions appropriately.
240 match.title_match_positions.swap(title_matches);
241 }
242 if (index_urls_)
243 match.url_match_positions.swap(url_matches);
244 match.node = node;
245 results->push_back(match);
246 }
247
248 bool BookmarkIndex::GetBookmarksMatchingTerm(const base::string16& term,
249 bool first_term,
250 Matches* matches) {
251 Index::const_iterator i = index_.lower_bound(term);
252 if (i == index_.end())
253 return false;
254
255 if (!query_parser::QueryParser::IsWordLongEnoughForPrefixSearch(term)) {
256 // Term is too short for prefix match, compare using exact match.
257 if (i->first != term)
258 return false; // No bookmarks with this term.
259
260 if (first_term) {
261 Match match;
262 match.terms.push_back(i);
263 matches->push_back(match);
264 return true;
265 }
266 CombineMatchesInPlace(i, matches);
267 } else if (first_term) {
268 // This is the first term and we're doing a prefix match. Loop through
269 // index adding all entries that start with term to matches.
270 while (i != index_.end() &&
271 i->first.size() >= term.size() &&
272 term.compare(0, term.size(), i->first, 0, term.size()) == 0) {
273 Match match;
274 match.terms.push_back(i);
275 matches->push_back(match);
276 ++i;
277 }
278 } else {
279 // Prefix match and not the first term. Loop through index combining
280 // current matches in matches with term, placing result in result.
281 Matches result;
282 while (i != index_.end() &&
283 i->first.size() >= term.size() &&
284 term.compare(0, term.size(), i->first, 0, term.size()) == 0) {
285 CombineMatches(i, *matches, &result);
286 ++i;
287 }
288 matches->swap(result);
289 }
290 return !matches->empty();
291 }
292
293 void BookmarkIndex::CombineMatchesInPlace(const Index::const_iterator& index_i,
294 Matches* matches) {
295 for (size_t i = 0; i < matches->size(); ) {
296 Match* match = &((*matches)[i]);
297 NodeSet intersection;
298 std::set_intersection(match->nodes_begin(), match->nodes_end(),
299 index_i->second.begin(), index_i->second.end(),
300 std::inserter(intersection, intersection.begin()));
301 if (intersection.empty()) {
302 matches->erase(matches->begin() + i);
303 } else {
304 match->terms.push_back(index_i);
305 match->nodes.swap(intersection);
306 ++i;
307 }
308 }
309 }
310
311 void BookmarkIndex::CombineMatches(const Index::const_iterator& index_i,
312 const Matches& current_matches,
313 Matches* result) {
314 for (size_t i = 0; i < current_matches.size(); ++i) {
315 const Match& match = current_matches[i];
316 NodeSet intersection;
317 std::set_intersection(match.nodes_begin(), match.nodes_end(),
318 index_i->second.begin(), index_i->second.end(),
319 std::inserter(intersection, intersection.begin()));
320 if (!intersection.empty()) {
321 result->push_back(Match());
322 Match& combined_match = result->back();
323 combined_match.terms = match.terms;
324 combined_match.terms.push_back(index_i);
325 combined_match.nodes.swap(intersection);
326 }
327 }
328 }
329
330 std::vector<base::string16> BookmarkIndex::ExtractQueryWords(
331 const base::string16& query) {
332 std::vector<base::string16> terms;
333 if (query.empty())
334 return std::vector<base::string16>();
335 query_parser::QueryParser parser;
336 parser.ParseQueryWords(base::i18n::ToLower(query), &terms);
337 return terms;
338 }
339
340 void BookmarkIndex::RegisterNode(const base::string16& term,
341 const BookmarkNode* node) {
342 index_[term].insert(node);
343 }
344
345 void BookmarkIndex::UnregisterNode(const base::string16& term,
346 const BookmarkNode* node) {
347 Index::iterator i = index_.find(term);
348 if (i == index_.end()) {
349 // We can get here if the node has the same term more than once. For
350 // example, a bookmark with the title 'foo foo' would end up here.
351 return;
352 }
353 i->second.erase(node);
354 if (i->second.empty())
355 index_.erase(i);
356 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698