-
Notifications
You must be signed in to change notification settings - Fork 406
/
BookmarksViewController.swift
883 lines (725 loc) · 31.3 KB
/
BookmarksViewController.swift
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
//
// BookmarksViewController.swift
// DuckDuckGo
//
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Common
import UIKit
import Core
import DDGSync
import MobileCoreServices
import UniformTypeIdentifiers
import Bookmarks
import CoreData
import Combine
import Persistence
import WidgetKit
// swiftlint:disable file_length
// swiftlint:disable type_body_length
class BookmarksViewController: UIViewController, UITableViewDelegate {
private enum Constants {
static var saveToFiles = "com.apple.DocumentManagerUICore.SaveToFiles"
static var bookmarksFileName = "DuckDuckGo Bookmarks.html"
static var importBookmarkImage = "Import-24"
static var exportBookmarkImage = "Export-24"
}
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var editButton: UIBarButtonItem!
@IBOutlet weak var favoritesContainer: UIView!
@IBOutlet weak var selectorControl: UISegmentedControl!
@IBOutlet weak var importFooterButton: UIButton!
// Need to retain these as we're going to add/remove them from the view hierarchy
@IBOutlet var doneButton: UIBarButtonItem!
@IBOutlet var emptyStateContainer: UIView!
@IBOutlet var searchBar: UISearchBar!
private let bookmarksDatabase: CoreDataDatabase
private let favicons: Favicons
private let syncService: DDGSyncing
private let syncDataProviders: SyncDataProviders
private var localUpdatesCancellable: AnyCancellable?
private var syncUpdatesCancellable: AnyCancellable?
/// Creating left and right toolbar UIBarButtonItems with customView so that 'Edit' button is centered
private lazy var addFolderButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle(UserText.addbookmarkFolderButton, for: .normal)
button.titleLabel?.font = .preferredFont(forTextStyle: .body)
button.sizeToFit()
button.addTarget(self, action: #selector(onAddFolderPressed(_:)), for: .touchUpInside)
return button
}()
private lazy var addFolderBarButtonItem = UIBarButtonItem(customView: addFolderButton)
private lazy var moreButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle(UserText.moreBookmarkButton, for: .normal)
button.titleLabel?.font = .preferredFont(forTextStyle: .body)
button.sizeToFit()
button.showsMenuAsPrimaryAction = true
return button
}()
private lazy var moreBarButtonItem = UIBarButtonItem(customView: moreButton)
private var bookmarksMenu: UIMenu {
return UIMenu(title: UserText.importExportBookmarksTitle,
children: [exportAction(), importAction()])
}
private var searchController: UISearchController?
weak var delegate: BookmarksDelegate?
fileprivate var viewModelCancellable: AnyCancellable?
fileprivate let viewModel: BookmarkListInteracting
fileprivate lazy var dataSource: BookmarksDataSource = {
return BookmarksDataSource(viewModel: viewModel)
}()
var searchDataSource: SearchBookmarksDataSource
var isNested: Bool {
viewModel.currentFolder?.uuid != BookmarkEntity.Constants.rootFolderID
}
var favoritesController: FavoritesViewController?
fileprivate var onDidAppearAction: () -> Void = {}
init?(coder: NSCoder,
bookmarksDatabase: CoreDataDatabase,
bookmarksSearch: BookmarksStringSearch,
parentID: NSManagedObjectID? = nil,
favicons: Favicons = Favicons.shared,
syncService: DDGSyncing,
syncDataProviders: SyncDataProviders
) {
self.bookmarksDatabase = bookmarksDatabase
self.searchDataSource = SearchBookmarksDataSource(searchEngine: bookmarksSearch)
self.viewModel = BookmarkListViewModel(bookmarksDatabase: bookmarksDatabase, parentID: parentID, syncService: syncService)
self.favicons = favicons
self.syncService = syncService
self.syncDataProviders = syncDataProviders
super.init(coder: coder)
bindSyncService()
}
required init?(coder: NSCoder) {
fatalError("Not implemented")
}
private func bindSyncService() {
localUpdatesCancellable = viewModel.localUpdates
.sink { [weak self] in
self?.syncService.scheduler.notifyDataChanged()
}
syncUpdatesCancellable = syncDataProviders.bookmarksAdapter.syncDidCompletePublisher
.sink { [weak self] _ in
self?.viewModel.reloadData()
DispatchQueue.main.async {
self?.tableView.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
viewModelCancellable = viewModel.externalUpdates.sink { [weak self] _ in
self?.tableView.reloadData()
self?.refreshAll()
}
syncService.scheduler.requestSyncImmediately()
tableView.delegate = self
registerForNotifications()
configureSelector()
configureTableView()
configureBars()
applyTheme(ThemeManager.shared.currentTheme)
selectorControl.removeFromSuperview()
if !isNested {
let stack = UIStackView(arrangedSubviews: [selectorControl])
stack.alignment = .center
stack.axis = .vertical
navigationController?.navigationBar.topItem?.titleView = stack
onViewSelectorChanged(selectorControl)
} else {
navigationItem.title = viewModel.currentFolder?.title
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
onDidAppearAction()
onDidAppearAction = {}
tableView.reloadData()
}
@IBAction func onViewSelectorChanged(_ segment: UISegmentedControl) {
switch selectorControl.selectedSegmentIndex {
case 0:
showBookmarksView()
case 1:
showFavoritesView()
default: assertionFailure("Invalid selected segment index")
}
refreshFooterView()
}
private func refreshAll() {
refreshEditButton()
refreshFooterView()
refreshMoreButton()
refreshAddFolderButton()
}
private func showBookmarksView() {
tableView.isHidden = false
favoritesContainer.isHidden = true
addFolderButton.isHidden = false
moreButton.isHidden = false
refreshAll()
}
private func showFavoritesView() {
searchBar.resignFirstResponder()
tableView.isHidden = true
favoritesContainer.isHidden = false
addFolderButton.isHidden = true
moreButton.isHidden = true
refreshAll()
}
func openEditFormWhenPresented(bookmark: BookmarkEntity) {
onDidAppearAction = { [weak self] in
self?.performSegue(withIdentifier: "AddOrEditBookmarkFolder", sender: bookmark.objectID)
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView.dataSource === searchDataSource {
didSelectScoredBookmarkAtIndex(indexPath.row)
} else {
didSelectBookmarkAtIndex(indexPath.row)
}
tableView.deselectRow(at: indexPath, animated: true)
}
private func didSelectScoredBookmarkAtIndex(_ index: Int) {
guard searchDataSource.results.indices.contains(index) else { return }
dismiss()
delegate?.bookmarksDidSelect(url: searchDataSource.results[index].url)
}
private func didSelectBookmarkAtIndex(_ index: Int) {
guard let bookmark = viewModel.bookmark(at: index) else { return }
if isEditingBookmarks {
performSegue(withIdentifier: "AddOrEditBookmarkFolder", sender: bookmark.objectID)
} else if bookmark.isFolder {
drillIntoFolder(bookmark)
} else {
select(bookmark: bookmark)
}
}
private func drillIntoFolder(_ parent: BookmarkEntity) {
let storyboard = UIStoryboard(name: "Bookmarks", bundle: nil)
let viewController = storyboard.instantiateViewController(identifier: "BookmarksViewController", creator: { coder in
let controller = BookmarksViewController(coder: coder,
bookmarksDatabase: self.bookmarksDatabase,
bookmarksSearch: self.searchDataSource.searchEngine,
parentID: parent.objectID,
syncService: self.syncService,
syncDataProviders: self.syncDataProviders)
controller?.delegate = self.delegate
return controller
})
navigationController?.pushViewController(viewController, animated: true)
}
func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
guard let bookmark = bookmarkForSwipeAtIndexPath(indexPath),
!bookmark.isFolder else {
return nil
}
let cell = tableView.cellForRow(at: indexPath)
cell?.tintColor = .black
let title = bookmark.isFavorite ? UserText.actionRemoveFavorite : UserText.favorite
let iconName = bookmark.isFavorite ? "Favorite-Remove-24" : "Favorite-24"
let toggleFavoriteAction = UIContextualAction(style: .normal, title: title) { [weak self] (_, _, completionHandler) in
completionHandler(true)
self?.toggleFavoriteAfterSwipe(bookmark, indexPath)
tableView.reloadRows(at: [indexPath], with: .automatic)
}
toggleFavoriteAction.image = UIImage(named: iconName)?.withTintColor(.black, renderingMode: .alwaysOriginal)
toggleFavoriteAction.backgroundColor = UIColor.yellow60
return UISwipeActionsConfiguration(actions: [toggleFavoriteAction])
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
guard let bookmark = bookmarkForSwipeAtIndexPath(indexPath) else {
return nil
}
let deleteAction = UIContextualAction(style: .destructive, title:
UserText.deleteBookmarkFolderAlertDeleteButton) { _, _, completion in
self.deleteBookmarkAfterSwipe(bookmark, indexPath, completion)
}
deleteAction.image = UIImage(named: "Trash-24")
return UISwipeActionsConfiguration(actions: [deleteAction])
}
private func bookmarkForSwipeAtIndexPath(_ indexPath: IndexPath) -> BookmarkEntity? {
if tableView.dataSource is BookmarksDataSource {
return viewModel.bookmark(at: indexPath.row)
} else if let dataSource = tableView.dataSource as? SearchBookmarksDataSource {
return viewModel.bookmark(with: dataSource.results[indexPath.row].objectID)
}
return nil
}
private func registerForNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(onApplicationBecameActive),
name: UIApplication.didBecomeActiveNotification,
object: nil)
}
private func toggleFavoriteAfterSwipe(_ bookmark: BookmarkEntity, _ indexPath: IndexPath) {
self.viewModel.toggleFavorite(bookmark)
WidgetCenter.shared.reloadAllTimelines()
if let dataSource = tableView.dataSource as? SearchBookmarksDataSource {
dataSource.toggleFavorite(at: indexPath.row)
}
}
private func domainsInBookmarkTree(_ bookmark: BookmarkEntity) -> Set<String> {
func addDomains(_ bookmark: BookmarkEntity, domains: inout Set<String>) {
if let domain = bookmark.urlObject?.host {
domains.insert(domain)
} else {
bookmark.childrenArray.forEach {
addDomains($0, domains: &domains)
}
}
}
var domains = Set<String>()
addDomains(bookmark, domains: &domains)
return domains
}
private func removeUnusedFaviconsForDomains(_ domains: Set<String>) {
domains
.filter { viewModel.countBookmarksForDomain($0) == 0 }
.forEach {
favicons.removeBookmarkFavicon(forDomain: $0)
}
}
private func deleteBookmarkAfterSwipe(_ bookmark: BookmarkEntity,
_ indexPath: IndexPath,
_ completion: @escaping (Bool) -> Void) {
func delete() {
let domains = domainsInBookmarkTree(bookmark)
let oldCount = viewModel.bookmarks.count
viewModel.softDeleteBookmark(bookmark)
let newCount = viewModel.bookmarks.count
// Make sure we are animating only single removal
if newCount > 0 && newCount + 1 == oldCount {
tableView.deleteRows(at: [indexPath], with: .fade)
} else {
tableView.reloadSections([indexPath.section], with: .none)
}
refreshFooterView()
removeUnusedFaviconsForDomains(domains)
}
func countAllChildrenInFolder(_ folder: BookmarkEntity) -> Int {
var count = 0
folder.childrenArray.forEach { bookmark in
count += 1
if bookmark.isFolder {
count += countAllChildrenInFolder(bookmark)
}
}
return count
}
if let dataSource = tableView.dataSource as? SearchBookmarksDataSource {
dataSource.results.remove(at: indexPath.row)
delete()
return
}
if bookmark.isFolder, bookmark.children?.count ?? 0 > 0 {
let title = String(format: UserText.deleteBookmarkFolderAlertTitle, bookmark.title ?? "")
let count = countAllChildrenInFolder(bookmark)
let message = UserText.deleteBookmarkFolderAlertMessage(numberOfChildren: count)
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(title: UserText.deleteBookmarkFolderAlertDeleteButton, style: .default) {
delete()
completion(true)
}
alertController.addAction(title: UserText.actionCancel, style: .cancel) {
completion(true)
}
present(alertController, animated: true)
} else {
delete()
completion(true)
}
}
private func configureSelector() {
favoritesContainer.backgroundColor = tableView.backgroundColor
selectorControl.setTitle(UserText.sectionTitleBookmarks, forSegmentAt: 0)
}
private func configureTableView() {
if isNested {
tableView.tableHeaderView = nil
}
tableView.dataSource = dataSource
importFooterButton.setTitle(UserText.importBookmarksFooterButton, for: .normal)
importFooterButton.setTitleColor(UIColor.cornflowerBlue, for: .normal)
importFooterButton.titleLabel?.textAlignment = .center
importFooterButton.addAction(UIAction { [weak self] _ in
self?.presentDocumentPicker()
}, for: .touchUpInside)
if viewModel.totalBookmarksCount == 0 {
tableView.tableHeaderView?.removeFromSuperview()
}
refreshFooterView()
}
@objc func onApplicationBecameActive(notification: NSNotification) {
tableView.reloadData()
}
func configureBars() {
self.navigationController?.setToolbarHidden(false, animated: true)
toolbarItems?.insert(addFolderBarButtonItem, at: 0)
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil)
toolbarItems?.insert(flexibleSpace, at: 1)
// Edit button is at position 2
configureToolbarMoreItem()
if isNested, let title = viewModel.currentFolder?.title {
self.title = title
}
refreshEditButton()
}
private func configureToolbarMoreItem() {
if isEditingBookmarks {
if toolbarItems?.count ?? 0 >= 5 {
toolbarItems?.remove(at: 4)
toolbarItems?.remove(at: 3)
}
} else {
if toolbarItems?.contains(moreBarButtonItem) == false {
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil)
toolbarItems?.insert(flexibleSpace, at: 3)
toolbarItems?.insert(moreBarButtonItem, at: 4)
}
refreshMoreButton()
}
}
private func refreshEditButton() {
if isEditingBookmarks {
changeEditButtonToDone()
return
}
editButton.title = UserText.actionGenericEdit
if !favoritesContainer.isHidden {
editButton.isEnabled = favoritesController?.isEditing == true || (favoritesController?.hasFavorites ?? false)
editButton.title = UserText.actionManageFavorites
} else if (dataSource.isEmpty && !isEditingBookmarks) || dataSource === searchDataSource {
disableEditButton()
} else if !isEditingBookmarks {
enableEditButton()
}
}
private func refreshAddFolderButton() {
if dataSource === searchDataSource {
disableAddFolderButton()
} else {
enableAddFolderButton()
}
}
private func refreshMoreButton() {
if isNested || isEditingBookmarks || dataSource === searchDataSource || viewModel.currentFolder?.isRoot == false {
disableMoreButton()
} else {
enableMoreButton()
}
}
private func refreshFooterView() {
if !isNested &&
dataSource.isEmpty &&
dataSource !== searchDataSource &&
selectorControl.selectedSegmentIndex == 0 {
showEmptyState()
} else {
hideEmptyState()
}
}
@IBAction func onAddFolderPressed(_ sender: Any) {
performSegue(withIdentifier: "AddOrEditBookmarkFolder", sender: nil)
}
@IBAction func onEditPressed(_ sender: UIBarButtonItem) {
if isEditingBookmarks {
finishEditing()
} else {
startEditing()
}
}
@IBAction func onDonePressed(_ sender: UIBarButtonItem) {
dismiss()
}
@IBSegueAction func onCreateEditor(_ coder: NSCoder, sender: Any?, segueIdentifier: String?) -> AddOrEditBookmarkViewController? {
if let id = sender as? NSManagedObjectID {
guard let controller = AddOrEditBookmarkViewController(coder: coder,
editingEntityID: id,
bookmarksDatabase: bookmarksDatabase,
syncService: syncService) else {
assertionFailure("Failed to create controller")
return nil
}
return controller
} else {
guard let controller = AddOrEditBookmarkViewController(coder: coder,
parentFolderID: viewModel.currentFolder?.objectID,
bookmarksDatabase: bookmarksDatabase,
syncService: syncService) else {
assertionFailure("Failed to create controller")
return nil
}
return controller
}
}
@IBSegueAction func onCreateFavoritesView(_ coder: NSCoder, sender: Any?, segueIdentifier: String?) -> FavoritesViewController {
guard let controller = FavoritesViewController(
coder: coder,
bookmarksDatabase: bookmarksDatabase,
syncService: syncService,
syncDataProviders: syncDataProviders
) else {
fatalError("Failed to create controller")
}
return controller
}
// MARK: Import bookmarks
func importAction() -> UIAction {
return UIAction(title: UserText.importBookmarksActionTitle,
image: UIImage(named: Constants.importBookmarkImage)
) { [weak self] _ in
self?.presentDocumentPicker()
}
}
func presentDocumentPicker() {
let docTypes = [UTType.html]
let docPicker = UIDocumentPickerViewController(forOpeningContentTypes: docTypes, asCopy: true)
docPicker.delegate = self
docPicker.allowsMultipleSelection = false
present(docPicker, animated: true)
}
func importBookmarks(fromHtml html: String) {
let bookmarkCountBeforeImport = dataSource.viewModel.totalBookmarksCount
let bookmarksDatabase = bookmarksDatabase
Task {
let result = await BookmarksImporter(coreDataStore: bookmarksDatabase).parseAndSave(html: html)
switch result {
case .success:
WidgetCenter.shared.reloadAllTimelines()
DispatchQueue.main.async { [weak self] in
let bookmarkCountAfterImport = self?.dataSource.viewModel.totalBookmarksCount ?? 0
let bookmarksImported = bookmarkCountAfterImport - bookmarkCountBeforeImport
Pixel.fire(pixel: .bookmarkImportSuccess,
withAdditionalParameters: [PixelParameters.bookmarkCount: "\(bookmarksImported)"])
ActionMessageView.present(message: UserText.importBookmarksSuccessMessage)
}
case .failure(let bookmarksImportError):
os_log("Bookmarks import error %s", type: .debug, bookmarksImportError.localizedDescription)
Pixel.fire(pixel: .bookmarkImportFailure)
DispatchQueue.main.async {
ActionMessageView.present(message: UserText.importBookmarksFailedMessage)
}
}
}
}
// MARK: Export bookmarks
func exportAction() -> UIAction {
return UIAction(title: UserText.exportBookmarksActionTitle,
image: UIImage(named: Constants.exportBookmarkImage),
attributes: dataSource.isEmpty ? .disabled : []) { [weak self] _ in
self?.exportHtmlFile()
}
}
func exportHtmlFile() {
// create file to export
let tempFileUrl = FileManager.default.temporaryDirectory.appendingPathComponent(Constants.bookmarksFileName)
do {
try BookmarksExporter(coreDataStore: bookmarksDatabase).exportBookmarksTo(url: tempFileUrl)
} catch {
os_log("bookmarks failed to export %s", type: .debug, error.localizedDescription)
ActionMessageView.present(message: UserText.exportBookmarksFailedMessage)
return
}
// create activityViewController with exported file
let activity = UIActivityViewController(activityItems: [tempFileUrl], applicationActivities: nil)
activity.completionWithItemsHandler = {[weak self] (activityType: UIActivity.ActivityType?, completed: Bool, _: [Any]?, error: Error?) in
guard error == nil else {
// this trips if user cancelled Save to Files but they are still in the UIActivityViewController so
// can still choose to share to another app so in this case we don't want to delete the bookmarks file yet
if let error = error as NSError?, error.code == NSUserCancelledError {
return
}
Pixel.fire(pixel: .bookmarkExportFailure)
self?.presentActionMessageView(withMessage: UserText.exportBookmarksFailedMessage)
self?.cleanupTempFile(tempFileUrl)
return
}
if completed && activityType != nil {
if let activityTypeStr = activityType?.rawValue, activityTypeStr == Constants.saveToFiles {
self?.presentActionMessageView(withMessage: UserText.exportBookmarksFilesSuccessMessage)
} else {
self?.presentActionMessageView(withMessage: UserText.exportBookmarksShareSuccessMessage)
}
Pixel.fire(pixel: .bookmarkExportSuccess)
}
self?.cleanupTempFile(tempFileUrl)
}
if let popover = activity.popoverPresentationController {
popover.sourceView = moreBarButtonItem.customView
}
present(activity, animated: true, completion: nil)
}
func cleanupTempFile(_ tempFileUrl: URL) {
try? FileManager.default.removeItem(at: tempFileUrl)
}
func presentActionMessageView(withMessage message: String) {
DispatchQueue.main.async {
ActionMessageView.present(message: message)
}
}
// when swipe-to-delete control is shown tableView.isEditing is true
private var isEditingBookmarks: Bool = false
private func startEditing() {
assert(!isEditingBookmarks)
// necessary in case a cell is swiped (which would mean isEditing is already true, and setting it again wouldn't do anything)
tableView.isEditing = false
tableView.setEditing(true, animated: true)
favoritesController?.isEditing = true
self.isEditingBookmarks = true
changeEditButtonToDone()
configureToolbarMoreItem()
refreshFooterView()
}
private func finishEditing() {
favoritesController?.isEditing = false
guard tableView.isEditing else {
return
}
tableView.setEditing(false, animated: true)
self.isEditingBookmarks = false
refreshEditButton()
enableDoneButton()
configureToolbarMoreItem()
refreshFooterView()
}
private func enableEditButton() {
editButton.title = UserText.navigationTitleEdit
editButton.isEnabled = true
}
private func disableEditButton() {
editButton.title = UserText.navigationTitleEdit
editButton.isEnabled = false
}
private func enableAddFolderButton() {
addFolderBarButtonItem.title = UserText.addbookmarkFolderButton
addFolderBarButtonItem.isEnabled = true
}
private func disableAddFolderButton() {
addFolderBarButtonItem.isEnabled = false
}
private func changeEditButtonToDone() {
editButton.title = UserText.navigationTitleDone
doneButton.title = ""
navigationItem.rightBarButtonItem = nil
doneButton.isEnabled = false
}
private func enableDoneButton() {
doneButton.title = UserText.navigationTitleDone
navigationItem.rightBarButtonItem = doneButton
doneButton.isEnabled = true
}
private func enableMoreButton() {
moreButton.menu = bookmarksMenu
moreButton.isEnabled = true
}
private func disableMoreButton() {
moreButton.isEnabled = false
}
private func showEmptyState() {
emptyStateContainer.isHidden = false
importFooterButton.isHidden = false
importFooterButton.isEnabled = true
searchBar.removeFromSuperview()
}
private func hideEmptyState() {
emptyStateContainer.isHidden = true
importFooterButton.isHidden = true
importFooterButton.isEnabled = false
tableView.tableHeaderView = searchBar
}
private func prepareForSearching() {
finishEditing()
disableEditButton()
disableAddFolderButton()
}
private func finishSearching() {
tableView.dataSource = dataSource
tableView.reloadData()
enableEditButton()
enableAddFolderButton()
}
fileprivate func select(bookmark: BookmarkEntity) {
guard let url = bookmark.urlObject else { return }
dismiss()
delegate?.bookmarksDidSelect(url: url)
}
private func dismiss() {
dismiss(animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let viewController = segue.destination as? FavoritesViewController {
viewController.delegate = self
favoritesController = viewController
}
}
}
extension BookmarksViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
guard !searchText.isEmpty else {
if tableView.dataSource !== dataSource {
finishSearching()
}
return
}
if dataSource !== searchDataSource {
prepareForSearching()
tableView.dataSource = searchDataSource
}
searchDataSource.performSearch(searchText)
tableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
finishSearching()
}
}
extension BookmarksViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
finishEditing()
}
}
extension BookmarksViewController: Themable {
func decorate(with theme: Theme) {
decorateNavigationBar(with: theme)
decorateToolbar(with: theme)
overrideSystemTheme(with: theme)
searchController?.searchBar.searchTextField.textColor = theme.searchBarTextColor
tableView.backgroundColor = theme.backgroundColor
tableView.separatorColor = theme.tableCellSeparatorColor
navigationController?.view.backgroundColor = tableView.backgroundColor
tableView.reloadData()
}
}
extension BookmarksViewController: UIDocumentPickerDelegate {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let url = urls.first, let data = try? Data(contentsOf: url), let contents = String(data: data, encoding: .utf8) else {
ActionMessageView.present(message: UserText.importBookmarksFailedMessage)
return
}
importBookmarks(fromHtml: contents)
}
}
extension BookmarksViewController: FavoritesViewControllerDelegate {
func favoritesViewController(_ controller: FavoritesViewController, didSelectFavorite favorite: BookmarkEntity) {
select(bookmark: favorite)
}
func favoritesViewController(_ controller: FavoritesViewController, didRequestEditFavorite favorite: BookmarkEntity) {
performSegue(withIdentifier: "AddOrEditBookmarkFolder", sender: favorite.objectID)
}
}
// swiftlint:enable type_body_length
// swiftlint:enable file_length