Stack sampling profiler: add fire-and-forget interface
[chromium-blink-merge.git] / components / bookmarks / browser / bookmark_utils.cc
bloba815d1c5c9141d0f99c53a18773239106a371218
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.
5 #include "components/bookmarks/browser/bookmark_utils.h"
7 #include <stdint.h>
8 #include <utility>
10 #include "base/bind.h"
11 #include "base/containers/hash_tables.h"
12 #include "base/files/file_path.h"
13 #include "base/i18n/case_conversion.h"
14 #include "base/i18n/string_search.h"
15 #include "base/macros.h"
16 #include "base/metrics/user_metrics_action.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/time/time.h"
22 #include "components/bookmarks/browser/bookmark_client.h"
23 #include "components/bookmarks/browser/bookmark_model.h"
24 #include "components/bookmarks/browser/scoped_group_bookmark_actions.h"
25 #include "components/bookmarks/common/bookmark_pref_names.h"
26 #include "components/pref_registry/pref_registry_syncable.h"
27 #include "components/query_parser/query_parser.h"
28 #include "net/base/net_util.h"
29 #include "ui/base/clipboard/clipboard.h"
30 #include "ui/base/models/tree_node_iterator.h"
31 #include "url/gurl.h"
33 using base::Time;
35 namespace bookmarks {
37 namespace {
39 // The maximum length of URL or title returned by the Cleanup functions.
40 const size_t kCleanedUpUrlMaxLength = 1024u;
41 const size_t kCleanedUpTitleMaxLength = 1024u;
43 void CloneBookmarkNodeImpl(BookmarkModel* model,
44 const BookmarkNodeData::Element& element,
45 const BookmarkNode* parent,
46 int index_to_add_at,
47 bool reset_node_times) {
48 // Make sure to not copy non clonable keys.
49 BookmarkNode::MetaInfoMap meta_info_map = element.meta_info_map;
50 for (const std::string& key : model->non_cloned_keys())
51 meta_info_map.erase(key);
53 if (element.is_url) {
54 Time date_added = reset_node_times ? Time::Now() : element.date_added;
55 DCHECK(!date_added.is_null());
57 model->AddURLWithCreationTimeAndMetaInfo(parent,
58 index_to_add_at,
59 element.title,
60 element.url,
61 date_added,
62 &meta_info_map);
63 } else {
64 const BookmarkNode* cloned_node = model->AddFolderWithMetaInfo(
65 parent, index_to_add_at, element.title, &meta_info_map);
66 if (!reset_node_times) {
67 DCHECK(!element.date_folder_modified.is_null());
68 model->SetDateFolderModified(cloned_node, element.date_folder_modified);
70 for (int i = 0; i < static_cast<int>(element.children.size()); ++i)
71 CloneBookmarkNodeImpl(model, element.children[i], cloned_node, i,
72 reset_node_times);
76 // Comparison function that compares based on date modified of the two nodes.
77 bool MoreRecentlyModified(const BookmarkNode* n1, const BookmarkNode* n2) {
78 return n1->date_folder_modified() > n2->date_folder_modified();
81 // Returns true if |text| contains each string in |words|. This is used when
82 // searching for bookmarks.
83 bool DoesBookmarkTextContainWords(const base::string16& text,
84 const std::vector<base::string16>& words) {
85 for (size_t i = 0; i < words.size(); ++i) {
86 if (!base::i18n::StringSearchIgnoringCaseAndAccents(
87 words[i], text, NULL, NULL)) {
88 return false;
91 return true;
94 // Returns true if |node|s title or url contains the strings in |words|.
95 // |languages| argument is user's accept-language setting to decode IDN.
96 bool DoesBookmarkContainWords(const BookmarkNode* node,
97 const std::vector<base::string16>& words,
98 const std::string& languages) {
99 return
100 DoesBookmarkTextContainWords(node->GetTitle(), words) ||
101 DoesBookmarkTextContainWords(
102 base::UTF8ToUTF16(node->url().spec()), words) ||
103 DoesBookmarkTextContainWords(net::FormatUrl(
104 node->url(), languages, net::kFormatUrlOmitNothing,
105 net::UnescapeRule::NORMAL, NULL, NULL, NULL), words);
108 // This is used with a tree iterator to skip subtrees which are not visible.
109 bool PruneInvisibleFolders(const BookmarkNode* node) {
110 return !node->IsVisible();
113 // This traces parents up to root, determines if node is contained in a
114 // selected folder.
115 bool HasSelectedAncestor(BookmarkModel* model,
116 const std::vector<const BookmarkNode*>& selected_nodes,
117 const BookmarkNode* node) {
118 if (!node || model->is_permanent_node(node))
119 return false;
121 for (size_t i = 0; i < selected_nodes.size(); ++i)
122 if (node->id() == selected_nodes[i]->id())
123 return true;
125 return HasSelectedAncestor(model, selected_nodes, node->parent());
128 const BookmarkNode* GetNodeByID(const BookmarkNode* node, int64_t id) {
129 if (node->id() == id)
130 return node;
132 for (int i = 0, child_count = node->child_count(); i < child_count; ++i) {
133 const BookmarkNode* result = GetNodeByID(node->GetChild(i), id);
134 if (result)
135 return result;
137 return NULL;
140 // Attempts to shorten a URL safely (i.e., by preventing the end of the URL
141 // from being in the middle of an escape sequence) to no more than
142 // kCleanedUpUrlMaxLength characters, returning the result.
143 std::string TruncateUrl(const std::string& url) {
144 if (url.length() <= kCleanedUpUrlMaxLength)
145 return url;
147 // If we're in the middle of an escape sequence, truncate just before it.
148 if (url[kCleanedUpUrlMaxLength - 1] == '%')
149 return url.substr(0, kCleanedUpUrlMaxLength - 1);
150 if (url[kCleanedUpUrlMaxLength - 2] == '%')
151 return url.substr(0, kCleanedUpUrlMaxLength - 2);
153 return url.substr(0, kCleanedUpUrlMaxLength);
156 // Returns the URL from the clipboard. If there is no URL an empty URL is
157 // returned.
158 GURL GetUrlFromClipboard() {
159 base::string16 url_text;
160 #if !defined(OS_IOS)
161 ui::Clipboard::GetForCurrentThread()->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE,
162 &url_text);
163 #endif
164 return GURL(url_text);
167 class VectorIterator {
168 public:
169 explicit VectorIterator(std::vector<const BookmarkNode*>* nodes)
170 : nodes_(nodes), current_(nodes->begin()) {}
171 bool has_next() { return (current_ != nodes_->end()); }
172 const BookmarkNode* Next() {
173 const BookmarkNode* result = *current_;
174 ++current_;
175 return result;
178 private:
179 std::vector<const BookmarkNode*>* nodes_;
180 std::vector<const BookmarkNode*>::iterator current_;
182 DISALLOW_COPY_AND_ASSIGN(VectorIterator);
185 template <class type>
186 void GetBookmarksMatchingPropertiesImpl(
187 type& iterator,
188 BookmarkModel* model,
189 const QueryFields& query,
190 const std::vector<base::string16>& query_words,
191 size_t max_count,
192 const std::string& languages,
193 std::vector<const BookmarkNode*>* nodes) {
194 while (iterator.has_next()) {
195 const BookmarkNode* node = iterator.Next();
196 if ((!query_words.empty() &&
197 !DoesBookmarkContainWords(node, query_words, languages)) ||
198 model->is_permanent_node(node)) {
199 continue;
201 if (query.title && node->GetTitle() != *query.title)
202 continue;
204 nodes->push_back(node);
205 if (nodes->size() == max_count)
206 return;
210 } // namespace
212 QueryFields::QueryFields() {}
213 QueryFields::~QueryFields() {}
215 void CloneBookmarkNode(BookmarkModel* model,
216 const std::vector<BookmarkNodeData::Element>& elements,
217 const BookmarkNode* parent,
218 int index_to_add_at,
219 bool reset_node_times) {
220 if (!parent->is_folder() || !model) {
221 NOTREACHED();
222 return;
224 for (size_t i = 0; i < elements.size(); ++i) {
225 CloneBookmarkNodeImpl(model, elements[i], parent,
226 index_to_add_at + static_cast<int>(i),
227 reset_node_times);
231 void CopyToClipboard(BookmarkModel* model,
232 const std::vector<const BookmarkNode*>& nodes,
233 bool remove_nodes) {
234 if (nodes.empty())
235 return;
237 // Create array of selected nodes with descendants filtered out.
238 std::vector<const BookmarkNode*> filtered_nodes;
239 for (size_t i = 0; i < nodes.size(); ++i)
240 if (!HasSelectedAncestor(model, nodes, nodes[i]->parent()))
241 filtered_nodes.push_back(nodes[i]);
243 BookmarkNodeData(filtered_nodes).
244 WriteToClipboard(ui::CLIPBOARD_TYPE_COPY_PASTE);
246 if (remove_nodes) {
247 ScopedGroupBookmarkActions group_cut(model);
248 for (size_t i = 0; i < filtered_nodes.size(); ++i) {
249 int index = filtered_nodes[i]->parent()->GetIndexOf(filtered_nodes[i]);
250 if (index > -1)
251 model->Remove(filtered_nodes[i]);
256 // Updates |title| such that |url| and |title| pair are unique among the
257 // children of |parent|.
258 void MakeTitleUnique(const BookmarkModel* model,
259 const BookmarkNode* parent,
260 const GURL& url,
261 base::string16* title) {
262 base::hash_set<base::string16> titles;
263 base::string16 original_title_lower = base::i18n::ToLower(*title);
264 for (int i = 0; i < parent->child_count(); i++) {
265 const BookmarkNode* node = parent->GetChild(i);
266 if (node->is_url() && (url == node->url()) &&
267 base::StartsWith(base::i18n::ToLower(node->GetTitle()),
268 original_title_lower,
269 base::CompareCase::SENSITIVE)) {
270 titles.insert(node->GetTitle());
274 if (titles.find(*title) == titles.end())
275 return;
277 for (size_t i = 0; i < titles.size(); i++) {
278 const base::string16 new_title(*title +
279 base::ASCIIToUTF16(base::StringPrintf(
280 " (%lu)", (unsigned long)(i + 1))));
281 if (titles.find(new_title) == titles.end()) {
282 *title = new_title;
283 return;
286 NOTREACHED();
289 void PasteFromClipboard(BookmarkModel* model,
290 const BookmarkNode* parent,
291 int index) {
292 if (!parent)
293 return;
295 BookmarkNodeData bookmark_data;
296 if (!bookmark_data.ReadFromClipboard(ui::CLIPBOARD_TYPE_COPY_PASTE)) {
297 GURL url = GetUrlFromClipboard();
298 if (!url.is_valid())
299 return;
300 BookmarkNode node(url);
301 node.SetTitle(base::ASCIIToUTF16(url.spec()));
302 bookmark_data = BookmarkNodeData(&node);
304 if (index == -1)
305 index = parent->child_count();
306 ScopedGroupBookmarkActions group_paste(model);
308 if (bookmark_data.size() == 1 &&
309 model->IsBookmarked(bookmark_data.elements[0].url)) {
310 MakeTitleUnique(model,
311 parent,
312 bookmark_data.elements[0].url,
313 &bookmark_data.elements[0].title);
316 CloneBookmarkNode(model, bookmark_data.elements, parent, index, true);
319 bool CanPasteFromClipboard(BookmarkModel* model, const BookmarkNode* node) {
320 if (!node || !model->client()->CanBeEditedByUser(node))
321 return false;
322 return (BookmarkNodeData::ClipboardContainsBookmarks() ||
323 GetUrlFromClipboard().is_valid());
326 std::vector<const BookmarkNode*> GetMostRecentlyModifiedUserFolders(
327 BookmarkModel* model,
328 size_t max_count) {
329 std::vector<const BookmarkNode*> nodes;
330 ui::TreeNodeIterator<const BookmarkNode> iterator(
331 model->root_node(), base::Bind(&PruneInvisibleFolders));
333 while (iterator.has_next()) {
334 const BookmarkNode* parent = iterator.Next();
335 if (!model->client()->CanBeEditedByUser(parent))
336 continue;
337 if (parent->is_folder() && parent->date_folder_modified() > Time()) {
338 if (max_count == 0) {
339 nodes.push_back(parent);
340 } else {
341 std::vector<const BookmarkNode*>::iterator i =
342 std::upper_bound(nodes.begin(), nodes.end(), parent,
343 &MoreRecentlyModified);
344 if (nodes.size() < max_count || i != nodes.end()) {
345 nodes.insert(i, parent);
346 while (nodes.size() > max_count)
347 nodes.pop_back();
350 } // else case, the root node, which we don't care about or imported nodes
351 // (which have a time of 0).
354 if (nodes.size() < max_count) {
355 // Add the permanent nodes if there is space. The permanent nodes are the
356 // only children of the root_node.
357 const BookmarkNode* root_node = model->root_node();
359 for (int i = 0; i < root_node->child_count(); ++i) {
360 const BookmarkNode* node = root_node->GetChild(i);
361 if (node->IsVisible() && model->client()->CanBeEditedByUser(node) &&
362 std::find(nodes.begin(), nodes.end(), node) == nodes.end()) {
363 nodes.push_back(node);
365 if (nodes.size() == max_count)
366 break;
370 return nodes;
373 void GetMostRecentlyAddedEntries(BookmarkModel* model,
374 size_t count,
375 std::vector<const BookmarkNode*>* nodes) {
376 ui::TreeNodeIterator<const BookmarkNode> iterator(model->root_node());
377 while (iterator.has_next()) {
378 const BookmarkNode* node = iterator.Next();
379 if (node->is_url()) {
380 std::vector<const BookmarkNode*>::iterator insert_position =
381 std::upper_bound(nodes->begin(), nodes->end(), node,
382 &MoreRecentlyAdded);
383 if (nodes->size() < count || insert_position != nodes->end()) {
384 nodes->insert(insert_position, node);
385 while (nodes->size() > count)
386 nodes->pop_back();
392 bool MoreRecentlyAdded(const BookmarkNode* n1, const BookmarkNode* n2) {
393 return n1->date_added() > n2->date_added();
396 void GetBookmarksMatchingProperties(BookmarkModel* model,
397 const QueryFields& query,
398 size_t max_count,
399 const std::string& languages,
400 std::vector<const BookmarkNode*>* nodes) {
401 std::vector<base::string16> query_words;
402 query_parser::QueryParser parser;
403 if (query.word_phrase_query) {
404 parser.ParseQueryWords(base::i18n::ToLower(*query.word_phrase_query),
405 query_parser::MatchingAlgorithm::DEFAULT,
406 &query_words);
407 if (query_words.empty())
408 return;
411 if (query.url) {
412 // Shortcut into the BookmarkModel if searching for URL.
413 GURL url(*query.url);
414 std::vector<const BookmarkNode*> url_matched_nodes;
415 if (url.is_valid())
416 model->GetNodesByURL(url, &url_matched_nodes);
417 bookmarks::VectorIterator iterator(&url_matched_nodes);
418 GetBookmarksMatchingPropertiesImpl<bookmarks::VectorIterator>(
419 iterator, model, query, query_words, max_count, languages, nodes);
420 } else {
421 ui::TreeNodeIterator<const BookmarkNode> iterator(model->root_node());
422 GetBookmarksMatchingPropertiesImpl<
423 ui::TreeNodeIterator<const BookmarkNode>>(
424 iterator, model, query, query_words, max_count, languages, nodes);
428 void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {
429 registry->RegisterBooleanPref(
430 prefs::kShowBookmarkBar,
431 false,
432 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
433 registry->RegisterBooleanPref(prefs::kEditBookmarksEnabled, true);
434 registry->RegisterBooleanPref(
435 prefs::kShowAppsShortcutInBookmarkBar,
436 true,
437 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
438 registry->RegisterBooleanPref(
439 prefs::kShowManagedBookmarksInBookmarkBar,
440 true,
441 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
442 // Don't sync this, as otherwise, due to a limitation in sync, it
443 // will cause a deadlock (see http://crbug.com/97955). If we truly
444 // want to sync the expanded state of folders, it should be part of
445 // bookmark sync itself (i.e., a property of the sync folder nodes).
446 registry->RegisterListPref(prefs::kBookmarkEditorExpandedNodes,
447 new base::ListValue);
448 registry->RegisterListPref(prefs::kManagedBookmarks);
449 registry->RegisterListPref(prefs::kSupervisedBookmarks);
452 const BookmarkNode* GetParentForNewNodes(
453 const BookmarkNode* parent,
454 const std::vector<const BookmarkNode*>& selection,
455 int* index) {
456 const BookmarkNode* real_parent = parent;
458 if (selection.size() == 1 && selection[0]->is_folder())
459 real_parent = selection[0];
461 if (index) {
462 if (selection.size() == 1 && selection[0]->is_url()) {
463 *index = real_parent->GetIndexOf(selection[0]) + 1;
464 if (*index == 0) {
465 // Node doesn't exist in parent, add to end.
466 NOTREACHED();
467 *index = real_parent->child_count();
469 } else {
470 *index = real_parent->child_count();
474 return real_parent;
477 void DeleteBookmarkFolders(BookmarkModel* model,
478 const std::vector<int64_t>& ids) {
479 // Remove the folders that were removed. This has to be done after all the
480 // other changes have been committed.
481 for (std::vector<int64_t>::const_iterator iter = ids.begin();
482 iter != ids.end();
483 ++iter) {
484 const BookmarkNode* node = GetBookmarkNodeByID(model, *iter);
485 if (!node)
486 continue;
487 model->Remove(node);
491 void AddIfNotBookmarked(BookmarkModel* model,
492 const GURL& url,
493 const base::string16& title) {
494 if (IsBookmarkedByUser(model, url))
495 return; // Nothing to do, a user bookmark with that url already exists.
496 model->client()->RecordAction(base::UserMetricsAction("BookmarkAdded"));
497 const BookmarkNode* parent = model->GetParentForNewNodes();
498 model->AddURL(parent, parent->child_count(), title, url);
501 void RemoveAllBookmarks(BookmarkModel* model, const GURL& url) {
502 std::vector<const BookmarkNode*> bookmarks;
503 model->GetNodesByURL(url, &bookmarks);
505 // Remove all the user bookmarks.
506 for (size_t i = 0; i < bookmarks.size(); ++i) {
507 const BookmarkNode* node = bookmarks[i];
508 int index = node->parent()->GetIndexOf(node);
509 if (index > -1 && model->client()->CanBeEditedByUser(node))
510 model->Remove(node);
514 base::string16 CleanUpUrlForMatching(
515 const GURL& gurl,
516 const std::string& languages,
517 base::OffsetAdjuster::Adjustments* adjustments) {
518 base::OffsetAdjuster::Adjustments tmp_adjustments;
519 return base::i18n::ToLower(net::FormatUrlWithAdjustments(
520 GURL(TruncateUrl(gurl.spec())), languages,
521 net::kFormatUrlOmitUsernamePassword,
522 net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS,
523 NULL, NULL, adjustments ? adjustments : &tmp_adjustments));
526 base::string16 CleanUpTitleForMatching(const base::string16& title) {
527 return base::i18n::ToLower(title.substr(0u, kCleanedUpTitleMaxLength));
530 bool CanAllBeEditedByUser(BookmarkClient* client,
531 const std::vector<const BookmarkNode*>& nodes) {
532 for (size_t i = 0; i < nodes.size(); ++i) {
533 if (!client->CanBeEditedByUser(nodes[i]))
534 return false;
536 return true;
539 bool IsBookmarkedByUser(BookmarkModel* model, const GURL& url) {
540 std::vector<const BookmarkNode*> nodes;
541 model->GetNodesByURL(url, &nodes);
542 for (size_t i = 0; i < nodes.size(); ++i) {
543 if (model->client()->CanBeEditedByUser(nodes[i]))
544 return true;
546 return false;
549 const BookmarkNode* GetBookmarkNodeByID(const BookmarkModel* model,
550 int64_t id) {
551 // TODO(sky): TreeNode needs a method that visits all nodes using a predicate.
552 return GetNodeByID(model->root_node(), id);
555 bool IsDescendantOf(const BookmarkNode* node, const BookmarkNode* root) {
556 return node && node->HasAncestor(root);
559 bool HasDescendantsOf(const std::vector<const BookmarkNode*>& list,
560 const BookmarkNode* root) {
561 for (const BookmarkNode* node : list) {
562 if (IsDescendantOf(node, root))
563 return true;
565 return false;
568 } // namespace bookmarks