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

Side by Side Diff: components/bookmarks/core/browser/bookmark_utils.cc

Issue 284893003: Move bookmarks/core/... to bookmarks/... (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Fixing errors reported by presubmit 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 2014 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 "components/bookmarks/core/browser/bookmark_utils.h"
6
7 #include <utility>
8
9 #include "base/basictypes.h"
10 #include "base/files/file_path.h"
11 #include "base/i18n/case_conversion.h"
12 #include "base/i18n/string_search.h"
13 #include "base/metrics/user_metrics_action.h"
14 #include "base/prefs/pref_service.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/time/time.h"
17 #include "components/bookmarks/core/browser/bookmark_model.h"
18 #include "components/bookmarks/core/browser/scoped_group_bookmark_actions.h"
19 #include "components/bookmarks/core/common/bookmark_pref_names.h"
20 #include "components/pref_registry/pref_registry_syncable.h"
21 #include "components/query_parser/query_parser.h"
22 #include "net/base/net_util.h"
23 #include "ui/base/models/tree_node_iterator.h"
24 #include "url/gurl.h"
25
26 using base::Time;
27
28 namespace {
29
30 // The maximum length of URL or title returned by the Cleanup functions.
31 const size_t kCleanedUpUrlMaxLength = 1024u;
32 const size_t kCleanedUpTitleMaxLength = 1024u;
33
34 void CloneBookmarkNodeImpl(BookmarkModel* model,
35 const BookmarkNodeData::Element& element,
36 const BookmarkNode* parent,
37 int index_to_add_at,
38 bool reset_node_times) {
39 if (element.is_url) {
40 Time date_added = reset_node_times ? Time::Now() : element.date_added;
41 DCHECK(!date_added.is_null());
42
43 model->AddURLWithCreationTimeAndMetaInfo(parent,
44 index_to_add_at,
45 element.title,
46 element.url,
47 date_added,
48 &element.meta_info_map);
49 } else {
50 const BookmarkNode* cloned_node = model->AddFolderWithMetaInfo(
51 parent, index_to_add_at, element.title, &element.meta_info_map);
52 if (!reset_node_times) {
53 DCHECK(!element.date_folder_modified.is_null());
54 model->SetDateFolderModified(cloned_node, element.date_folder_modified);
55 }
56 for (int i = 0; i < static_cast<int>(element.children.size()); ++i)
57 CloneBookmarkNodeImpl(model, element.children[i], cloned_node, i,
58 reset_node_times);
59 }
60 }
61
62 // Comparison function that compares based on date modified of the two nodes.
63 bool MoreRecentlyModified(const BookmarkNode* n1, const BookmarkNode* n2) {
64 return n1->date_folder_modified() > n2->date_folder_modified();
65 }
66
67 // Returns true if |text| contains each string in |words|. This is used when
68 // searching for bookmarks.
69 bool DoesBookmarkTextContainWords(const base::string16& text,
70 const std::vector<base::string16>& words) {
71 for (size_t i = 0; i < words.size(); ++i) {
72 if (!base::i18n::StringSearchIgnoringCaseAndAccents(
73 words[i], text, NULL, NULL)) {
74 return false;
75 }
76 }
77 return true;
78 }
79
80 // Returns true if |node|s title or url contains the strings in |words|.
81 // |languages| argument is user's accept-language setting to decode IDN.
82 bool DoesBookmarkContainWords(const BookmarkNode* node,
83 const std::vector<base::string16>& words,
84 const std::string& languages) {
85 return
86 DoesBookmarkTextContainWords(node->GetTitle(), words) ||
87 DoesBookmarkTextContainWords(
88 base::UTF8ToUTF16(node->url().spec()), words) ||
89 DoesBookmarkTextContainWords(net::FormatUrl(
90 node->url(), languages, net::kFormatUrlOmitNothing,
91 net::UnescapeRule::NORMAL, NULL, NULL, NULL), words);
92 }
93
94 // This is used with a tree iterator to skip subtrees which are not visible.
95 bool PruneInvisibleFolders(const BookmarkNode* node) {
96 return !node->IsVisible();
97 }
98
99 // This traces parents up to root, determines if node is contained in a
100 // selected folder.
101 bool HasSelectedAncestor(BookmarkModel* model,
102 const std::vector<const BookmarkNode*>& selected_nodes,
103 const BookmarkNode* node) {
104 if (!node || model->is_permanent_node(node))
105 return false;
106
107 for (size_t i = 0; i < selected_nodes.size(); ++i)
108 if (node->id() == selected_nodes[i]->id())
109 return true;
110
111 return HasSelectedAncestor(model, selected_nodes, node->parent());
112 }
113
114 const BookmarkNode* GetNodeByID(const BookmarkNode* node, int64 id) {
115 if (node->id() == id)
116 return node;
117
118 for (int i = 0, child_count = node->child_count(); i < child_count; ++i) {
119 const BookmarkNode* result = GetNodeByID(node->GetChild(i), id);
120 if (result)
121 return result;
122 }
123 return NULL;
124 }
125
126 // Attempts to shorten a URL safely (i.e., by preventing the end of the URL
127 // from being in the middle of an escape sequence) to no more than
128 // kCleanedUpUrlMaxLength characters, returning the result.
129 std::string TruncateUrl(const std::string& url) {
130 if (url.length() <= kCleanedUpUrlMaxLength)
131 return url;
132
133 // If we're in the middle of an escape sequence, truncate just before it.
134 if (url[kCleanedUpUrlMaxLength - 1] == '%')
135 return url.substr(0, kCleanedUpUrlMaxLength - 1);
136 if (url[kCleanedUpUrlMaxLength - 2] == '%')
137 return url.substr(0, kCleanedUpUrlMaxLength - 2);
138
139 return url.substr(0, kCleanedUpUrlMaxLength);
140 }
141
142 } // namespace
143
144 namespace bookmark_utils {
145
146 QueryFields::QueryFields() {}
147 QueryFields::~QueryFields() {}
148
149 void CloneBookmarkNode(BookmarkModel* model,
150 const std::vector<BookmarkNodeData::Element>& elements,
151 const BookmarkNode* parent,
152 int index_to_add_at,
153 bool reset_node_times) {
154 if (!parent->is_folder() || !model) {
155 NOTREACHED();
156 return;
157 }
158 for (size_t i = 0; i < elements.size(); ++i) {
159 CloneBookmarkNodeImpl(model, elements[i], parent,
160 index_to_add_at + static_cast<int>(i),
161 reset_node_times);
162 }
163 }
164
165 void CopyToClipboard(BookmarkModel* model,
166 const std::vector<const BookmarkNode*>& nodes,
167 bool remove_nodes) {
168 if (nodes.empty())
169 return;
170
171 // Create array of selected nodes with descendants filtered out.
172 std::vector<const BookmarkNode*> filtered_nodes;
173 for (size_t i = 0; i < nodes.size(); ++i)
174 if (!HasSelectedAncestor(model, nodes, nodes[i]->parent()))
175 filtered_nodes.push_back(nodes[i]);
176
177 BookmarkNodeData(filtered_nodes).
178 WriteToClipboard(ui::CLIPBOARD_TYPE_COPY_PASTE);
179
180 if (remove_nodes) {
181 ScopedGroupBookmarkActions group_cut(model);
182 for (size_t i = 0; i < filtered_nodes.size(); ++i) {
183 int index = filtered_nodes[i]->parent()->GetIndexOf(filtered_nodes[i]);
184 if (index > -1)
185 model->Remove(filtered_nodes[i]->parent(), index);
186 }
187 }
188 }
189
190 void PasteFromClipboard(BookmarkModel* model,
191 const BookmarkNode* parent,
192 int index) {
193 if (!parent)
194 return;
195
196 BookmarkNodeData bookmark_data;
197 if (!bookmark_data.ReadFromClipboard(ui::CLIPBOARD_TYPE_COPY_PASTE))
198 return;
199
200 if (index == -1)
201 index = parent->child_count();
202 ScopedGroupBookmarkActions group_paste(model);
203 CloneBookmarkNode(model, bookmark_data.elements, parent, index, true);
204 }
205
206 bool CanPasteFromClipboard(const BookmarkNode* node) {
207 if (!node)
208 return false;
209 return BookmarkNodeData::ClipboardContainsBookmarks();
210 }
211
212 std::vector<const BookmarkNode*> GetMostRecentlyModifiedFolders(
213 BookmarkModel* model,
214 size_t max_count) {
215 std::vector<const BookmarkNode*> nodes;
216 ui::TreeNodeIterator<const BookmarkNode> iterator(model->root_node(),
217 PruneInvisibleFolders);
218
219 while (iterator.has_next()) {
220 const BookmarkNode* parent = iterator.Next();
221 if (parent->is_folder() && parent->date_folder_modified() > Time()) {
222 if (max_count == 0) {
223 nodes.push_back(parent);
224 } else {
225 std::vector<const BookmarkNode*>::iterator i =
226 std::upper_bound(nodes.begin(), nodes.end(), parent,
227 &MoreRecentlyModified);
228 if (nodes.size() < max_count || i != nodes.end()) {
229 nodes.insert(i, parent);
230 while (nodes.size() > max_count)
231 nodes.pop_back();
232 }
233 }
234 } // else case, the root node, which we don't care about or imported nodes
235 // (which have a time of 0).
236 }
237
238 if (nodes.size() < max_count) {
239 // Add the permanent nodes if there is space. The permanent nodes are the
240 // only children of the root_node.
241 const BookmarkNode* root_node = model->root_node();
242
243 for (int i = 0; i < root_node->child_count(); ++i) {
244 const BookmarkNode* node = root_node->GetChild(i);
245 if (node->IsVisible() &&
246 std::find(nodes.begin(), nodes.end(), node) == nodes.end()) {
247 nodes.push_back(node);
248
249 if (nodes.size() == max_count)
250 break;
251 }
252 }
253 }
254 return nodes;
255 }
256
257 void GetMostRecentlyAddedEntries(BookmarkModel* model,
258 size_t count,
259 std::vector<const BookmarkNode*>* nodes) {
260 ui::TreeNodeIterator<const BookmarkNode> iterator(model->root_node());
261 while (iterator.has_next()) {
262 const BookmarkNode* node = iterator.Next();
263 if (node->is_url()) {
264 std::vector<const BookmarkNode*>::iterator insert_position =
265 std::upper_bound(nodes->begin(), nodes->end(), node,
266 &MoreRecentlyAdded);
267 if (nodes->size() < count || insert_position != nodes->end()) {
268 nodes->insert(insert_position, node);
269 while (nodes->size() > count)
270 nodes->pop_back();
271 }
272 }
273 }
274 }
275
276 bool MoreRecentlyAdded(const BookmarkNode* n1, const BookmarkNode* n2) {
277 return n1->date_added() > n2->date_added();
278 }
279
280 void GetBookmarksMatchingProperties(BookmarkModel* model,
281 const QueryFields& query,
282 size_t max_count,
283 const std::string& languages,
284 std::vector<const BookmarkNode*>* nodes) {
285 std::vector<base::string16> query_words;
286 query_parser::QueryParser parser;
287 if (query.word_phrase_query) {
288 parser.ParseQueryWords(base::i18n::ToLower(*query.word_phrase_query),
289 &query_words);
290 if (query_words.empty())
291 return;
292 }
293
294 ui::TreeNodeIterator<const BookmarkNode> iterator(model->root_node());
295 while (iterator.has_next()) {
296 const BookmarkNode* node = iterator.Next();
297 if ((!query_words.empty() &&
298 !DoesBookmarkContainWords(node, query_words, languages)) ||
299 model->is_permanent_node(node)) {
300 continue;
301 }
302 if (query.url) {
303 // Check against bare url spec and IDN-decoded url.
304 if (!node->is_url() ||
305 !(base::UTF8ToUTF16(node->url().spec()) == *query.url ||
306 net::FormatUrl(
307 node->url(), languages, net::kFormatUrlOmitNothing,
308 net::UnescapeRule::NORMAL, NULL, NULL, NULL) == *query.url)) {
309 continue;
310 }
311 }
312 if (query.title && node->GetTitle() != *query.title)
313 continue;
314
315 nodes->push_back(node);
316 if (nodes->size() == max_count)
317 return;
318 }
319 }
320
321 void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {
322 registry->RegisterBooleanPref(
323 prefs::kShowBookmarkBar,
324 false,
325 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
326 registry->RegisterBooleanPref(
327 prefs::kEditBookmarksEnabled,
328 true,
329 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
330 registry->RegisterBooleanPref(
331 prefs::kShowAppsShortcutInBookmarkBar,
332 true,
333 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
334 }
335
336 const BookmarkNode* GetParentForNewNodes(
337 const BookmarkNode* parent,
338 const std::vector<const BookmarkNode*>& selection,
339 int* index) {
340 const BookmarkNode* real_parent = parent;
341
342 if (selection.size() == 1 && selection[0]->is_folder())
343 real_parent = selection[0];
344
345 if (index) {
346 if (selection.size() == 1 && selection[0]->is_url()) {
347 *index = real_parent->GetIndexOf(selection[0]) + 1;
348 if (*index == 0) {
349 // Node doesn't exist in parent, add to end.
350 NOTREACHED();
351 *index = real_parent->child_count();
352 }
353 } else {
354 *index = real_parent->child_count();
355 }
356 }
357
358 return real_parent;
359 }
360
361 void DeleteBookmarkFolders(BookmarkModel* model,
362 const std::vector<int64>& ids) {
363 // Remove the folders that were removed. This has to be done after all the
364 // other changes have been committed.
365 for (std::vector<int64>::const_iterator iter = ids.begin();
366 iter != ids.end();
367 ++iter) {
368 const BookmarkNode* node = GetBookmarkNodeByID(model, *iter);
369 if (!node)
370 continue;
371 const BookmarkNode* parent = node->parent();
372 model->Remove(parent, parent->GetIndexOf(node));
373 }
374 }
375
376 void AddIfNotBookmarked(BookmarkModel* model,
377 const GURL& url,
378 const base::string16& title) {
379 std::vector<const BookmarkNode*> bookmarks;
380 model->GetNodesByURL(url, &bookmarks);
381 if (!bookmarks.empty())
382 return; // Nothing to do, a bookmark with that url already exists.
383
384 model->client()->RecordAction(base::UserMetricsAction("BookmarkAdded"));
385 const BookmarkNode* parent = model->GetParentForNewNodes();
386 model->AddURL(parent, parent->child_count(), title, url);
387 }
388
389 void RemoveAllBookmarks(BookmarkModel* model, const GURL& url) {
390 std::vector<const BookmarkNode*> bookmarks;
391 model->GetNodesByURL(url, &bookmarks);
392
393 // Remove all the bookmarks.
394 for (size_t i = 0; i < bookmarks.size(); ++i) {
395 const BookmarkNode* node = bookmarks[i];
396 int index = node->parent()->GetIndexOf(node);
397 if (index > -1)
398 model->Remove(node->parent(), index);
399 }
400 }
401
402 base::string16 CleanUpUrlForMatching(
403 const GURL& gurl,
404 const std::string& languages,
405 base::OffsetAdjuster::Adjustments* adjustments) {
406 base::OffsetAdjuster::Adjustments tmp_adjustments;
407 return base::i18n::ToLower(net::FormatUrlWithAdjustments(
408 GURL(TruncateUrl(gurl.spec())), languages,
409 net::kFormatUrlOmitUsernamePassword,
410 net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS,
411 NULL, NULL, adjustments ? adjustments : &tmp_adjustments));
412 }
413
414 base::string16 CleanUpTitleForMatching(const base::string16& title) {
415 return base::i18n::ToLower(title.substr(0u, kCleanedUpTitleMaxLength));
416 }
417
418 } // namespace bookmark_utils
419
420 const BookmarkNode* GetBookmarkNodeByID(const BookmarkModel* model, int64 id) {
421 // TODO(sky): TreeNode needs a method that visits all nodes using a predicate.
422 return GetNodeByID(model->root_node(), id);
423 }
OLDNEW
« no previous file with comments | « components/bookmarks/core/browser/bookmark_utils.h ('k') | components/bookmarks/core/browser/bookmark_utils_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698