1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
|
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/bookmarks/browser/bookmark_utils.h"
#include <stdint.h>
#include <algorithm>
#include <array>
#include <memory>
#include <unordered_set>
#include <utility>
#include "base/containers/contains.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/i18n/case_conversion.h"
#include "base/i18n/string_search.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/user_metrics.h"
#include "base/metrics/user_metrics_action.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/uuid.h"
#include "build/build_config.h"
#include "components/bookmarks/browser/bookmark_client.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/browser/bookmark_node.h"
#include "components/bookmarks/browser/scoped_group_bookmark_actions.h"
#include "components/bookmarks/common/bookmark_pref_names.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
#include "components/query_parser/query_parser.h"
#include "components/url_formatter/url_formatter.h"
#include "ui/base/models/tree_node_iterator.h"
#include "url/gurl.h"
using base::Time;
namespace bookmarks {
namespace {
void CloneBookmarkNodeImpl(BookmarkModel* model,
const BookmarkNodeData::Element& element,
const BookmarkNode* parent,
size_t index_to_add_at,
bool reset_node_times) {
// Make sure to not copy non clonable keys.
BookmarkNode::MetaInfoMap meta_info_map = element.meta_info_map;
if (element.is_url) {
Time date_added = reset_node_times ? Time::Now() : element.date_added;
DCHECK(!date_added.is_null());
const BookmarkNode* node = model->AddURL(
parent, index_to_add_at, element.title, element.url, &meta_info_map);
model->SetDateAdded(node, date_added);
} else {
const BookmarkNode* cloned_node = model->AddFolder(
parent, index_to_add_at, element.title, &meta_info_map);
if (!reset_node_times) {
DCHECK(!element.date_folder_modified.is_null());
model->SetDateFolderModified(cloned_node, element.date_folder_modified);
}
for (int i = 0; i < static_cast<int>(element.children.size()); ++i) {
CloneBookmarkNodeImpl(model, element.children[i], cloned_node, i,
reset_node_times);
}
}
}
// Returns true if `text` contains each string in `words`. This is used when
// searching for bookmarks.
bool DoesBookmarkTextContainWords(const std::u16string& text,
const std::vector<std::u16string>& words) {
for (size_t i = 0; i < words.size(); ++i) {
if (!base::i18n::StringSearchIgnoringCaseAndAccents(words[i], text, nullptr,
nullptr)) {
return false;
}
}
return true;
}
// Recursively searches for a node satisfying the functor `pred` . Returns
// nullptr if not found.
template <typename Predicate>
const BookmarkNode* FindNode(const BookmarkNode* node, Predicate pred) {
if (pred(node)) {
return node;
}
for (const auto& child : node->children()) {
const BookmarkNode* result = FindNode(child.get(), pred);
if (result) {
return result;
}
}
return nullptr;
}
template <class type>
std::vector<const BookmarkNode*> GetBookmarksMatchingPropertiesImpl(
type& iterator,
BookmarkModel* model,
const QueryFields& query,
const std::vector<std::u16string>& query_words,
size_t max_count) {
std::vector<const BookmarkNode*> nodes;
while (iterator.has_next()) {
const BookmarkNode* node = iterator.Next();
if ((!query_words.empty() &&
!DoesBookmarkContainWords(node->GetTitle(), node->url(),
query_words)) ||
model->is_permanent_node(node)) {
continue;
}
if (query.title && node->GetTitle() != *query.title) {
continue;
}
nodes.push_back(node);
if (nodes.size() == max_count) {
break;
}
}
return nodes;
}
template <class Comparator>
void GetMostRecentEntries(
BookmarkModel* model,
size_t limit,
std::multiset<const BookmarkNode*, Comparator>* nodes_set) {
ui::TreeNodeIterator<const BookmarkNode> iterator(model->root_node());
while (iterator.has_next()) {
const BookmarkNode* node = iterator.Next();
if (node->is_url()) {
nodes_set->insert(node);
if (nodes_set->size() > limit) {
nodes_set->erase(std::next(nodes_set->begin(), limit),
nodes_set->end());
}
}
}
}
} // namespace
QueryFields::QueryFields() = default;
QueryFields::~QueryFields() = default;
VectorIterator::VectorIterator(
std::vector<raw_ptr<const BookmarkNode, VectorExperimental>>* nodes)
: nodes_(nodes), current_(nodes->begin()) {}
VectorIterator::~VectorIterator() = default;
bool VectorIterator::has_next() {
return (current_ != nodes_->end());
}
const BookmarkNode* VectorIterator::Next() {
const BookmarkNode* result = *current_;
++current_;
return result;
}
void CloneBookmarkNode(BookmarkModel* model,
const std::vector<BookmarkNodeData::Element>& elements,
const BookmarkNode* parent,
size_t index_to_add_at,
bool reset_node_times) {
if (!parent->is_folder() || !model) {
NOTREACHED();
}
for (size_t i = 0; i < elements.size(); ++i) {
CloneBookmarkNodeImpl(model, elements[i], parent, index_to_add_at + i,
reset_node_times);
}
metrics::RecordCloneBookmarkNode(elements.size());
}
std::vector<const BookmarkNode*> GetMostRecentlyModifiedUserFolders(
BookmarkModel* model) {
std::vector<const BookmarkNode*> nodes;
ui::TreeNodeIterator<const BookmarkNode> iterator(
model->root_node(), base::BindRepeating(&PruneFoldersForDisplay, model));
while (iterator.has_next()) {
nodes.push_back(iterator.Next());
}
const std::array<const BookmarkNode*, 3>
account_permanent_nodes_possibly_null = {
model->account_mobile_node(), model->account_bookmark_bar_node(),
model->account_other_node()};
const BookmarkNode* default_node =
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
model->account_mobile_node() ? model->account_mobile_node()
: model->mobile_node();
#else // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS).
model->account_other_node() ? model->account_other_node()
: model->other_node();
#endif // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
auto more_recently_modified = [account_permanent_nodes_possibly_null,
default_node](const BookmarkNode* n1,
const BookmarkNode* n2) {
base::Time t1 = base::Contains(account_permanent_nodes_possibly_null, n1)
? std::max(n1->date_folder_modified(), n1->date_added())
: n1->date_folder_modified();
base::Time t2 = base::Contains(account_permanent_nodes_possibly_null, n2)
? std::max(n2->date_folder_modified(), n2->date_added())
: n2->date_folder_modified();
// If no node has been modified more recently, choose a default folder.
return t1 == t2 ? (n1 == default_node || n2 != default_node) : (t1 > t2);
};
std::ranges::stable_sort(nodes, more_recently_modified);
return nodes;
}
#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
BookmarkNodesSplitByAccountAndLocal::BookmarkNodesSplitByAccountAndLocal() =
default;
BookmarkNodesSplitByAccountAndLocal::BookmarkNodesSplitByAccountAndLocal(
const BookmarkNodesSplitByAccountAndLocal&) = default;
BookmarkNodesSplitByAccountAndLocal&
BookmarkNodesSplitByAccountAndLocal::operator=(
const BookmarkNodesSplitByAccountAndLocal&) = default;
BookmarkNodesSplitByAccountAndLocal::~BookmarkNodesSplitByAccountAndLocal() =
default;
BookmarkNodesSplitByAccountAndLocal GetMostRecentlyUsedFoldersForDisplay(
BookmarkModel* model,
const BookmarkNode* displayed_node) {
// `displayed_node` is meant to be a bookmark. Code below is not tested for
// folders.
CHECK(!displayed_node->is_folder());
// Max number of most recently used non-permanent-node folders.
static constexpr size_t kMaxMRUFolders = 5;
std::vector<const BookmarkNode*> mru_nodes =
bookmarks::GetMostRecentlyModifiedUserFolders(model);
const BookmarkNode* const most_recent_node =
mru_nodes.empty() ? nullptr : mru_nodes[0];
// Special case the parent item, it'll either remain first or filtered out as
// a permanent node and added back later.
std::erase(mru_nodes, displayed_node->parent()); // No-op if not present.
mru_nodes.insert(mru_nodes.begin(), displayed_node->parent());
// Remove permanent nodes, they'll be re-added at the end if used later.
std::erase_if(mru_nodes, [](const BookmarkNode* mru_node) {
return mru_node->is_permanent_node();
});
// Figure out which permanent nodes to add.
const bool account_nodes_exist =
model->account_bookmark_bar_node() != nullptr;
const std::vector<const BookmarkNode*> account_permanent_nodes(
{model->account_bookmark_bar_node(), model->account_other_node(),
model->account_mobile_node()});
const std::vector<const BookmarkNode*> local_permanent_nodes(
{model->bookmark_bar_node(), model->other_node(), model->mobile_node()});
std::vector<const BookmarkNode*> permanent_nodes_included;
for (const BookmarkNode* permanent_node :
account_nodes_exist ? account_permanent_nodes : local_permanent_nodes) {
if (!permanent_node->IsVisible()) {
continue;
}
permanent_nodes_included.push_back(permanent_node);
}
if (account_nodes_exist) {
// Add back the most recent node and the parent node if either of them are
// local permanent nodes. Permanent account nodes are preferred.
auto append_if_permanent_local_node = [model, &permanent_nodes_included](
const BookmarkNode* mru_node) {
if (mru_node->is_permanent_node() && model->IsLocalOnlyNode(*mru_node)) {
permanent_nodes_included.push_back(mru_node);
}
};
if (most_recent_node) {
append_if_permanent_local_node(most_recent_node);
}
if (displayed_node->parent() != most_recent_node) {
append_if_permanent_local_node(displayed_node->parent());
}
}
// Cap total number of non-permanent nodes to kMaxMRUFolders.
mru_nodes.resize(std::min(mru_nodes.size(), kMaxMRUFolders));
// Add permanent nodes at the end (note that these lists are both sorted and
// will remain sorted (permanent last) when split them up below.
mru_nodes.insert(mru_nodes.end(), permanent_nodes_included.begin(),
permanent_nodes_included.end());
// Split between account and local nodes if there are account nodes.
BookmarkNodesSplitByAccountAndLocal result;
if (account_nodes_exist) {
std::vector<const BookmarkNode*> account_nodes;
std::vector<const BookmarkNode*> local_nodes;
for (const BookmarkNode* mru_node : mru_nodes) {
(model->IsLocalOnlyNode(*mru_node) ? result.local_nodes
: result.account_nodes)
.push_back(mru_node);
}
} else {
result.local_nodes = std::move(mru_nodes);
}
return result;
}
BookmarkNodesSplitByAccountAndLocal GetPermanentNodesForDisplay(
const BookmarkModel* model) {
BookmarkNodesSplitByAccountAndLocal permanent_nodes;
for (const auto& permanent_node : model->root_node()->children()) {
BookmarkNode* node = permanent_node.get();
// Do not include permanent nodes if they should not be visible.
if (PruneFoldersForDisplay(model, node)) {
continue;
}
if (model->IsLocalOnlyNode(*node) ||
model->client()->IsSyncFeatureEnabledIncludingBookmarks()) {
permanent_nodes.local_nodes.push_back(node);
} else {
permanent_nodes.account_nodes.push_back(node);
}
}
return permanent_nodes;
}
#endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
bool HasLocalOrSyncableBookmarks(const BookmarkModel* model) {
return std::ranges::any_of(
std::array{model->bookmark_bar_node(), model->other_node(),
model->mobile_node()},
[](const BookmarkNode* node) { return !node->children().empty(); });
}
void GetMostRecentlyAddedEntries(BookmarkModel* model,
size_t count,
std::vector<const BookmarkNode*>* nodes) {
// std::set is used here since insert element into std::vector is slower than
// std::set, so we use std::set to find the most recent bookmarks, and then
// return to users as std::vector.
std::multiset<const BookmarkNode*, decltype(&MoreRecentlyAdded)> nodes_set(
&MoreRecentlyAdded);
GetMostRecentEntries(model, count, &nodes_set);
nodes->reserve(nodes_set.size());
std::move(nodes_set.begin(), nodes_set.end(), std::back_inserter(*nodes));
}
bool MoreRecentlyAdded(const BookmarkNode* n1, const BookmarkNode* n2) {
return n1->date_added() > n2->date_added();
}
void GetMostRecentlyUsedEntries(BookmarkModel* model,
size_t count,
std::vector<const BookmarkNode*>* nodes) {
// std::set is used here since insert element into std::vector is slower than
// std::set, so we use std::set to find the most recent bookmarks, and then
// return to users as std::vector.
auto lastUsedComp = [](const BookmarkNode* n1, const BookmarkNode* n2) {
if (n1->date_last_used() == n2->date_last_used()) {
// Both bookmarks have same used date, we compare added date instead,
// normally this happens when both bookmarks are never used.
return n1->date_added() > n2->date_added();
}
return n1->date_last_used() > n2->date_last_used();
};
std::multiset<const BookmarkNode*, decltype(lastUsedComp)> nodes_set(
lastUsedComp);
GetMostRecentEntries(model, count, &nodes_set);
nodes->reserve(nodes_set.size());
std::move(nodes_set.begin(), nodes_set.end(), std::back_inserter(*nodes));
}
std::vector<const BookmarkNode*> GetBookmarksMatchingProperties(
BookmarkModel* model,
const QueryFields& query,
size_t max_count) {
std::vector<std::u16string> query_words = ParseBookmarkQuery(query);
if (query.word_phrase_query && query_words.empty()) {
return {};
}
if (query.url) {
// Shortcut into the BookmarkModel if searching for URL.
GURL url(*query.url);
std::vector<raw_ptr<const BookmarkNode, VectorExperimental>>
url_matched_nodes;
if (url.is_valid()) {
url_matched_nodes = model->GetNodesByURL(url);
}
VectorIterator iterator(&url_matched_nodes);
return GetBookmarksMatchingPropertiesImpl<VectorIterator>(
iterator, model, query, query_words, max_count);
}
ui::TreeNodeIterator<const BookmarkNode> iterator(model->root_node());
return GetBookmarksMatchingPropertiesImpl<
ui::TreeNodeIterator<const BookmarkNode>>(iterator, model, query,
query_words, max_count);
}
// Parses the provided query and returns a vector of query words.
std::vector<std::u16string> ParseBookmarkQuery(
const bookmarks::QueryFields& query) {
std::vector<std::u16string> query_words;
if (query.word_phrase_query) {
query_parser::QueryParser::ParseQueryWords(
base::i18n::ToLower(*query.word_phrase_query),
query_parser::MatchingAlgorithm::DEFAULT, &query_words);
}
return query_words;
}
// Returns true if `node`s title or url contains the strings in `words`.
bool DoesBookmarkContainWords(const std::u16string& title,
const GURL& url,
const std::vector<std::u16string>& words) {
return DoesBookmarkTextContainWords(title, words) ||
DoesBookmarkTextContainWords(base::UTF8ToUTF16(url.spec()), words) ||
DoesBookmarkTextContainWords(
url_formatter::FormatUrl(url, url_formatter::kFormatUrlOmitNothing,
base::UnescapeRule::NORMAL, nullptr,
nullptr, nullptr),
words);
}
void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterBooleanPref(
prefs::kShowBookmarkBar, false,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
registry->RegisterBooleanPref(prefs::kEditBookmarksEnabled, true);
registry->RegisterBooleanPref(
prefs::kShowAppsShortcutInBookmarkBar, false,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
registry->RegisterBooleanPref(
prefs::kShowTabGroupsInBookmarkBar, true,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
registry->RegisterBooleanPref(
prefs::kShowManagedBookmarksInBookmarkBar, true,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
registry->RegisterTimePref(prefs::kBookmarkStorageComputationLastUpdatePref,
base::Time());
RegisterManagedBookmarksPrefs(registry);
}
void RegisterManagedBookmarksPrefs(PrefRegistrySimple* registry) {
registry->RegisterListPref(prefs::kManagedBookmarks);
registry->RegisterStringPref(prefs::kManagedBookmarksFolderName,
std::string());
}
void DeleteBookmarkFolders(BookmarkModel* model,
const std::vector<int64_t>& ids,
const base::Location& location) {
// Remove the folders that were removed. This has to be done after all the
// other changes have been committed.
for (auto iter = ids.begin(); iter != ids.end(); ++iter) {
const BookmarkNode* node = GetBookmarkNodeByID(model, *iter);
if (!node) {
continue;
}
model->Remove(node, metrics::BookmarkEditSource::kUser, location);
}
}
const BookmarkNode* AddIfNotBookmarked(BookmarkModel* model,
const GURL& url,
const std::u16string& title) {
// Nothing to do, a user bookmark with that url already exists.
if (IsBookmarkedByUser(model, url)) {
return nullptr;
}
base::RecordAction(base::UserMetricsAction("BookmarkAdded"));
const BookmarkNode* parent_to_use = GetParentForNewNodes(model, url);
return model->AddNewURL(parent_to_use, parent_to_use->children().size(),
title, url);
}
void RemoveAllBookmarks(BookmarkModel* model,
const GURL& url,
const base::Location& location) {
// Remove all the user bookmarks.
for (const BookmarkNode* node : model->GetNodesByURL(url)) {
if (!model->client()->IsNodeManaged(node)) {
model->Remove(node, metrics::BookmarkEditSource::kUser, location);
}
}
}
bool IsBookmarkedByUser(BookmarkModel* model, const GURL& url) {
for (const BookmarkNode* node : model->GetNodesByURL(url)) {
if (!model->client()->IsNodeManaged(node)) {
return true;
}
}
return false;
}
const BookmarkNode* GetBookmarkNodeByID(const BookmarkModel* model,
int64_t id) {
return FindNode(model->root_node(),
[id](const BookmarkNode* node) { return node->id() == id; });
}
bool IsDescendantOf(const BookmarkNode* node, const BookmarkNode* root) {
return node && node->HasAncestor(root);
}
bool HasDescendantsOf(
const std::vector<raw_ptr<const BookmarkNode, VectorExperimental>>& list,
const BookmarkNode* root) {
for (const BookmarkNode* node : list) {
if (IsDescendantOf(node, root)) {
return true;
}
}
return false;
}
const BookmarkNode* GetParentForNewNodes(BookmarkModel* model,
const GURL& url) {
const BookmarkNode* parent = model->client()->GetSuggestedSaveLocation(url);
if (parent) {
return parent;
}
// Return the last modified folder if there is no save location suggestion.
std::vector<const BookmarkNode*> nodes =
GetMostRecentlyModifiedUserFolders(model);
CHECK(!nodes.empty());
return nodes[0];
}
bool PruneFoldersForDisplay(const BookmarkModel* model,
const BookmarkNode* node) {
return !node->IsVisible() || !node->is_folder() ||
model->client()->IsNodeManaged(node);
}
} // namespace bookmarks
|