NaCl: Update revision in DEPS, r12770 -> r12773
[chromium-blink-merge.git] / chrome / browser / bookmarks / bookmark_utils.cc
blob7cc9af4b2c80d457ae1aaacd36d6140c874b89c5
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/bookmarks/bookmark_utils.h"
7 #include <utility>
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/prefs/pref_service.h"
14 #include "base/strings/string16.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/time/time.h"
17 #include "chrome/browser/bookmarks/bookmark_model.h"
18 #include "chrome/browser/history/query_parser.h"
19 #include "chrome/browser/undo/bookmark_undo_service.h"
20 #include "chrome/browser/undo/bookmark_undo_service_factory.h"
21 #include "chrome/browser/undo/bookmark_undo_utils.h"
22 #include "chrome/common/pref_names.h"
23 #include "components/user_prefs/pref_registry_syncable.h"
24 #include "content/public/browser/user_metrics.h"
25 #include "net/base/net_util.h"
26 #include "ui/base/models/tree_node_iterator.h"
28 using base::Time;
30 namespace {
32 void CloneBookmarkNodeImpl(BookmarkModel* model,
33 const BookmarkNodeData::Element& element,
34 const BookmarkNode* parent,
35 int index_to_add_at,
36 bool reset_node_times) {
37 const BookmarkNode* cloned_node = NULL;
38 if (element.is_url) {
39 if (reset_node_times) {
40 cloned_node = model->AddURL(parent, index_to_add_at, element.title,
41 element.url);
42 } else {
43 DCHECK(!element.date_added.is_null());
44 cloned_node = model->AddURLWithCreationTime(parent, index_to_add_at,
45 element.title, element.url,
46 element.date_added);
48 } else {
49 cloned_node = model->AddFolder(parent, index_to_add_at, element.title);
50 if (!reset_node_times) {
51 DCHECK(!element.date_folder_modified.is_null());
52 model->SetDateFolderModified(cloned_node, element.date_folder_modified);
54 for (int i = 0; i < static_cast<int>(element.children.size()); ++i)
55 CloneBookmarkNodeImpl(model, element.children[i], cloned_node, i,
56 reset_node_times);
58 model->SetNodeMetaInfoMap(cloned_node, element.meta_info_map);
61 // Comparison function that compares based on date modified of the two nodes.
62 bool MoreRecentlyModified(const BookmarkNode* n1, const BookmarkNode* n2) {
63 return n1->date_folder_modified() > n2->date_folder_modified();
66 // Returns true if |text| contains each string in |words|. This is used when
67 // searching for bookmarks.
68 bool DoesBookmarkTextContainWords(const base::string16& text,
69 const std::vector<base::string16>& words) {
70 for (size_t i = 0; i < words.size(); ++i) {
71 if (!base::i18n::StringSearchIgnoringCaseAndAccents(
72 words[i], text, NULL, NULL)) {
73 return false;
76 return true;
79 // Returns true if |node|s title or url contains the strings in |words|.
80 // |languages| argument is user's accept-language setting to decode IDN.
81 bool DoesBookmarkContainWords(const BookmarkNode* node,
82 const std::vector<base::string16>& words,
83 const std::string& languages) {
84 return
85 DoesBookmarkTextContainWords(node->GetTitle(), words) ||
86 DoesBookmarkTextContainWords(
87 base::UTF8ToUTF16(node->url().spec()), words) ||
88 DoesBookmarkTextContainWords(net::FormatUrl(
89 node->url(), languages, net::kFormatUrlOmitNothing,
90 net::UnescapeRule::NORMAL, NULL, NULL, NULL), words);
93 // This is used with a tree iterator to skip subtrees which are not visible.
94 bool PruneInvisibleFolders(const BookmarkNode* node) {
95 return !node->IsVisible();
98 // This traces parents up to root, determines if node is contained in a
99 // selected folder.
100 bool HasSelectedAncestor(BookmarkModel* model,
101 const std::vector<const BookmarkNode*>& selectedNodes,
102 const BookmarkNode* node) {
103 if (!node || model->is_permanent_node(node))
104 return false;
106 for (size_t i = 0; i < selectedNodes.size(); ++i)
107 if (node->id() == selectedNodes[i]->id())
108 return true;
110 return HasSelectedAncestor(model, selectedNodes, node->parent());
113 } // namespace
115 namespace bookmark_utils {
117 QueryFields::QueryFields() {}
118 QueryFields::~QueryFields() {}
120 void CloneBookmarkNode(BookmarkModel* model,
121 const std::vector<BookmarkNodeData::Element>& elements,
122 const BookmarkNode* parent,
123 int index_to_add_at,
124 bool reset_node_times) {
125 if (!parent->is_folder() || !model) {
126 NOTREACHED();
127 return;
129 for (size_t i = 0; i < elements.size(); ++i) {
130 CloneBookmarkNodeImpl(model, elements[i], parent, index_to_add_at + i,
131 reset_node_times);
135 void CopyToClipboard(BookmarkModel* model,
136 const std::vector<const BookmarkNode*>& nodes,
137 bool remove_nodes) {
138 if (nodes.empty())
139 return;
141 // Create array of selected nodes with descendants filtered out.
142 std::vector<const BookmarkNode*> filteredNodes;
143 for (size_t i = 0; i < nodes.size(); ++i)
144 if (!HasSelectedAncestor(model, nodes, nodes[i]->parent()))
145 filteredNodes.push_back(nodes[i]);
147 BookmarkNodeData(filteredNodes).
148 WriteToClipboard(ui::CLIPBOARD_TYPE_COPY_PASTE);
150 if (remove_nodes) {
151 #if !defined(OS_ANDROID)
152 ScopedGroupBookmarkActions group_cut(model->profile());
153 #endif
154 for (size_t i = 0; i < filteredNodes.size(); ++i) {
155 int index = filteredNodes[i]->parent()->GetIndexOf(filteredNodes[i]);
156 if (index > -1)
157 model->Remove(filteredNodes[i]->parent(), index);
162 void PasteFromClipboard(BookmarkModel* model,
163 const BookmarkNode* parent,
164 int index) {
165 if (!parent)
166 return;
168 BookmarkNodeData bookmark_data;
169 if (!bookmark_data.ReadFromClipboard(ui::CLIPBOARD_TYPE_COPY_PASTE))
170 return;
172 if (index == -1)
173 index = parent->child_count();
174 #if !defined(OS_ANDROID)
175 ScopedGroupBookmarkActions group_paste(model->profile());
176 #endif
177 CloneBookmarkNode(model, bookmark_data.elements, parent, index, true);
180 bool CanPasteFromClipboard(const BookmarkNode* node) {
181 if (!node)
182 return false;
183 return BookmarkNodeData::ClipboardContainsBookmarks();
186 std::vector<const BookmarkNode*> GetMostRecentlyModifiedFolders(
187 BookmarkModel* model,
188 size_t max_count) {
189 std::vector<const BookmarkNode*> nodes;
190 ui::TreeNodeIterator<const BookmarkNode> iterator(model->root_node(),
191 PruneInvisibleFolders);
193 while (iterator.has_next()) {
194 const BookmarkNode* parent = iterator.Next();
195 if (parent->is_folder() && parent->date_folder_modified() > base::Time()) {
196 if (max_count == 0) {
197 nodes.push_back(parent);
198 } else {
199 std::vector<const BookmarkNode*>::iterator i =
200 std::upper_bound(nodes.begin(), nodes.end(), parent,
201 &MoreRecentlyModified);
202 if (nodes.size() < max_count || i != nodes.end()) {
203 nodes.insert(i, parent);
204 while (nodes.size() > max_count)
205 nodes.pop_back();
208 } // else case, the root node, which we don't care about or imported nodes
209 // (which have a time of 0).
212 if (nodes.size() < max_count) {
213 // Add the permanent nodes if there is space. The permanent nodes are the
214 // only children of the root_node.
215 const BookmarkNode* root_node = model->root_node();
217 for (int i = 0; i < root_node->child_count(); ++i) {
218 const BookmarkNode* node = root_node->GetChild(i);
219 if (node->IsVisible() &&
220 std::find(nodes.begin(), nodes.end(), node) == nodes.end()) {
221 nodes.push_back(node);
223 if (nodes.size() == max_count)
224 break;
228 return nodes;
231 void GetMostRecentlyAddedEntries(BookmarkModel* model,
232 size_t count,
233 std::vector<const BookmarkNode*>* nodes) {
234 ui::TreeNodeIterator<const BookmarkNode> iterator(model->root_node());
235 while (iterator.has_next()) {
236 const BookmarkNode* node = iterator.Next();
237 if (node->is_url()) {
238 std::vector<const BookmarkNode*>::iterator insert_position =
239 std::upper_bound(nodes->begin(), nodes->end(), node,
240 &MoreRecentlyAdded);
241 if (nodes->size() < count || insert_position != nodes->end()) {
242 nodes->insert(insert_position, node);
243 while (nodes->size() > count)
244 nodes->pop_back();
250 bool MoreRecentlyAdded(const BookmarkNode* n1, const BookmarkNode* n2) {
251 return n1->date_added() > n2->date_added();
254 void GetBookmarksMatchingProperties(BookmarkModel* model,
255 const QueryFields& query,
256 size_t max_count,
257 const std::string& languages,
258 std::vector<const BookmarkNode*>* nodes) {
259 std::vector<base::string16> query_words;
260 QueryParser parser;
261 if (query.word_phrase_query) {
262 parser.ParseQueryWords(base::i18n::ToLower(*query.word_phrase_query),
263 &query_words);
264 if (query_words.empty())
265 return;
268 ui::TreeNodeIterator<const BookmarkNode> iterator(model->root_node());
269 while (iterator.has_next()) {
270 const BookmarkNode* node = iterator.Next();
271 if ((!query_words.empty() &&
272 !DoesBookmarkContainWords(node, query_words, languages)) ||
273 model->is_permanent_node(node)) {
274 continue;
276 if (query.url) {
277 // Check against bare url spec and IDN-decoded url.
278 if (!node->is_url() ||
279 !(base::UTF8ToUTF16(node->url().spec()) == *query.url ||
280 net::FormatUrl(
281 node->url(), languages, net::kFormatUrlOmitNothing,
282 net::UnescapeRule::NORMAL, NULL, NULL, NULL) == *query.url)) {
283 continue;
286 if (query.title && node->GetTitle() != *query.title)
287 continue;
289 nodes->push_back(node);
290 if (nodes->size() == max_count)
291 return;
295 void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {
296 registry->RegisterBooleanPref(
297 prefs::kShowBookmarkBar,
298 false,
299 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
300 registry->RegisterBooleanPref(
301 prefs::kEditBookmarksEnabled,
302 true,
303 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
304 registry->RegisterBooleanPref(
305 prefs::kShowAppsShortcutInBookmarkBar,
306 true,
307 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
310 const BookmarkNode* GetParentForNewNodes(
311 const BookmarkNode* parent,
312 const std::vector<const BookmarkNode*>& selection,
313 int* index) {
314 const BookmarkNode* real_parent = parent;
316 if (selection.size() == 1 && selection[0]->is_folder())
317 real_parent = selection[0];
319 if (index) {
320 if (selection.size() == 1 && selection[0]->is_url()) {
321 *index = real_parent->GetIndexOf(selection[0]) + 1;
322 if (*index == 0) {
323 // Node doesn't exist in parent, add to end.
324 NOTREACHED();
325 *index = real_parent->child_count();
327 } else {
328 *index = real_parent->child_count();
332 return real_parent;
335 void DeleteBookmarkFolders(BookmarkModel* model,
336 const std::vector<int64>& ids) {
337 // Remove the folders that were removed. This has to be done after all the
338 // other changes have been committed.
339 for (std::vector<int64>::const_iterator iter = ids.begin();
340 iter != ids.end();
341 ++iter) {
342 const BookmarkNode* node = model->GetNodeByID(*iter);
343 if (!node)
344 continue;
345 const BookmarkNode* parent = node->parent();
346 model->Remove(parent, parent->GetIndexOf(node));
350 void AddIfNotBookmarked(BookmarkModel* model,
351 const GURL& url,
352 const base::string16& title) {
353 std::vector<const BookmarkNode*> bookmarks;
354 model->GetNodesByURL(url, &bookmarks);
355 if (!bookmarks.empty())
356 return; // Nothing to do, a bookmark with that url already exists.
358 content::RecordAction(base::UserMetricsAction("BookmarkAdded"));
359 const BookmarkNode* parent = model->GetParentForNewNodes();
360 model->AddURL(parent, parent->child_count(), title, url);
363 void RemoveAllBookmarks(BookmarkModel* model, const GURL& url) {
364 std::vector<const BookmarkNode*> bookmarks;
365 model->GetNodesByURL(url, &bookmarks);
367 // Remove all the bookmarks.
368 for (size_t i = 0; i < bookmarks.size(); ++i) {
369 const BookmarkNode* node = bookmarks[i];
370 int index = node->parent()->GetIndexOf(node);
371 if (index > -1)
372 model->Remove(node->parent(), index);
376 } // namespace bookmark_utils