1import UIKit
2
3extension Notebook {
4 /// Whether the notebook keeps a recycle bin: an open folder does, even with no sections
5 /// left, and a lone section, listed by its file's path or none, doesn't.
6 var hasRecycleBin: Bool { handle != nil && !tabs.contains { $0.path.isEmpty || $0.path.hasPrefix("/") } }
7}
8
9/// OneNote's Notebook Recycle Bin: the pages and sections deleted from a notebook, each
10/// restored to a section or folder the reader picks.
11final class RecycleBinViewController: UITableViewController {
12 private static let deletedPages = "OneNote_RecycleBin/OneNote_DeletedPages.one"
13
14 private let notebook: Notebook
15 /// Deleted Pages, open while the bin shows.
16 private var deleted: Section?
17 private var sections: [Tab] = []
18 private var observers: [NSObjectProtocol] = []
19
20 /// Shows `notebook`'s bin as a sheet over the controller on top of `window`.
21 static func present(_ notebook: Notebook, in window: UIWindow?) {
22 var top = window?.rootViewController
23 while let presented = top?.presentedViewController { top = presented }
24 let navigation = UINavigationController(rootViewController: RecycleBinViewController(notebook: notebook))
25 navigation.sheetPresentationController?.detents = [.medium(), .large()]
26 navigation.sheetPresentationController?.prefersGrabberVisible = true
27 top?.present(navigation, animated: true)
28 }
29
30 private init(notebook: Notebook) {
31 self.notebook = notebook
32 super.init(style: .insetGrouped)
33 title = "Recycle Bin"
34 }
35
36 required init?(coder: NSCoder) { fatalError() }
37
38 deinit { observers.forEach(NotificationCenter.default.removeObserver) }
39
40 override func viewDidLoad() {
41 super.viewDidLoad()
42 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "binned")
43 navigationItem.rightBarButtonItem = UIBarButtonItem(
44 systemItem: .done, primaryAction: UIAction { [weak self] _ in self?.dismiss(animated: true) })
45 observers = [
46 NotificationCenter.default.addObserver(forName: Section.changed, object: nil, queue: .main) { [weak self] note in
47 if let self, note.object as AnyObject? === deleted { show() }
48 },
49 NotificationCenter.default.addObserver(forName: Notebook.listed, object: notebook, queue: .main) {
50 [weak self] _ in self?.reload()
51 },
52 ]
53 // Each row's Restore button takes its size as the row is made.
54 registerForTraitChanges([UITraitPreferredContentSizeCategory.self]) { (self: Self, _) in
55 self.tableView.reloadData()
56 }
57 var loading = UIContentUnavailableConfiguration.loading()
58 loading.text = "Opening…"
59 contentUnavailableConfiguration = loading
60 reload()
61 }
62
63 private var pages: [Row] { deleted?.rows ?? [] }
64
65 private func reload() {
66 guard let library = notebook.handle else { return failed(notebook.problem) }
67 let pointer = Int(bitPattern: library)
68 background({ decode([Tab].self, sb_library_recycle_bin(OpaquePointer(bitPattern: pointer))) }) { [weak self] tabs in
69 guard let self else { return }
70 guard let tabs else { return failed(nil) }
71 sections = tabs.filter { $0.path != Self.deletedPages }
72 guard deleted == nil, let tab = tabs.first(where: { $0.path == Self.deletedPages }) else { return show() }
73 Section.open(tab, of: notebook) { [weak self] section, problem in
74 guard let section else { return self?.failed(problem) ?? () }
75 self?.deleted = section
76 self?.show()
77 }
78 }
79 }
80
81 /// Says the bin can't be read, rather than that it is empty.
82 private func failed(_ problem: String?) {
83 var failed = UIContentUnavailableConfiguration.empty()
84 failed.text = "Can’t Open Recycle Bin"
85 failed.secondaryText = problem ?? "Check that the notebook can be reached, then try again."
86 contentUnavailableConfiguration = failed
87 }
88
89 private func show() {
90 tableView.reloadData()
91 var empty = UIContentUnavailableConfiguration.empty()
92 empty.image = UIImage(systemName: "trash")
93 empty.text = "No Deleted Pages or Sections"
94 empty.secondaryText = "Pages and sections you delete appear here."
95 contentUnavailableConfiguration = pages.isEmpty && sections.isEmpty ? empty : nil
96 }
97
98 /// The table's groups: Deleted Pages, then Deleted Sections, each where it has rows.
99 private var groups: [Int] { [0, 1].filter { $0 == 0 ? !pages.isEmpty : !sections.isEmpty } }
100
101 override func numberOfSections(in tableView: UITableView) -> Int { groups.count }
102
103 override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
104 groups[section] == 0 ? "Deleted Pages" : "Deleted Sections"
105 }
106
107 override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
108 section == groups.count - 1 ? "Content here is deleted after 60 days." : nil
109 }
110
111 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
112 groups[section] == 0 ? pages.count : sections.count
113 }
114
115 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
116 let cell = tableView.dequeueReusableCell(withIdentifier: "binned", for: indexPath)
117 var content = cell.defaultContentConfiguration()
118 if groups[indexPath.section] == 0 {
119 let page = pages[indexPath.row]
120 content.text = page.title.isEmpty ? "Untitled Page" : page.title
121 content.image = UIImage(systemName: "doc.text")
122 } else {
123 let tab = sections[indexPath.row]
124 content.text = tab.name
125 content.image = UIImage(systemName: "rectangle.portrait.fill")
126 content.imageProperties.tintColor = tab.uiColor
127 }
128 cell.contentConfiguration = content
129 cell.selectionStyle = .none
130 var restore = UIButton.Configuration.plain()
131 restore.title = "Restore"
132 let button = UIButton(configuration: restore)
133 button.menu = menu(at: indexPath)
134 button.showsMenuAsPrimaryAction = true
135 button.accessibilityLabel = "Restore \(content.text ?? "")"
136 button.sizeToFit()
137 cell.accessoryView = button
138 return cell
139 }
140
141 override func tableView(
142 _ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint
143 ) -> UIContextMenuConfiguration? {
144 let menu = menu(at: indexPath)
145 return UIContextMenuConfiguration(actionProvider: { _ in menu })
146 }
147
148 /// Restore To: the notebook's sections for a page, its folders for a section, as the
149 /// desktop's Restore To offers them.
150 private func menu(at indexPath: IndexPath) -> UIMenu {
151 let place = { (path: String) in path.split(separator: "/").joined(separator: " › ") }
152 guard groups[indexPath.section] == 1 else {
153 let page = pages[indexPath.row].id
154 let choices = notebook.sections(besides: Self.deletedPages).map { tab in
155 UIAction(title: place(tab.group.isEmpty ? tab.name : tab.group + "/" + tab.name)) { [notebook] _ in
156 Arranging.move(page: page, of: notebook, from: Self.deletedPages, to: tab.path)
157 }
158 }
159 let none = UIAction(title: "No Sections", subtitle: "Add or restore a section first", attributes: .disabled) { _ in }
160 return UIMenu(title: "Restore To", children: choices.isEmpty ? [none] : choices)
161 }
162 let path = sections[indexPath.row].path
163 let file = path.split(separator: "/").last.map(String.init) ?? path
164 let choices = ([""] + notebook.groups).map { folder in
165 // A section of the same file name there would refuse it, as the file systems
166 // notebooks live on ignore case.
167 let taken = notebook.entries(in: folder).contains {
168 ($0.split(separator: "/").last.map(String.init) ?? $0).caseInsensitiveCompare(file) == .orderedSame
169 }
170 return UIAction(
171 title: folder.isEmpty ? notebook.name : place(folder),
172 subtitle: taken ? "A section with this name is already here" : nil, attributes: taken ? .disabled : []
173 ) { [notebook] _ in Arranging.place(path, of: notebook, in: folder) }
174 }
175 return UIMenu(title: "Restore To", children: choices)
176 }
177}