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

Side by Side Diff: ios/chrome/browser/ui/bookmarks/bookmark_utils_ios.mm

Issue 2586993002: Upstream Chrome on iOS source code [3/11]. (Closed)
Patch Set: Created 4 years 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) 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 #import "ios/chrome/browser/ui/bookmarks/bookmark_utils_ios.h"
6
7 #include <stdint.h>
8 #include <memory>
9
10 #include "base/hash.h"
11 #include "base/i18n/string_compare.h"
12 #include "base/mac/bind_objc_block.h"
13 #include "base/mac/scoped_nsautorelease_pool.h"
14 #include "base/mac/scoped_nsobject.h"
15 #include "base/metrics/user_metrics_action.h"
16 #include "base/strings/sys_string_conversions.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "components/bookmarks/browser/bookmark_model.h"
19 #include "components/query_parser/query_parser.h"
20 #include "components/strings/grit/components_strings.h"
21 #include "ios/chrome/browser/bookmarks/bookmarks_utils.h"
22 #include "ios/chrome/browser/experimental_flags.h"
23 #import "ios/chrome/browser/ui/bookmarks/bookmark_collection_cells.h"
24 #import "ios/chrome/browser/ui/bookmarks/bookmark_menu_item.h"
25 #import "ios/chrome/browser/ui/bookmarks/bookmark_position_cache.h"
26 #include "ios/chrome/browser/ui/bookmarks/undo_manager_wrapper.h"
27 #include "ios/chrome/browser/ui/ui_util.h"
28 #import "ios/chrome/browser/ui/uikit_ui_util.h"
29 #include "ios/chrome/grit/ios_strings.h"
30 #import "ios/third_party/material_components_ios/src/components/Snackbar/src/Mat erialSnackbar.h"
31 #include "third_party/skia/include/core/SkColor.h"
32 #include "ui/base/l10n/l10n_util.h"
33 #include "ui/base/l10n/l10n_util_mac.h"
34 #include "ui/base/models/tree_node_iterator.h"
35
36 using bookmarks::BookmarkNode;
37
38 namespace bookmark_utils_ios {
39
40 namespace {
41
42 const BookmarkNode* FindFolderById(bookmarks::BookmarkModel* model,
43 int64_t id) {
44 ui::TreeNodeIterator<const BookmarkNode> iterator(model->root_node());
45 while (iterator.has_next()) {
46 const BookmarkNode* bookmark = iterator.Next();
47 if (bookmark->id() == id && bookmark->is_folder())
48 return bookmark;
49 }
50 return NULL;
51 }
52
53 const SkColor colors[] = {
54 0xE64A19, 0xF09300, 0xAFB42B, 0x689F38,
55 0x0B8043, 0x0097A7, 0x7B1FA2, 0xC2185B,
56 };
57
58 UIColor* ColorFromSkColor(SkColor color) {
59 return [UIColor colorWithRed:SkColorGetR(color) / 255.0f
60 green:SkColorGetG(color) / 255.0f
61 blue:SkColorGetB(color) / 255.0f
62 alpha:1.0];
63 }
64
65 } // namespace
66
67 // This is the distance from the left edge of the screen to the left edge of a
68 // 24x24 image.
69 const CGFloat menuMargin = 16;
70 const CGFloat titleMargin = 73;
71 const CGFloat titleToIconDistance = 33;
72 const CGFloat menuAnimationDuration = 0.2;
73 NSString* const kPositionCacheKey = @"BookmarksStarsPositionCacheKey";
74 NSString* const kBookmarksSnackbarCategory = @"BookmarksSnackbarCategory";
75
76 NSString* TitleForBookmarkNode(const BookmarkNode* node) {
77 NSString* title;
78
79 if (node->type() == BookmarkNode::BOOKMARK_BAR) {
80 title = l10n_util::GetNSString(IDS_IOS_BOOKMARK_NEW_BOOKMARKS_BAR_TITLE);
81 } else if (node->type() == BookmarkNode::MOBILE) {
82 title = l10n_util::GetNSString(IDS_BOOKMARK_BAR_MOBILE_FOLDER_NAME);
83 } else if (node->type() == BookmarkNode::OTHER_NODE) {
84 title = l10n_util::GetNSString(IDS_BOOKMARK_BAR_OTHER_FOLDER_NAME);
85 } else {
86 title = base::SysUTF16ToNSString(node->GetTitle());
87 }
88
89 // Assign a default bookmark name if it is at top level.
90 if (node->is_root() && ![title length])
91 title = l10n_util::GetNSString(IDS_SYNC_DATATYPE_BOOKMARKS);
92
93 return title;
94 }
95
96 UIColor* DefaultColor(const GURL& url) {
97 uint32_t hash = base::Hash(url.possibly_invalid_spec());
98 SkColor color = colors[hash % arraysize(colors)];
99 return ColorFromSkColor(color);
100 }
101
102 NSString* subtitleForBookmarkNode(const BookmarkNode* node) {
103 if (node->is_url())
104 return base::SysUTF8ToNSString(node->url().host());
105
106 int childCount = node->GetTotalNodeCount() - 1;
107 NSString* subtitle;
108 if (childCount == 0) {
109 subtitle = l10n_util::GetNSString(IDS_IOS_BOOKMARK_NO_ITEM_COUNT);
110 } else if (childCount == 1) {
111 subtitle = l10n_util::GetNSString(IDS_IOS_BOOKMARK_ONE_ITEM_COUNT);
112 } else {
113 NSString* childCountString = [NSString stringWithFormat:@"%d", childCount];
114 subtitle =
115 l10n_util::GetNSStringF(IDS_IOS_BOOKMARK_ITEM_COUNT,
116 base::SysNSStringToUTF16(childCountString));
117 }
118 return subtitle;
119 }
120
121 UIColor* mainBackgroundColor() {
122 if (IsIPadIdiom()) {
123 return [UIColor whiteColor];
124 } else {
125 return [UIColor colorWithWhite:242 / 255.0 alpha:1.0];
126 }
127 }
128
129 UIColor* menuBackgroundColor() {
130 if (bookmarkMenuIsInSlideInPanel()) {
131 return [UIColor whiteColor];
132 } else {
133 return [UIColor clearColor];
134 }
135 }
136
137 UIColor* darkTextColor() {
138 return [UIColor colorWithWhite:33 / 255.0 alpha:1.0];
139 }
140
141 UIColor* lightTextColor() {
142 return [UIColor colorWithWhite:118 / 255.0 alpha:1.0];
143 }
144
145 UIColor* highlightedDarkTextColor() {
146 return [UIColor colorWithWhite:102 / 255.0 alpha:1.0];
147 }
148
149 UIColor* blueColor() {
150 return [UIColor colorWithRed:66 / 255.0
151 green:129 / 255.0
152 blue:244 / 255.0
153 alpha:1];
154 }
155
156 UIColor* GrayColor() {
157 return [UIColor colorWithWhite:242 / 255.0 alpha:1.0];
158 }
159
160 UIColor* separatorColor() {
161 return [UIColor colorWithWhite:214 / 255.0 alpha:1.0];
162 }
163
164 UIColor* FolderLabelColor() {
165 return [UIColor colorWithWhite:38 / 255.0 alpha:0.8];
166 }
167
168 CGFloat StatusBarHeight() {
169 CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
170 CGRect statusBarWindowRect =
171 [[UIApplication sharedApplication].keyWindow convertRect:statusBarFrame
172 fromWindow:nil];
173 if (UIInterfaceOrientationIsPortrait(
174 [UIApplication sharedApplication].statusBarOrientation)) {
175 return CGRectGetHeight(statusBarWindowRect);
176 } else {
177 return CGRectGetWidth(statusBarWindowRect);
178 }
179 }
180
181 BOOL bookmarkMenuIsInSlideInPanel() {
182 return !IsIPadIdiom() || IsCompactTablet();
183 }
184
185 UIView* dropShadowWithWidth(CGFloat width) {
186 UIImage* shadowImage = [UIImage imageNamed:@"bookmark_bar_shadow"];
187 UIImageView* shadow =
188 [[[UIImageView alloc] initWithImage:shadowImage] autorelease];
189 CGRect shadowFrame = CGRectMake(0, 0, width, 4);
190 shadow.frame = shadowFrame;
191 shadow.autoresizingMask =
192 UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
193 return shadow;
194 }
195
196 #pragma mark - Updating Bookmarks
197
198 // Deletes all subnodes of |node|, including |node|, that are in |bookmarks|.
199 void DeleteBookmarks(const std::set<const BookmarkNode*>& bookmarks,
200 bookmarks::BookmarkModel* model,
201 const BookmarkNode* node);
202
203 // Presents a toast which will undo the changes made to the bookmark model if
204 // the user presses the undo button, and the UndoManagerWrapper allows the undo
205 // to go through.
206 void PresentUndoToastWithWrapper(UndoManagerWrapper* wrapper, NSString* text);
207
208 void CreateOrUpdateBookmarkWithUndoToast(
209 const BookmarkNode* node,
210 NSString* title,
211 const GURL& url,
212 const BookmarkNode* folder,
213 bookmarks::BookmarkModel* bookmark_model,
214 ios::ChromeBrowserState* browser_state) {
215 DCHECK(!node || node->is_url());
216 base::string16 titleString = base::SysNSStringToUTF16(title);
217
218 // If the bookmark has no changes supporting Undo, just bail out.
219 if (node && node->GetTitle() == titleString && node->url() == url &&
220 node->parent() == folder) {
221 return;
222 }
223
224 // Secondly, create an Undo group for all undoable actions.
225 base::scoped_nsobject<UndoManagerWrapper> wrapper(
226 [[UndoManagerWrapper alloc] initWithBrowserState:browser_state]);
227
228 // Create or update the bookmark.
229 [wrapper startGroupingActions];
230
231 // Save the bookmark information.
232 if (!node) { // Create a new bookmark.
233 bookmark_model->client()->RecordAction(
234 base::UserMetricsAction("BookmarkAdded"));
235 node =
236 bookmark_model->AddURL(folder, folder->child_count(), titleString, url);
237 } else { // Update the information.
238 bookmark_model->SetTitle(node, titleString);
239 bookmark_model->SetURL(node, url);
240
241 DCHECK(folder);
242 DCHECK(!folder->HasAncestor(node));
243 if (node->parent() != folder) {
244 bookmark_model->Move(node, folder, folder->child_count());
245 }
246 DCHECK(node->parent() == folder);
247 }
248
249 [wrapper stopGroupingActions];
250 [wrapper resetUndoManagerChanged];
251
252 NSString* text =
253 l10n_util::GetNSString((node) ? IDS_IOS_BOOKMARK_NEW_BOOKMARK_UPDATED
254 : IDS_IOS_BOOKMARK_NEW_BOOKMARK_CREATED);
255 PresentUndoToastWithWrapper(wrapper, text);
256 }
257
258 void PresentUndoToastWithWrapper(UndoManagerWrapper* wrapper, NSString* text) {
259 // Create the block that will be executed if the user taps the undo button.
260 MDCSnackbarMessageAction* action =
261 [[[MDCSnackbarMessageAction alloc] init] autorelease];
262 action.handler = ^{
263 if (![wrapper hasUndoManagerChanged])
264 [wrapper undo];
265 };
266
267 action.title = l10n_util::GetNSString(IDS_IOS_BOOKMARK_NEW_UNDO_BUTTON_TITLE);
268 action.accessibilityIdentifier = @"Undo";
269 action.accessibilityLabel =
270 l10n_util::GetNSString(IDS_IOS_BOOKMARK_NEW_UNDO_BUTTON_TITLE);
271 MDCSnackbarMessage* message = [MDCSnackbarMessage messageWithText:text];
272 message.action = action;
273 message.category = kBookmarksSnackbarCategory;
274 [MDCSnackbarManager showMessage:message];
275 }
276
277 void DeleteBookmarks(const std::set<const BookmarkNode*>& bookmarks,
278 bookmarks::BookmarkModel* model) {
279 DCHECK(model->loaded());
280 DeleteBookmarks(bookmarks, model, model->root_node());
281 }
282
283 void DeleteBookmarks(const std::set<const BookmarkNode*>& bookmarks,
284 bookmarks::BookmarkModel* model,
285 const BookmarkNode* node) {
286 // Delete children in reverse order, so that the index remains valid.
287 for (int i = node->child_count() - 1; i >= 0; --i) {
288 DeleteBookmarks(bookmarks, model, node->GetChild(i));
289 }
290
291 if (bookmarks.find(node) != bookmarks.end())
292 model->Remove(node);
293 }
294
295 void DeleteBookmarksWithUndoToast(const std::set<const BookmarkNode*>& nodes,
296 bookmarks::BookmarkModel* model,
297 ios::ChromeBrowserState* browser_state) {
298 size_t nodeCount = nodes.size();
299 DCHECK_GT(nodeCount, 0u);
300
301 base::scoped_nsobject<UndoManagerWrapper> wrapper(
302 [[UndoManagerWrapper alloc] initWithBrowserState:browser_state]);
303
304 // Delete the selected bookmarks.
305 [wrapper startGroupingActions];
306 bookmark_utils_ios::DeleteBookmarks(nodes, model);
307 [wrapper stopGroupingActions];
308 [wrapper resetUndoManagerChanged];
309
310 NSString* text = nil;
311
312 if (nodeCount == 1) {
313 text = l10n_util::GetNSString(IDS_IOS_BOOKMARK_NEW_SINGLE_BOOKMARK_DELETE);
314 } else {
315 NSString* countString = [NSString stringWithFormat:@"%zu", nodeCount];
316 text =
317 l10n_util::GetNSStringF(IDS_IOS_BOOKMARK_NEW_MULTIPLE_BOOKMARK_DELETE,
318 base::SysNSStringToUTF16(countString));
319 }
320
321 PresentUndoToastWithWrapper(wrapper, text);
322 }
323
324 bool MoveBookmarks(const std::set<const BookmarkNode*>& bookmarks,
325 bookmarks::BookmarkModel* model,
326 const BookmarkNode* folder) {
327 bool didPerformMove = false;
328
329 // Calling Move() on the model will triger observer methods to fire, one of
330 // them may modify the passed in |bookmarks|. To protect against this scenario
331 // a copy of the set is made first.
332 const std::set<const BookmarkNode*> bookmarks_copy(bookmarks);
333 for (const BookmarkNode* node : bookmarks_copy) {
334 // The bookmarks model can change under us at any time, so we can't make
335 // any assumptions.
336 if (folder->HasAncestor(node))
337 continue;
338 if (node->parent() != folder) {
339 model->Move(node, folder, folder->child_count());
340 didPerformMove = true;
341 }
342 }
343 return didPerformMove;
344 }
345
346 void MoveBookmarksWithUndoToast(const std::set<const BookmarkNode*>& nodes,
347 bookmarks::BookmarkModel* model,
348 const BookmarkNode* folder,
349 ios::ChromeBrowserState* browser_state) {
350 size_t nodeCount = nodes.size();
351 DCHECK_GT(nodeCount, 0u);
352
353 base::scoped_nsobject<UndoManagerWrapper> wrapper(
354 [[UndoManagerWrapper alloc] initWithBrowserState:browser_state]);
355
356 // Move the selected bookmarks.
357 [wrapper startGroupingActions];
358 bool didPerformMove = bookmark_utils_ios::MoveBookmarks(nodes, model, folder);
359 [wrapper stopGroupingActions];
360 [wrapper resetUndoManagerChanged];
361
362 if (!didPerformMove)
363 return; // Don't present a snackbar when no real move as happened.
364
365 NSString* text = nil;
366 if (nodeCount == 1) {
367 text = l10n_util::GetNSString(IDS_IOS_BOOKMARK_NEW_SINGLE_BOOKMARK_MOVE);
368 } else {
369 NSString* countString = [NSString stringWithFormat:@"%zu", nodeCount];
370 text = l10n_util::GetNSStringF(IDS_IOS_BOOKMARK_NEW_MULTIPLE_BOOKMARK_MOVE,
371 base::SysNSStringToUTF16(countString));
372 }
373
374 PresentUndoToastWithWrapper(wrapper, text);
375 }
376
377 const BookmarkNode* defaultMoveFolder(
378 const std::set<const BookmarkNode*>& bookmarks,
379 bookmarks::BookmarkModel* model) {
380 if (bookmarks.size() == 0)
381 return model->mobile_node();
382 const BookmarkNode* firstParent = (*(bookmarks.begin()))->parent();
383 for (const BookmarkNode* node : bookmarks) {
384 if (node->parent() != firstParent)
385 return model->mobile_node();
386 }
387
388 return firstParent;
389 }
390
391 #pragma mark - Segregation of nodes by time.
392
393 NodesSection::NodesSection() {}
394
395 NodesSection::~NodesSection() {}
396
397 // Sorts NodesSection by their time.
398 class NodesSectionComparator : public std::binary_function<const NodesSection*,
399 const NodesSection*,
400 bool> {
401 public:
402 // Returns true if |n1| preceeds |n2|.
403 bool operator()(const NodesSection* n1, const NodesSection* n2) {
404 return n1->time > n2->time;
405 }
406 };
407
408 // Sorts bookmark nodes by their creation time.
409 class NodeCreationComparator : public std::binary_function<const BookmarkNode*,
410 const BookmarkNode*,
411 bool> {
412 public:
413 // Returns true if |n1| preceeds |n2|.
414 bool operator()(const BookmarkNode* n1, const BookmarkNode* n2) {
415 return n1->date_added() > n2->date_added();
416 }
417 };
418
419 void segregateNodes(const NodeVector& vector,
420 ScopedVector<NodesSection>& nodesSectionVector) {
421 nodesSectionVector.clear();
422
423 // Make a localized date formatter.
424 base::scoped_nsobject<NSDateFormatter> formatter(
425 [[NSDateFormatter alloc] init]);
426 [formatter setDateFormat:@"MMMM yyyy"];
427 // Segregate nodes by creation date.
428 // Nodes that were created in the same month are grouped together.
429 for (auto node : vector) {
430 base::mac::ScopedNSAutoreleasePool pool;
431 base::Time dateAdded = node->date_added();
432 base::TimeDelta delta = dateAdded - base::Time::UnixEpoch();
433 base::scoped_nsobject<NSDate> date(
434 [[NSDate alloc] initWithTimeIntervalSince1970:delta.InSeconds()]);
435 NSString* dateString = [formatter stringFromDate:date];
436 const std::string timeRepresentation = base::SysNSStringToUTF8(dateString);
437
438 BOOL found = NO;
439 for (NodesSection* nodesSection : nodesSectionVector) {
440 if (nodesSection->timeRepresentation == timeRepresentation) {
441 nodesSection->vector.push_back(node);
442 found = YES;
443 break;
444 }
445 }
446
447 if (found)
448 continue;
449
450 // No NodesSection found.
451 NodesSection* nodesSection = new NodesSection;
452 nodesSection->time = dateAdded;
453 nodesSection->timeRepresentation = timeRepresentation;
454 nodesSection->vector.push_back(node);
455 nodesSectionVector.push_back(nodesSection);
456 }
457
458 // Sort the NodesSections.
459 std::sort(nodesSectionVector.begin(), nodesSectionVector.end(),
460 NodesSectionComparator());
461
462 // For each NodesSection, sort the nodes inside.
463 for (NodesSection* nodesSection : nodesSectionVector)
464 std::sort(nodesSection->vector.begin(), nodesSection->vector.end(),
465 NodeCreationComparator());
466 }
467
468 #pragma mark - Useful bookmark manipulation.
469
470 // Adds all children of |folder| that are not obstructed to |results|. They are
471 // placed immediately after |folder|, using a depth-first, then alphabetically
472 // ordering. |results| must contain |folder|.
473 void UpdateFoldersFromNode(const BookmarkNode* folder,
474 NodeVector* results,
475 const NodeSet& obstructions);
476 // Returns whether |folder| has an ancestor in any of the nodes in
477 // |bookmarkNodes|.
478 bool FolderHasAncestorInBookmarkNodes(const BookmarkNode* folder,
479 const NodeSet& bookmarkNodes);
480 // Returns true if the node is not a folder, is not visible, or is an ancestor
481 // of any of the nodes in |obstructions|.
482 bool IsObstructed(const BookmarkNode* node, const NodeSet& obstructions);
483
484 namespace {
485 // Comparator used to sort bookmarks. No folders are allowed.
486 class FolderNodeComparator : public std::binary_function<const BookmarkNode*,
487 const BookmarkNode*,
488 bool> {
489 public:
490 explicit FolderNodeComparator(icu::Collator* collator)
491 : collator_(collator) {}
492
493 // Returns true if |n1| preceeds |n2|.
494 bool operator()(const BookmarkNode* n1, const BookmarkNode* n2) {
495 if (!collator_)
496 return n1->GetTitle() < n2->GetTitle();
497 return base::i18n::CompareString16WithCollator(*collator_, n1->GetTitle(),
498 n2->GetTitle()) == UCOL_LESS;
499 }
500
501 private:
502 icu::Collator* collator_;
503 };
504 };
505
506 bool FolderHasAncestorInBookmarkNodes(const BookmarkNode* folder,
507 const NodeSet& bookmarkNodes) {
508 DCHECK(folder->is_folder());
509 for (const BookmarkNode* node : bookmarkNodes) {
510 if (folder->HasAncestor(node))
511 return true;
512 }
513 return false;
514 }
515
516 bool IsObstructed(const BookmarkNode* node, const NodeSet& obstructions) {
517 if (!node->is_folder())
518 return true;
519 if (!node->IsVisible())
520 return true;
521 if (FolderHasAncestorInBookmarkNodes(node, obstructions))
522 return true;
523 return false;
524 }
525
526 void UpdateFoldersFromNode(const BookmarkNode* folder,
527 NodeVector* results,
528 const NodeSet& obstructions) {
529 std::vector<const BookmarkNode*> directDescendants;
530 for (int i = 0; i < folder->child_count(); ++i) {
531 const BookmarkNode* subfolder = folder->GetChild(i);
532 if (IsObstructed(subfolder, obstructions))
533 continue;
534
535 directDescendants.push_back(subfolder);
536 }
537
538 bookmark_utils_ios::SortFolders(&directDescendants);
539
540 auto it = std::find(results->begin(), results->end(), folder);
541 DCHECK(it != results->end());
542 ++it;
543 results->insert(it, directDescendants.begin(), directDescendants.end());
544
545 // Recursively perform the operation on each direct descendant.
546 for (auto node : directDescendants)
547 UpdateFoldersFromNode(node, results, obstructions);
548 }
549
550 void SortFolders(NodeVector* vector) {
551 UErrorCode error = U_ZERO_ERROR;
552 std::unique_ptr<icu::Collator> collator(icu::Collator::createInstance(error));
553 if (U_FAILURE(error))
554 collator.reset(NULL);
555 std::sort(vector->begin(), vector->end(),
556 FolderNodeComparator(collator.get()));
557 }
558
559 NodeVector VisibleNonDescendantNodes(const NodeSet& obstructions,
560 bookmarks::BookmarkModel* model) {
561 NodeVector results;
562
563 NodeVector primaryNodes = PrimaryPermanentNodes(model);
564 NodeVector filteredPrimaryNodes;
565 for (auto node : primaryNodes) {
566 if (IsObstructed(node, obstructions))
567 continue;
568
569 filteredPrimaryNodes.push_back(node);
570 }
571
572 // Copy the results over.
573 results = filteredPrimaryNodes;
574
575 // Iterate over a static copy of the filtered, root folders.
576 for (auto node : filteredPrimaryNodes)
577 UpdateFoldersFromNode(node, &results, obstructions);
578
579 return results;
580 }
581
582 // Whether |vector1| contains only elements of |vector2| in the same order.
583 BOOL IsSubvectorOfNodes(const NodeVector& vector1, const NodeVector& vector2) {
584 NodeVector::const_iterator it = vector2.begin();
585 // Scan the first vector.
586 for (const auto& node : vector1) {
587 // Look for a match in the rest of the second vector. When found, advance
588 // the iterator on vector2 to only focus on the remaining part of vector2,
589 // so that ordering is verified.
590 it = std::find(it, vector2.end(), node);
591 if (it == vector2.end())
592 return NO;
593 // If found in vector2, advance the iterator so that the match is only
594 // matched once.
595 it++;
596 }
597 return YES;
598 }
599
600 // Returns the indices in |vector2| of the items in |vector2| that are not
601 // present in |vector1|.
602 // |vector1| MUST be a subvector of |vector2| in the sense of |IsSubvector|.
603 std::vector<NodeVector::size_type> MissingNodesIndices(
604 const NodeVector& vector1,
605 const NodeVector& vector2) {
606 DCHECK(IsSubvectorOfNodes(vector1, vector2))
607 << "Can't compute missing nodes between nodes among which the first is "
608 "not a subvector of the second.";
609
610 std::vector<NodeVector::size_type> missingNodesIndices;
611 // Keep an iterator on vector1.
612 NodeVector::const_iterator it1 = vector1.begin();
613 // Scan vector2, looking for vector1 elements.
614 for (NodeVector::size_type i2 = 0; i2 != vector2.size(); i2++) {
615 // When vector1 has been fully traversed, all remaining elements of vector2
616 // are to be added to the missing nodes.
617 // Otherwise, while the element of vector2 is not equal to the element the
618 // iterator on vector1 is pointing to, add vector2 elements to the missing
619 // nodes.
620 if (it1 == vector1.end() || vector2[i2] != *it1) {
621 missingNodesIndices.push_back(i2);
622 } else {
623 // When there is a match between vector2 and vector1, advance the iterator
624 // of vector1.
625 it1++;
626 }
627 }
628 return missingNodesIndices;
629 }
630
631 #pragma mark - Cache position in collection view.
632
633 void CachePosition(CGFloat position, BookmarkMenuItem* item) {
634 BookmarkPositionCache* cache = nil;
635 switch (item.type) {
636 case bookmarks::MenuItemFolder:
637 cache = [BookmarkPositionCache
638 cacheForMenuItemFolderWithPosition:position
639 folderId:item.folder->id()];
640 break;
641 case bookmarks::MenuItemAll:
642 cache = [BookmarkPositionCache cacheForMenuItemAllWithPosition:position];
643 break;
644 case bookmarks::MenuItemDivider:
645 case bookmarks::MenuItemSectionHeader:
646 NOTREACHED();
647 break;
648 }
649
650 // TODO(crbug.com/388789): remove the use of NSUserDefaults.
651 NSData* data = [NSKeyedArchiver archivedDataWithRootObject:cache];
652 [[NSUserDefaults standardUserDefaults] setObject:data
653 forKey:kPositionCacheKey];
654 }
655
656 BOOL GetPositionCache(bookmarks::BookmarkModel* model,
657 BookmarkMenuItem** item,
658 CGFloat* position) {
659 DCHECK(model->loaded());
660 DCHECK(item);
661 DCHECK(position);
662
663 // TODO(crbug.com/388789): remove the use of NSUserDefaults.
664 NSData* data =
665 [[NSUserDefaults standardUserDefaults] objectForKey:kPositionCacheKey];
666 if (!data || ![data isKindOfClass:[NSData class]])
667 return NO;
668 BookmarkPositionCache* cache =
669 [NSKeyedUnarchiver unarchiveObjectWithData:data];
670 if (!cache)
671 return NO;
672
673 switch (cache.type) {
674 case bookmarks::MenuItemAll:
675 if (!experimental_flags::IsAllBookmarksEnabled())
676 return NO;
677 *item = [BookmarkMenuItem allMenuItem];
678 break;
679 case bookmarks::MenuItemFolder: {
680 const BookmarkNode* bookmark = FindFolderById(model, cache.folderId);
681 if (!bookmark)
682 return NO;
683 const BookmarkNode* parent = RootLevelFolderForNode(bookmark, model);
684 if (!parent)
685 parent = bookmark;
686 *item =
687 [BookmarkMenuItem folderMenuItemForNode:bookmark rootAncestor:parent];
688 break;
689 }
690 case bookmarks::MenuItemDivider:
691 case bookmarks::MenuItemSectionHeader:
692 NOTREACHED();
693 return NO;
694 }
695
696 *position = cache.position;
697 return YES;
698 }
699
700 void ClearPositionCache() {
701 [[NSUserDefaults standardUserDefaults] removeObjectForKey:kPositionCacheKey];
702 }
703
704 } // namespace bookmark_utils_ios
OLDNEW
« no previous file with comments | « ios/chrome/browser/ui/bookmarks/bookmark_utils_ios.h ('k') | ios/chrome/browser/ui/bookmarks/bookmark_utils_ios_unittest.mm » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698