1import UIKit
2import UniformTypeIdentifiers
3
4/// The places notebooks are kept, each listing its notebooks with their sections, as Files
5/// lists its locations and Notes each account's folders.
6final class NotebooksViewController: UICollectionViewController, UIDocumentPickerDelegate {
7 private let listInputView = UIView(frame: .zero)
8 override var inputView: UIView? { listInputView }
9
10 enum Location: Hashable {
11 /// Snowbound's folder in iCloud Drive, where new notebooks go while iCloud Drive is on.
12 case icloud
13 /// Snowbound's Documents, which Files shows as Snowbound's folder.
14 case onDevice
15 /// Notebooks opened from Files or a server.
16 case elsewhere
17 }
18
19 enum Item: Hashable {
20 case location(Location)
21 case notebook(String)
22 /// A section group, by its `/`-separated path.
23 case group(notebook: String, path: String)
24 case section(notebook: String, path: String)
25 /// Opening, or why the notebook cannot be.
26 case status(notebook: String)
27 }
28
29 var dataSource: UICollectionViewDiffableDataSource<Location, Item>!
30 private var collapsed: Set<Item> = []
31 /// What each notebook's row shows of its sync status, by notebook id.
32 private var attention: [String: Sync.Attention] = [:]
33 private var selected: Item?
34 var onOpen: ((Tab, Notebook) -> Void)?
35
36 private static let device = "On My \(UIDevice.current.model)"
37
38 init() {
39 super.init(collectionViewLayout: UICollectionViewFlowLayout())
40 title = "Notebooks"
41 navigationItem.largeTitleDisplayMode = .always
42 }
43
44 required init?(coder: NSCoder) { fatalError() }
45
46 override func viewDidLoad() {
47 super.viewDidLoad()
48 collectionView.collectionViewLayout = UICollectionViewCompositionalLayout { [weak self] _, environment in
49 let compact = environment.traitCollection.horizontalSizeClass == .compact
50 var list = UICollectionLayoutListConfiguration(appearance: compact ? .insetGrouped : .sidebar)
51 list.headerMode = .firstItemInSection
52 list.trailingSwipeActionsConfigurationProvider = { indexPath in
53 guard let self, !self.isEditing, let item = self.dataSource.itemIdentifier(for: indexPath) else { return nil }
54 if case .notebook(let id) = item, let notebook = self.notebook(id) {
55 return UISwipeActionsConfiguration(actions: self.swipeActions(for: notebook, at: indexPath))
56 }
57 guard item == .location(.onDevice) else { return nil }
58 let hide = UIContextualAction(style: .normal, title: "Hide") { [weak self] _, _, done in
59 self?.showOnDevice(false)
60 done(true)
61 }
62 hide.image = UIImage(systemName: "eye.slash")
63 return UISwipeActionsConfiguration(actions: [hide])
64 }
65 return NSCollectionLayoutSection.list(using: list, layoutEnvironment: environment)
66 }
67 let cell = UICollectionView.CellRegistration<UICollectionViewListCell, Item> { [weak self] cell, _, item in
68 self?.configure(cell, item)
69 self?.arranging(cell, item)
70 }
71 dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { view, indexPath, item in
72 view.dequeueConfiguredReusableCell(using: cell, for: indexPath, item: item)
73 }
74 dataSource.sectionSnapshotHandlers.willCollapseItem = { [weak self] in self?.collapsed.insert($0) }
75 dataSource.sectionSnapshotHandlers.willExpandItem = { [weak self] in self?.collapsed.remove($0) }
76
77 let add = UIMenu(children: [
78 UIDeferredMenuElement.uncached { [weak self] provide in
79 guard let self else { return provide([]) }
80 var places: [UIMenuElement] = []
81 if ICloud.documents != nil {
82 places.append(
83 UIAction(title: "iCloud Drive", image: UIImage(systemName: "icloud")) { [weak self] _ in
84 self?.newNotebook(inCloud: true)
85 })
86 } else if !ICloud.signedIn {
87 places.append(
88 UIAction(title: "Turn On iCloud Drive", image: UIImage(systemName: "icloud")) { _ in
89 if let settings = URL(string: UIApplication.openSettingsURLString) {
90 UIApplication.shared.open(settings)
91 }
92 })
93 }
94 places.append(
95 UIAction(title: Self.device, image: UIImage(systemName: "iphone")) { [weak self] _ in
96 self?.newNotebook(inCloud: false)
97 })
98 var actions: [UIMenuElement] = [
99 UIMenu(title: "New Notebook", options: .displayInline, children: places),
100 UIAction(title: "Open from Server", image: UIImage(systemName: "server.rack")) { [weak self] _ in
101 self?.connect()
102 },
103 UIAction(title: "Open Folder", image: UIImage(systemName: "folder")) { [weak self] _ in
104 self?.openFolder()
105 },
106 ]
107 let copied = Notebooks.onDevice.contains { $0.source == .documents(path: Notebooks.guide) }
108 if Notebooks.guideOffered && !copied {
109 actions.append(
110 UIAction(title: "Open the Snowbound Guide", image: UIImage(systemName: "book")) { [weak self] _ in
111 self?.openGuide()
112 })
113 }
114 provide(actions)
115 }
116 ])
117 let more = UIMenu(children: [
118 UIDeferredMenuElement.uncached { [weak self] provide in
119 var actions: [UIMenuElement] = [
120 UIAction(title: "Sync Status", image: UIImage(systemName: "arrow.triangle.2.circlepath")) {
121 [weak self] _ in self.map(SyncViewController.present)
122 }
123 ]
124 if !Notebooks.showsOnDevice {
125 actions.append(
126 UIAction(title: "Show \(Self.device)", image: UIImage(systemName: "eye")) { [weak self] _ in
127 self?.showOnDevice(true)
128 })
129 }
130 actions.append(
131 UIAction(title: "Personalize", image: UIImage(systemName: "person.crop.circle")) { [weak self] _ in
132 guard let self else { return }
133 Author.ask(from: self) {}
134 })
135 actions.append(Appearance.menu())
136 actions.append(Editing.fontMenu())
137 actions.append(Editing.markdownAction())
138 provide(actions)
139 }
140 ])
141 navigationItem.rightBarButtonItems = [
142 UIBarButtonItem(title: "Add Notebook", image: UIImage(systemName: "plus"), menu: add),
143 UIBarButtonItem(title: "More", image: UIImage(systemName: "ellipsis"), menu: more),
144 ]
145 navigationItem.searchController = SearchViewController.controller()
146 setUpArranging()
147 if #available(iOS 26, *) {
148 // Search sits in the bottom toolbar, as Notes and Files put it.
149 navigationItem.preferredSearchBarPlacement = .integrated
150 }
151 updateSelectionActions()
152 for name in [Sync.changed, Section.changed] {
153 NotificationCenter.default.addObserver(self, selector: #selector(refreshSync(_:)), name: name, object: nil)
154 }
155 NotificationCenter.default.addObserver(forName: Notebook.listed, object: nil, queue: .main) { [weak self] _ in
156 guard let self else { return }
157 reload(animated: true)
158 var shown = dataSource.snapshot()
159 shown.reconfigureItems(shown.itemIdentifiers)
160 dataSource.apply(shown, animatingDifferences: false)
161 }
162 reload()
163 }
164
165 override func viewWillAppear(_ animated: Bool) {
166 super.viewWillAppear(animated)
167 navigationController?.navigationBar.prefersLargeTitles = true
168 navigationController?.setToolbarHidden(toolbarItems?.isEmpty != false, animated: false)
169 }
170
171 func notebook(_ id: String) -> Notebook? { Notebooks.all.first { $0.id == id } }
172
173 func reload(animated: Bool = false) {
174 guard isViewLoaded else { return }
175 let selection = collectionView.indexPathsForSelectedItems?.compactMap { dataSource.itemIdentifier(for: $0) } ?? []
176 if Prototype.welcome {
177 let welcome = Prototype.welcome(
178 new: { [weak self] in self?.newNotebook(inCloud: ICloud.documents != nil) },
179 openFolder: { [weak self] in self?.openFolder() }, connect: { [weak self] in self?.connect() })
180 contentUnavailableConfiguration = welcome
181 if welcome != nil { return dataSource.apply(.init(), animatingDifferences: false) }
182 }
183 // A place with no notebooks is left out; the Add Notebook menu reaches every place.
184 let locations: [(Location, [Notebook])] = [
185 (.icloud, Notebooks.inCloud), (.onDevice, Notebooks.onDevice), (.elsewhere, Notebooks.elsewhere),
186 ].filter { !$0.1.isEmpty }
187 if locations.isEmpty {
188 var empty = UIContentUnavailableConfiguration.empty()
189 empty.text = "No Notebooks"
190 empty.secondaryText = "Create a notebook, or open one from a server or folder."
191 var button = UIButton.Configuration.borderedProminent()
192 button.title = "New Notebook"
193 empty.button = button
194 empty.buttonProperties.primaryAction = UIAction { [weak self] _ in
195 self?.newNotebook(inCloud: ICloud.documents != nil)
196 }
197 contentUnavailableConfiguration = empty
198 } else {
199 contentUnavailableConfiguration = nil
200 }
201 // Locations kept keep their rows, so a move animates.
202 if dataSource.snapshot().sectionIdentifiers != locations.map(\.0) {
203 var sections = NSDiffableDataSourceSnapshot<Location, Item>()
204 sections.appendSections(locations.map(\.0))
205 dataSource.apply(sections, animatingDifferences: false)
206 }
207 for (location, notebooks) in locations {
208 var list = NSDiffableDataSourceSectionSnapshot<Item>()
209 let header = Item.location(location)
210 list.append([header])
211 list.append(notebooks.map { .notebook($0.id) }, to: header)
212 for notebook in notebooks {
213 let parent = Item.notebook(notebook.id)
214 guard notebook.handle != nil else {
215 list.append([.status(notebook: notebook.id)], to: parent)
216 continue
217 }
218 for tab in notebook.tabs {
219 var parent = parent
220 var path = ""
221 for part in tab.group.split(separator: "/") {
222 path += (path.isEmpty ? "" : "/") + part
223 let group = Item.group(notebook: notebook.id, path: path)
224 if !list.contains(group) { list.append([group], to: parent) }
225 parent = group
226 }
227 list.append([.section(notebook: notebook.id, path: tab.path)], to: parent)
228 }
229 }
230 list.expand(list.items.filter { !collapsed.contains($0) })
231 dataSource.apply(list, to: location, animatingDifferences: animated)
232 }
233 showSelection()
234 if isEditing {
235 for item in selection {
236 if let index = dataSource.indexPath(for: item) {
237 collectionView.selectItem(at: index, animated: false, scrollPosition: [])
238 }
239 }
240 updateSelectionActions()
241 }
242 refreshSync()
243 }
244
245 /// Reads every notebook's sync status, marks the rows it changed, and tells of a notebook
246 /// that has just stopped syncing with edits waiting.
247 @objc private func refreshSync(_ notification: Notification? = nil) {
248 guard notification?.userInfo?["unchanged"] as? Bool != true else { return }
249 Sync.status { [weak self] notebooks in
250 guard let self else { return }
251 var changed: [Item] = []
252 for (notebook, sections) in notebooks {
253 let before = attention[notebook.id]
254 let after = Sync.attention(sections)
255 guard before != after else { continue }
256 attention[notebook.id] = after
257 changed.append(.notebook(notebook.id))
258 // The list is off screen on a phone while a page shows.
259 if let toast = Sync.toast(notebook.name, from: before, to: after),
260 let window = splitViewController?.view.window ?? view.window
261 {
262 SyncToast.show(toast.title, toast.detail, in: window) { [weak self] in
263 self.map(SyncViewController.present)
264 }
265 }
266 }
267 var shown = dataSource.snapshot()
268 let items = changed.filter { shown.indexOfItem($0) != nil }
269 guard !items.isEmpty else { return }
270 shown.reconfigureItems(items)
271 dataSource.apply(shown, animatingDifferences: false)
272 }
273 }
274
275 /// Lists Documents and iCloud Drive again and opens the notebooks new there; `opened` runs
276 /// as each opens.
277 func rescan(opened: ((Notebook) -> Void)? = nil) {
278 for notebook in Notebooks.scanICloud() + Notebooks.scan() {
279 notebook.open { [weak self] in
280 self?.reload()
281 opened?(notebook)
282 }
283 }
284 reload()
285 }
286
287 /// Lists the notebooks again and opens the first section of the one from `source`.
288 private func rescan(opening source: Source) {
289 rescan { [weak self] notebook in
290 guard notebook.source == source, let tab = notebook.tabs.first(where: \.readable) else { return }
291 self?.onOpen?(tab, notebook)
292 }
293 }
294
295 private func showOnDevice(_ shown: Bool) {
296 Notebooks.showsOnDevice = shown
297 rescan()
298 }
299
300 func select(_ tab: Tab, of notebook: Notebook) {
301 selected = .section(notebook: notebook.id, path: tab.path)
302 showSelection()
303 }
304
305 /// Marks the open section, as the sidebar of a wide window keeps it.
306 private func showSelection() {
307 guard !isEditing, let selected, let indexPath = dataSource.indexPath(for: selected) else { return }
308 collectionView.selectItem(at: indexPath, animated: false, scrollPosition: [])
309 }
310
311 override func setEditing(_ editing: Bool, animated: Bool) {
312 super.setEditing(editing, animated: animated)
313 for index in collectionView.indexPathsForSelectedItems ?? [] {
314 collectionView.deselectItem(at: index, animated: false)
315 }
316 collectionView.isEditing = editing
317 collectionView.dragInteractionEnabled = !editing
318 if !editing { showSelection() }
319 updateSelectionActions()
320 }
321
322 private func updateSelectionActions() {
323 guard isEditing else {
324 let corner = Prototype.quickNote ? [QuickNote.item()] : []
325 if #available(iOS 26, *) {
326 toolbarItems = [navigationItem.searchBarPlacementBarButtonItem] + (corner.isEmpty ? [] : [.fixedSpace()] + corner)
327 } else {
328 toolbarItems = corner.isEmpty ? [] : [.flexibleSpace()] + corner
329 }
330 navigationController?.setToolbarHidden(toolbarItems?.isEmpty != false, animated: false)
331 return
332 }
333 let selection = (collectionView.indexPathsForSelectedItems ?? []).sorted().compactMap {
334 dataSource.itemIdentifier(for: $0)
335 }
336 var actions: [UIMenuElement] = []
337 let notebooks = selection.compactMap { item -> Notebook? in
338 guard case .notebook(let id) = item else { return nil }
339 return notebook(id)
340 }
341 if !selection.isEmpty, notebooks.count == selection.count {
342 let folders = notebooks.compactMap { folder(of: $0) }
343 if folders.count == notebooks.count {
344 actions.append(UIAction(title: "Share", image: UIImage(systemName: "square.and.arrow.up")) { [weak self] _ in
345 guard let self else { return }
346 let sheet = UIActivityViewController(activityItems: folders, applicationActivities: nil)
347 sheet.popoverPresentationController?.barButtonItem = toolbarItems?.last
348 present(sheet, animated: true)
349 })
350 let deletable = notebooks.allSatisfy { $0.handle != nil }
351 actions.append(UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: deletable ? .destructive : [.destructive, .disabled]) { [weak self] _ in
352 self?.delete(notebooks)
353 })
354 } else if notebooks.allSatisfy({ notebook in Notebooks.elsewhere.contains { $0 === notebook } }) {
355 actions.append(UIAction(title: "Close", image: UIImage(systemName: "xmark.circle")) { [weak self] _ in
356 for notebook in notebooks {
357 for scene in UIApplication.shared.connectedScenes {
358 (scene.delegate as? SceneDelegate)?.close(notebook)
359 }
360 Notebooks.remove(notebook)
361 }
362 self?.reload()
363 })
364 }
365 }
366 let entries = selection.compactMap { item -> (Notebook, String)? in
367 switch item {
368 case .section(let id, let path), .group(let id, let path): return notebook(id).map { ($0, path) }
369 default: return nil
370 }
371 }
372 if let notebook = entries.first?.0, entries.count == selection.count,
373 entries.allSatisfy({ $0.0 === notebook })
374 {
375 let paths = entries.map(\.1).filter { path in !entries.contains { path.hasPrefix($0.1 + "/") } }
376 let destinations = notebook.destinations(of: paths[0]).filter { destination in
377 paths.allSatisfy { notebook.destinations(of: $0).contains(destination) }
378 }
379 if !destinations.isEmpty {
380 actions.append(UIMenu(title: "Move", image: UIImage(systemName: "folder"), children: destinations.map { folder in
381 UIAction(title: folder.isEmpty ? notebook.name : folder.split(separator: "/").joined(separator: " › ")) { [weak self] _ in
382 self?.setEditing(false, animated: true)
383 func move(_ remaining: ArraySlice<String>) {
384 guard let path = remaining.first else { return }
385 Arranging.place(path, of: notebook, in: folder) { move(remaining.dropFirst()) }
386 }
387 move(paths[...])
388 }
389 }))
390 }
391 if notebook.hasRecycleBin {
392 actions.append(UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: .destructive) { [weak self] _ in
393 self?.confirmRecycling(paths, of: notebook)
394 })
395 }
396 }
397 let action = UIBarButtonItem(title: "Actions", image: UIImage(systemName: "ellipsis.circle"), menu: UIMenu(children: actions))
398 action.isEnabled = !actions.isEmpty
399 toolbarItems = [.flexibleSpace(), action]
400 navigationController?.setToolbarHidden(false, animated: false)
401 }
402
403 private func delete(_ notebooks: [Notebook]) {
404 let alert = UIAlertController(
405 title: notebooks.count == 1 ? "Delete Notebook?" : "Delete \(notebooks.count) Notebooks?",
406 message: notebooks.count == 1
407 ? "It moves to Recently Deleted in Files. If it can’t, it’s deleted permanently."
408 : "They move to Recently Deleted in Files. Any that can’t are deleted permanently.",
409 preferredStyle: .alert)
410 alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
411 alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { [weak self] _ in
412 guard let self, let release = Arranging.reserve() else { return }
413 setEditing(false, animated: true)
414 collectionView.isUserInteractionEnabled = false
415 for notebook in notebooks {
416 for scene in UIApplication.shared.connectedScenes {
417 (scene.delegate as? SceneDelegate)?.close(notebook)
418 }
419 }
420 background({ () -> (String?, [Notebook]) in
421 // No folder is removed until every notebook has published its edits.
422 for notebook in notebooks {
423 guard let handle = notebook.handle else {
424 return ("\(notebook.name): Open this notebook before deleting it.", notebooks)
425 }
426 var error: UnsafeMutablePointer<CChar>?
427 let closed = sb_library_close(handle, 10, &error)
428 _ = take(error)
429 if !closed {
430 return ("\(notebook.name): Changes haven’t been saved. Check that the notebook is reachable and writable, then try again.", notebooks)
431 }
432 }
433 var failed: [Notebook] = []
434 var problems: [String] = []
435 for notebook in notebooks {
436 guard let folder = self.folder(of: notebook) else { continue }
437 do {
438 do { try FileManager.default.trashItem(at: folder, resultingItemURL: nil) }
439 catch { try FileManager.default.removeItem(at: folder) }
440 } catch {
441 failed.append(notebook)
442 problems.append("\(notebook.name): \(error.localizedDescription)")
443 }
444 }
445 return (problems.isEmpty ? nil : problems.joined(separator: "\n\n"), failed)
446 }) { [weak self] problem, failed in
447 release()
448 self?.collectionView.isUserInteractionEnabled = true
449 for notebook in notebooks { notebook.pause() }
450 for notebook in failed { notebook.open { self?.reload() } }
451 self?.rescan()
452 if let problem { self?.alert("Can’t Delete", problem) }
453 }
454 })
455 present(alert, animated: true)
456 }
457
458 private func configure(_ cell: UICollectionViewListCell, _ item: Item) {
459 var content = cell.defaultContentConfiguration()
460 var accessories: [UICellAccessory] = []
461 switch item {
462 case .location(let location):
463 content.text =
464 switch location {
465 case .icloud: "iCloud Drive"
466 case .onDevice: Self.device
467 case .elsewhere: "Other Locations"
468 }
469 accessories = [.outlineDisclosure(options: .init(style: .header))]
470 case .notebook(let id):
471 guard let notebook = notebook(id) else { break }
472 content.text = notebook.name
473 content.image = .notebook(notebook.color)
474 var details: [String] = []
475 if case .server(let server) = notebook.source { details.append(server.host) }
476 if let state = attention[id]?.state {
477 details.append(Sync.label(state))
478 let mark = UIImageView(image: UIImage(systemName: Sync.symbol(state)))
479 mark.tintColor = state == .notConnected || Sync.offline ? .secondaryLabel : .systemOrange
480 mark.preferredSymbolConfiguration = UIImage.SymbolConfiguration(textStyle: .body)
481 accessories.append(.customView(configuration: .init(customView: mark, placement: .trailing(displayed: .always))))
482 }
483 content.secondaryText = details.isEmpty ? nil : details.joined(separator: " · ")
484 content.secondaryTextProperties.color = .secondaryLabel
485 let more = UIButton(type: .system)
486 more.setImage(UIImage(systemName: "ellipsis.circle"), for: .normal)
487 more.accessibilityLabel = "More"
488 more.showsMenuAsPrimaryAction = true
489 more.menu = menu(for: notebook)
490 accessories += [
491 .customView(configuration: .init(customView: more, placement: .trailing(displayed: .always))),
492 .outlineDisclosure(options: .init(style: .cell)),
493 ]
494 case .group(_, let path):
495 content.text = path.split(separator: "/").last.map(String.init)
496 content.image = UIImage(systemName: "folder")
497 content.textProperties.color = .secondaryLabel
498 accessories = [.outlineDisclosure(options: .init(style: .cell))]
499 case .section(let id, let path):
500 guard let tab = notebook(id)?.tabs.first(where: { $0.path == path }) else { break }
501 content.text = tab.name
502 content.image = UIImage(
503 systemName: tab.readable ? "rectangle.portrait.fill" : tab.downloading ? "icloud.and.arrow.down" : "lock.fill")
504 content.imageProperties.tintColor = tab.uiColor
505 if tab.locked {
506 content.secondaryText = "Password protected"
507 } else if !tab.readable {
508 content.secondaryText = tab.downloading ? "Downloading…" : tab.problem ?? "Can’t be opened here"
509 content.textProperties.color = .secondaryLabel
510 }
511 case .status(let id):
512 if let problem = notebook(id)?.problem {
513 content.text = "Can’t Open Notebook"
514 content.secondaryText = problem
515 content.image = UIImage(systemName: "exclamationmark.triangle")
516 content.imageProperties.tintColor = .systemOrange
517 let retry = UIImageView(image: UIImage(systemName: "arrow.clockwise"))
518 accessories = [.customView(configuration: .init(customView: retry, placement: .trailing()))]
519 } else {
520 content.text = "Opening…"
521 content.textProperties.color = .secondaryLabel
522 let spinner = UIActivityIndicatorView(style: .medium)
523 spinner.startAnimating()
524 accessories = [.customView(configuration: .init(customView: spinner, placement: .trailing()))]
525 }
526 }
527 cell.contentConfiguration = content
528 cell.accessories = accessories
529 }
530
531 private func menu(for notebook: Notebook) -> UIMenu {
532 // Why the notebook isn't syncing and when it last did, while it isn't.
533 let status: [UIMenuElement] =
534 attention[notebook.id].map { attention in
535 let details = UIAction(
536 title: Sync.label(attention.state), subtitle: attention.detail.isEmpty ? nil : attention.detail,
537 image: UIImage(systemName: Sync.symbol(attention.state))
538 ) { [weak self] _ in self.map(SyncViewController.present) }
539 let now = UIAction(title: "Sync Now", image: UIImage(systemName: "arrow.clockwise")) { _ in
540 if let handle = notebook.handle { sb_library_sync_now(handle) }
541 }
542 return [UIMenu(options: .displayInline, children: [details, now])]
543 } ?? []
544 var actions = [
545 UIAction(title: "New Section", image: UIImage(systemName: "plus.rectangle.portrait")) {
546 [weak self] _ in self?.newSection(in: notebook)
547 },
548 UIAction(title: "Tags Summary", image: UIImage(systemName: "tag")) { [weak self] _ in
549 guard let self else { return }
550 (view.window?.windowScene?.delegate as? SceneDelegate)?.showTags(of: notebook, from: self)
551 },
552 ]
553 if notebook.hasRecycleBin {
554 actions.append(
555 UIAction(title: "Notebook Recycle Bin", image: UIImage(systemName: "trash")) { [weak self] _ in
556 RecycleBinViewController.present(notebook, in: self?.view.window)
557 })
558 }
559 // A notebook On My iPhone is its folder there, handled as Files handles a folder.
560 guard let folder = folder(of: notebook) else {
561 var extra: [UIMenuElement] = []
562 if case .server = notebook.source {
563 extra.append(
564 UIAction(title: "Change Server Address", image: UIImage(systemName: "server.rack")) { [weak self] _ in
565 self?.changeServer(of: notebook)
566 })
567 }
568 let image = UIImage(systemName: "xmark.circle")
569 let close = UIAction(title: "Close Notebook", image: image, attributes: .destructive) { [weak self] _ in
570 Notebooks.remove(notebook)
571 self?.reload()
572 }
573 return UIMenu(children: status + actions + extra + [close])
574 }
575 let file = [
576 UIAction(title: "Rename", image: UIImage(systemName: "pencil")) { [weak self] _ in
577 self?.rename(folder, of: notebook)
578 },
579 UIAction(title: "Duplicate", image: UIImage(systemName: "plus.square.on.square")) { [weak self] _ in
580 self?.duplicate(folder, of: notebook)
581 },
582 UIAction(title: "Share", image: UIImage(systemName: "square.and.arrow.up")) { [weak self] _ in
583 self?.share(folder, from: notebook)
584 },
585 UIAction(title: "Show in Files", image: UIImage(systemName: "folder")) { _ in
586 // Files opens the folder a `shareddocuments` URL names.
587 if let url = URL(string: "shareddocuments://" + folder.path) { UIApplication.shared.open(url) }
588 },
589 ]
590 let delete = UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: .destructive) {
591 [weak self] _ in self?.delete(folder, of: notebook)
592 }
593 return UIMenu(children: status + [
594 UIMenu(options: .displayInline, children: actions), UIMenu(options: .displayInline, children: file), delete,
595 ])
596 }
597
598 private func swipeActions(for notebook: Notebook, at indexPath: IndexPath) -> [UIContextualAction] {
599 guard let folder = folder(of: notebook) else {
600 let close = UIContextualAction(style: .destructive, title: "Close") { [weak self] _, _, done in
601 Notebooks.remove(notebook)
602 self?.reload()
603 done(true)
604 }
605 close.image = UIImage(systemName: "xmark.circle")
606 return [close]
607 }
608 let delete = UIContextualAction(style: .destructive, title: "Delete") { [weak self] _, _, done in
609 self?.delete(folder, of: notebook)
610 done(true)
611 }
612 delete.image = UIImage(systemName: "trash")
613 let share = UIContextualAction(style: .normal, title: "Share") { [weak self] _, _, done in
614 self?.share(folder, from: notebook)
615 done(true)
616 }
617 share.image = UIImage(systemName: "square.and.arrow.up")
618 share.backgroundColor = .systemBlue
619 return [delete, share]
620 }
621
622 /// The notebook's folder or section file On My iPhone; nil for one opened elsewhere.
623 private func folder(of notebook: Notebook) -> URL? {
624 guard case .documents(let path) = notebook.source else { return nil }
625 return documentsDirectory.appendingPathComponent(path)
626 }
627
628 /// Publishes the notebook's edits and lets go of it, closing any section of it shown,
629 /// then runs `act`; refuses with why while an edit can't be published, as moving the
630 /// folder then would strand it.
631 private func close(_ notebook: Notebook, refusing title: String, then act: @escaping () -> Void) {
632 guard let release = Arranging.reserve() else { return }
633 for scene in UIApplication.shared.connectedScenes {
634 (scene.delegate as? SceneDelegate)?.close(notebook)
635 }
636 guard let handle = notebook.handle else {
637 defer { release() }
638 return act()
639 }
640 let pointer = Int(bitPattern: handle)
641 background({ () -> String? in
642 var error: UnsafeMutablePointer<CChar>?
643 let closed = sb_library_close(OpaquePointer(bitPattern: pointer), 10, &error)
644 let problem = take(error)
645 return closed ? nil : problem ?? ""
646 }) { [weak self] problem in
647 defer { release() }
648 if let problem {
649 self?.alert(title, problem)
650 return
651 }
652 notebook.pause()
653 act()
654 }
655 }
656
657 private func rename(_ folder: URL, of notebook: Notebook) {
658 let alert = UIAlertController(title: "Rename", message: nil, preferredStyle: .alert)
659 let isFile = folder.pathExtension.lowercased() == "one"
660 let rename = UIAlertAction(title: "Rename", style: .default) { [weak self, weak alert] _ in
661 let name = alert?.textFields?.first?.text?.trimmingCharacters(in: .whitespaces) ?? ""
662 let target = folder.deletingLastPathComponent().appendingPathComponent(
663 isFile ? name + "." + folder.pathExtension : name)
664 guard target != folder else { return }
665 guard !FileManager.default.fileExists(atPath: target.path) else {
666 self?.alert("“\(name)” Already Exists", "Choose a different name.")
667 return
668 }
669 self?.close(notebook, refusing: "Can’t Rename") {
670 do {
671 try FileManager.default.moveItem(at: folder, to: target)
672 _ = sb_notebook_moved(cacheDirectory.path, folder.path, target.path, nil)
673 } catch {
674 self?.alert("Can’t Rename", error.localizedDescription)
675 }
676 self?.rescan()
677 }
678 }
679 alert.addTextField { field in
680 field.text = folder.deletingPathExtension().lastPathComponent
681 field.autocapitalizationType = .words
682 field.clearButtonMode = .whileEditing
683 NotificationCenter.default.addObserver(
684 forName: UITextField.textDidChangeNotification, object: field, queue: .main
685 ) { _ in rename.isEnabled = Self.namesFile(field) }
686 }
687 alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
688 alert.addAction(rename)
689 alert.preferredAction = rename
690 present(alert, animated: true)
691 }
692
693 /// Whether `field` holds a name a notebook's folder can take.
694 private static func namesFile(_ field: UITextField) -> Bool {
695 let name = (field.text ?? "").trimmingCharacters(in: .whitespaces)
696 return !name.isEmpty && !name.hasPrefix(".") && !name.contains("/")
697 }
698
699 /// Copies the notebook beside itself, named as Files names a duplicate.
700 private func duplicate(_ folder: URL, of notebook: Notebook) {
701 // The copy takes what the open sections have stored.
702 for section in Section.all where section.notebook === notebook && !section.flush(10) {
703 return alert("Can’t Duplicate", "Some changes haven’t been saved to the notebook yet.")
704 }
705 let base = folder.deletingPathExtension().lastPathComponent
706 let ext = folder.pathExtension
707 var copy = folder
708 for n in 2... {
709 let name = base + " \(n)"
710 copy = folder.deletingLastPathComponent().appendingPathComponent(ext.isEmpty ? name : name + "." + ext)
711 if !FileManager.default.fileExists(atPath: copy.path) { break }
712 }
713 let target = copy
714 background({ () -> String? in
715 do { try FileManager.default.copyItem(at: folder, to: target) } catch { return error.localizedDescription }
716 return nil
717 }) { [weak self] problem in
718 if let problem { self?.alert("Can’t Duplicate", problem) }
719 self?.rescan()
720 }
721 }
722
723 private func share(_ folder: URL, from notebook: Notebook) {
724 let sheet = UIActivityViewController(activityItems: [folder], applicationActivities: nil)
725 if let popover = sheet.popoverPresentationController {
726 if let indexPath = dataSource.indexPath(for: .notebook(notebook.id)),
727 let cell = collectionView.cellForItem(at: indexPath)
728 {
729 popover.sourceView = cell
730 popover.sourceRect = cell.bounds
731 } else {
732 popover.sourceView = view
733 }
734 }
735 present(sheet, animated: true)
736 }
737
738 /// Moves the notebook to Recently Deleted, or, where the system keeps none, removes it
739 /// once confirmed.
740 private func delete(_ folder: URL, of notebook: Notebook) {
741 close(notebook, refusing: "Can’t Delete") { [weak self] in self?.remove(folder, of: notebook) }
742 }
743
744 private func remove(_ folder: URL, of notebook: Notebook) {
745 if (try? FileManager.default.trashItem(at: folder, resultingItemURL: nil)) != nil {
746 if let window = view.window {
747 SyncToast.show(
748 "“\(notebook.name)” Deleted", "Restore it from Recently Deleted in Files", symbol: "trash",
749 hint: "Opens Files", in: window
750 ) {
751 if let files = URL(string: "shareddocuments://" + folder.deletingLastPathComponent().path) {
752 UIApplication.shared.open(files)
753 }
754 }
755 }
756 return rescan()
757 }
758 let name = folder.deletingPathExtension().lastPathComponent
759 let alert = UIAlertController(
760 title: "Delete “\(name)”?", message: "This notebook will be deleted immediately. You can’t undo this action.",
761 preferredStyle: .alert)
762 alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { [weak self] _ in
763 notebook.open { self?.reload() }
764 })
765 alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { [weak self] _ in
766 self?.close(notebook, refusing: "Can’t Delete") {
767 do { try FileManager.default.removeItem(at: folder) } catch {
768 self?.alert("Can’t Delete", error.localizedDescription)
769 }
770 self?.rescan()
771 }
772 })
773 present(alert, animated: true)
774 }
775
776 override func collectionView(
777 _ collectionView: UICollectionView, contextMenuConfigurationForItemsAt indexPaths: [IndexPath], point: CGPoint
778 ) -> UIContextMenuConfiguration? {
779 guard !isEditing, indexPaths.count == 1, let item = dataSource.itemIdentifier(for: indexPaths[0]) else { return nil }
780 guard case .notebook(let id) = item, let notebook = notebook(id) else {
781 let actions = arrangeMenu(item) + deleteAction(item)
782 return actions.isEmpty ? nil : UIContextMenuConfiguration(actionProvider: { _ in UIMenu(children: actions) })
783 }
784 return UIContextMenuConfiguration(actionProvider: { [weak self] _ in
785 UIMenu(children: (self?.menu(for: notebook).children ?? []) + (self?.arrangeMenu(item) ?? []))
786 })
787 }
788
789 /// Delete for a section or group.
790 private func deleteAction(_ item: Item) -> [UIMenuElement] {
791 switch item {
792 case .section(let id, let path), .group(let id, let path):
793 guard let notebook = notebook(id), notebook.hasRecycleBin else { return [] }
794 return [
795 UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: .destructive) { [weak self] _ in
796 self?.confirmRecycling([path], of: notebook)
797 }
798 ]
799 default: return []
800 }
801 }
802
803 /// Moves the sections and groups at `paths` to the notebook's recycle bin once confirmed.
804 private func confirmRecycling(_ paths: [String], of notebook: Notebook) {
805 let path = paths[0]
806 let tab = notebook.tabs.first { $0.path == path }
807 let title = paths.count > 1
808 ? "Delete \(paths.count) Items?" : "Delete “\(tab?.name ?? path.split(separator: "/").last.map(String.init) ?? path)”?"
809 let message =
810 paths.count > 1 ? "They move to this notebook’s Recycle Bin."
811 : tab == nil ? "Its sections move to this notebook’s Recycle Bin." : "It moves to this notebook’s Recycle Bin."
812 let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
813 alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
814 alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { [weak self] _ in
815 self?.setEditing(false, animated: true)
816 self?.recycle(paths[...], of: notebook)
817 })
818 present(alert, animated: true)
819 }
820
821 private func recycle(_ paths: ArraySlice<String>, of notebook: Notebook) {
822 guard let path = paths.first, let library = notebook.handle, let release = Arranging.reserve() else { return }
823 for scene in UIApplication.shared.connectedScenes {
824 _ = (scene.delegate as? SceneDelegate)?.release(path, of: notebook)
825 }
826 let pointer = Int(bitPattern: library)
827 background({ sb_library_delete(OpaquePointer(bitPattern: pointer), path) }) { [weak self] deleted in
828 notebook.reload {
829 release()
830 NotificationCenter.default.post(name: Notebook.listed, object: notebook)
831 guard deleted else {
832 self?.alert("Can’t Delete", "Check that the notebook can be reached, then try again.")
833 return
834 }
835 self?.recycle(paths.dropFirst(), of: notebook)
836 }
837 }
838 }
839
840 override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
841 guard let item = dataSource.itemIdentifier(for: indexPath) else { return false }
842 if isEditing {
843 switch item {
844 case .notebook, .group, .section: return true
845 default: return false
846 }
847 }
848 switch item {
849 case .section(let id, let path):
850 let tab = notebook(id)?.tabs.first(where: { $0.path == path })
851 return tab?.readable == true || tab?.locked == true
852 case .status(let id):
853 guard let notebook = notebook(id), notebook.problem != nil else { return false }
854 let spinner = UIActivityIndicatorView(style: .medium)
855 spinner.startAnimating()
856 (collectionView.cellForItem(at: indexPath) as? UICollectionViewListCell)?.accessories = [
857 .customView(configuration: .init(customView: spinner, placement: .trailing()))
858 ]
859 notebook.open { [weak self] in self?.reload() }
860 case .notebook, .group:
861 // The row opens and closes, as a folder of Files' sidebar does.
862 guard let location = dataSource.sectionIdentifier(for: indexPath.section) else { return false }
863 var list = dataSource.snapshot(for: location)
864 if list.isExpanded(item) {
865 list.collapse([item])
866 collapsed.insert(item)
867 } else {
868 list.expand([item])
869 collapsed.remove(item)
870 }
871 dataSource.apply(list, to: location)
872 case .location: break
873 }
874 return false
875 }
876
877 override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
878 if isEditing { return updateSelectionActions() }
879 guard case .section(let id, let path) = dataSource.itemIdentifier(for: indexPath), let notebook = notebook(id),
880 let tab = notebook.tabs.first(where: { $0.path == path })
881 else { return }
882 if tab.locked { return unlock(tab, of: notebook, wrong: false) }
883 onOpen?(tab, notebook)
884 }
885
886 override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
887 if isEditing { updateSelectionActions() }
888 }
889
890 /// Asks for a protected section's password, as OneNote's Protected Section dialog does,
891 /// and opens it once unlocked.
892 private func unlock(_ tab: Tab, of notebook: Notebook, wrong: Bool) {
893 let alert = UIAlertController(
894 title: "Protected Section",
895 message: wrong ? "Password is incorrect." : "Section “\(tab.name)” is password protected.",
896 preferredStyle: .alert)
897 alert.addTextField { field in
898 field.isSecureTextEntry = true
899 field.placeholder = "Password"
900 }
901 alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
902 alert.addAction(UIAlertAction(title: "OK", style: .default) { [weak self, weak alert] _ in
903 let password = alert?.textFields?.first?.text ?? ""
904 notebook.unlock(tab.path, password: password) { unlocked in
905 self?.reload()
906 if unlocked, let opened = notebook.tabs.first(where: { $0.path == tab.path }) {
907 self?.onOpen?(opened, notebook)
908 } else {
909 self?.unlock(tab, of: notebook, wrong: true)
910 }
911 }
912 })
913 present(alert, animated: true)
914 }
915
916 private func add(_ notebook: Notebook) {
917 Notebooks.add(notebook)
918 openFirstSection(of: notebook)
919 }
920
921 private func openFirstSection(of notebook: Notebook) {
922 reload()
923 notebook.open { [weak self] in
924 self?.reload()
925 if let tab = notebook.tabs.first(where: \.readable) { self?.onOpen?(tab, notebook) }
926 }
927 }
928
929 /// Creates a notebook in iCloud Drive or On My iPhone, as OneNote's New Notebook does, and
930 /// opens it.
931 private func newNotebook(inCloud: Bool) {
932 guard let author = Author.name else {
933 return Author.ask(from: self) { [weak self] in self?.newNotebook(inCloud: inCloud) }
934 }
935 let alert = UIAlertController(
936 title: inCloud ? "New iCloud Notebook" : "New Notebook", message: nil, preferredStyle: .alert)
937 let create = UIAlertAction(title: "Create", style: .default) { [weak self, weak alert] _ in
938 let name = alert?.textFields?.first?.text?.trimmingCharacters(in: .whitespaces) ?? ""
939 self?.create(name, by: author, inCloud: inCloud)
940 }
941 alert.addTextField { field in
942 field.placeholder = "Name"
943 // A notebook in iCloud Drive starts named for it, so the list tells it apart.
944 if inCloud {
945 let taken = Set(Notebooks.inCloud.map(\.name))
946 field.text = (1...).lazy.map { $0 == 1 ? "iCloud Notebook" : "iCloud Notebook \($0)" }
947 .first { !taken.contains($0) }
948 }
949 create.isEnabled = field.text?.isEmpty == false
950 field.autocapitalizationType = .words
951 NotificationCenter.default.addObserver(
952 forName: UITextField.textDidChangeNotification, object: field, queue: .main
953 ) { _ in create.isEnabled = Self.namesFile(field) }
954 }
955 alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
956 alert.addAction(create)
957 alert.preferredAction = create
958 present(alert, animated: true)
959 }
960
961 private func create(_ name: String, by author: String, inCloud: Bool) {
962 let place = inCloud ? ICloud.documents : documentsDirectory
963 guard let folder = place?.appendingPathComponent(name) else { return }
964 guard !FileManager.default.fileExists(atPath: folder.path) else {
965 return alert("“\(name)” Already Exists", "Choose a different name.")
966 }
967 let (date, time) = titleDate()
968 background({ () -> String? in
969 var error: UnsafeMutablePointer<CChar>?
970 let made = sb_notebook_create(folder.path, cacheDirectory.path, author, date, time, &error)
971 let problem = take(error)
972 return made ? nil : problem ?? ""
973 }) { [weak self] problem in
974 guard let self else { return }
975 if let problem { return alert("Can’t Create Notebook", problem) }
976 if !inCloud && !Notebooks.showsOnDevice { Notebooks.showsOnDevice = true }
977 rescan(opening: inCloud ? .icloud(path: name) : .documents(path: name))
978 }
979 }
980
981 /// Copies the guide the app carries to On My iPhone and opens the copy, so the carried one
982 /// stays as shipped.
983 private func openGuide() {
984 let copy = documentsDirectory.appendingPathComponent(Notebooks.guide)
985 background({ () -> String? in
986 guard !FileManager.default.fileExists(atPath: copy.path) else { return nil }
987 guard let carried = Bundle.main.url(forResource: Notebooks.guide, withExtension: nil) else {
988 return "The guide is missing from this copy of Snowbound."
989 }
990 do { try FileManager.default.copyItem(at: carried, to: copy) } catch { return error.localizedDescription }
991 return nil
992 }) { [weak self] problem in
993 guard let self else { return }
994 if let problem { return alert("Can’t Open the Guide", problem) }
995 if !Notebooks.showsOnDevice { Notebooks.showsOnDevice = true }
996 rescan(opening: .documents(path: Notebooks.guide))
997 }
998 }
999
1000 private func openFolder() {
1001 let picker = UIDocumentPickerViewController(
1002 forOpeningContentTypes: [.folder, UTType(filenameExtension: "one") ?? .data])
1003 picker.delegate = self
1004 present(picker, animated: true)
1005 }
1006
1007 func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
1008 if let url = urls.first { open(document: url) }
1009 }
1010
1011 /// Opens the folder or section file at `url`, chosen here or opened from Files, at its first
1012 /// section, listing it unless it is listed.
1013 func open(document url: URL) {
1014 let accessing = url.startAccessingSecurityScopedResource()
1015 defer { if accessing { url.stopAccessingSecurityScopedResource() } }
1016 let listed = Notebooks.all.first { notebook in
1017 guard case .files(let bookmark) = notebook.source else { return false }
1018 var stale = false
1019 let location = try? URL(resolvingBookmarkData: bookmark, bookmarkDataIsStale: &stale)
1020 return location?.standardizedFileURL == url.standardizedFileURL
1021 }
1022 if let listed {
1023 // A notebook still opening at launch lists no sections yet.
1024 if let tab = listed.tabs.first(where: \.readable) { onOpen?(tab, listed) } else { openFirstSection(of: listed) }
1025 return
1026 }
1027 guard let bookmark = try? url.bookmarkData() else { return }
1028 add(Notebook(name: url.deletingPathExtension().lastPathComponent, source: .files(bookmark: bookmark)))
1029 }
1030
1031 private func connect() {
1032 let server = ServerViewController()
1033 server.onOpen = { [weak self] notebook in
1034 self?.dismiss(animated: true)
1035 self?.add(notebook)
1036 }
1037 present(UINavigationController(rootViewController: server), animated: true)
1038 }
1039
1040 private func changeServer(of notebook: Notebook) {
1041 let server = ServerViewController(editing: notebook)
1042 server.onUpdate = { [weak self] restore in
1043 self?.dismiss(animated: true) {
1044 self?.reload()
1045 restore()
1046 }
1047 }
1048 present(UINavigationController(rootViewController: server), animated: true)
1049 }
1050
1051 private func newSection(in notebook: Notebook) {
1052 let alert = UIAlertController(title: "New Section", message: nil, preferredStyle: .alert)
1053 alert.addTextField { field in
1054 field.placeholder = "Name"
1055 field.autocapitalizationType = .words
1056 }
1057 alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
1058 alert.addAction(UIAlertAction(title: "Create", style: .default) { [weak self, weak alert] _ in
1059 let name = alert?.textFields?.first?.text?.trimmingCharacters(in: .whitespaces) ?? ""
1060 guard !name.isEmpty, let handle = notebook.handle else { return }
1061 let (date, time) = titleDate()
1062 let path = take(sb_library_new_section(handle, "", name, Author.name ?? "", date, time))
1063 notebook.reload {
1064 self?.reload()
1065 if let tab = notebook.tabs.first(where: { $0.path == path }) { self?.onOpen?(tab, notebook) }
1066 }
1067 })
1068 present(alert, animated: true)
1069 }
1070}
1071
1072extension UIFont {
1073 func withTraits(_ traits: UIFontDescriptor.SymbolicTraits) -> UIFont {
1074 fontDescriptor.withSymbolicTraits(traits).map { UIFont(descriptor: $0, size: 0) } ?? self
1075 }
1076}
1077
1078/// A section's pages, subpages indented, each page's conflict pages beneath it.
1079final class PagesViewController: UITableViewController {
1080 private let listInputView = UIView(frame: .zero)
1081 override var inputView: UIView? { listInputView }
1082
1083 struct Item {
1084 let row: Row
1085 let version: Row.Version?
1086 var id: String { version?.id ?? row.id }
1087 }
1088
1089 private(set) var section: Section?
1090 private(set) var items: [Item] = []
1091 private var selected: String?
1092 private lazy var search = SearchViewController.controller { [weak self] in self?.section }
1093 /// Opens a page of the section.
1094 var onOpen: ((Section, String) -> Void)?
1095
1096 /// The section strip prototype, over the pages.
1097 private lazy var strip = SectionStrip { [weak self] tab, notebook in
1098 (self?.view.window?.windowScene?.delegate as? SceneDelegate)?.open(tab, of: notebook)
1099 }
1100
1101 init() {
1102 super.init(style: .plain)
1103 }
1104
1105 required init?(coder: NSCoder) { fatalError() }
1106
1107 override func viewDidLoad() {
1108 super.viewDidLoad()
1109 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "page")
1110 navigationItem.searchController = search
1111 navigationItem.hidesSearchBarWhenScrolling = false
1112 if #available(iOS 26, *) {
1113 navigationItem.preferredSearchBarPlacement = .integrated
1114 }
1115 updateSelectionActions()
1116 NotificationCenter.default.addObserver(
1117 self, selector: #selector(changed), name: Section.changed, object: nil)
1118 setUpArranging()
1119 if Prototype.sectionStrip {
1120 for direction in [UISwipeGestureRecognizer.Direction.left, .right] {
1121 let swipe = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
1122 swipe.direction = direction
1123 tableView.addGestureRecognizer(swipe)
1124 }
1125 }
1126 }
1127
1128 @objc private func swiped(_ swipe: UISwipeGestureRecognizer) {
1129 if let tab = strip.neighbour(swipe.direction == .left ? 1 : -1) { strip.pick(tab) }
1130 }
1131
1132 override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
1133 Prototype.sectionStrip && strip.notebook != nil ? strip : nil
1134 }
1135
1136 override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
1137 Prototype.sectionStrip && strip.notebook != nil ? 50 : 0
1138 }
1139
1140 override func viewWillAppear(_ animated: Bool) {
1141 super.viewWillAppear(animated)
1142 navigationController?.setToolbarHidden(section == nil, animated: false)
1143 }
1144
1145 func loading(_ tab: Tab) {
1146 if isEditing { setEditing(false, animated: false) }
1147 section = nil
1148 items = []
1149 title = tab.name
1150 if Prototype.sectionStrip, let notebook = strip.notebook {
1151 title = notebook.name
1152 strip.select(tab.path)
1153 }
1154 tableView.reloadData()
1155 var loading = UIContentUnavailableConfiguration.loading()
1156 loading.text = "Opening…"
1157 contentUnavailableConfiguration = loading
1158 navigationController?.setToolbarHidden(true, animated: false)
1159 }
1160
1161 /// Lets go of the section shown, as when its notebook goes.
1162 func clear() {
1163 if isEditing { setEditing(false, animated: false) }
1164 section = nil
1165 items = []
1166 title = nil
1167 tableView.reloadData()
1168 contentUnavailableConfiguration = nil
1169 navigationController?.setToolbarHidden(true, animated: false)
1170 }
1171
1172 func failed(_ problem: String?) {
1173 var empty = UIContentUnavailableConfiguration.empty()
1174 empty.text = "Can’t Open Section"
1175 empty.secondaryText = problem
1176 contentUnavailableConfiguration = empty
1177 }
1178
1179 func load(_ section: Section) {
1180 self.section = section
1181 title = section.tab.name
1182 if Prototype.sectionStrip {
1183 title = section.notebook.name
1184 strip.show(section.notebook, selected: section.tab.path)
1185 }
1186 navigationController?.setToolbarHidden(false, animated: false)
1187 reload()
1188 }
1189
1190 func select(_ id: String) {
1191 selected = id
1192 guard !isEditing else { return }
1193 if let index = items.firstIndex(where: { $0.id == id }) {
1194 tableView.selectRow(at: IndexPath(row: index, section: 0), animated: false, scrollPosition: .none)
1195 }
1196 }
1197
1198 func startSearching() {
1199 search.isActive = true
1200 DispatchQueue.main.async { self.search.searchBar.becomeFirstResponder() }
1201 }
1202
1203 override func setEditing(_ editing: Bool, animated: Bool) {
1204 super.setEditing(editing, animated: animated)
1205 for index in tableView.indexPathsForSelectedRows ?? [] { tableView.deselectRow(at: index, animated: false) }
1206 tableView.dragInteractionEnabled = !editing
1207 if !editing, let selected { select(selected) }
1208 updateSelectionActions()
1209 }
1210
1211 private func updateSelectionActions() {
1212 guard isEditing else {
1213 let add = UIBarButtonItem(title: "New Page", image: UIImage(systemName: "plus"), primaryAction: UIAction { [weak self] _ in
1214 self?.newPage(under: nil)
1215 })
1216 if #available(iOS 26, *) {
1217 toolbarItems = [navigationItem.searchBarPlacementBarButtonItem, .fixedSpace(), add]
1218 } else { toolbarItems = [.flexibleSpace(), add] }
1219 return
1220 }
1221 let selection = (tableView.indexPathsForSelectedRows ?? []).sorted().map { items[$0.row] }
1222 let delete = UIBarButtonItem(title: "Delete", image: UIImage(systemName: "trash"), primaryAction: UIAction { [weak self] _ in
1223 guard let self, let section else { return }
1224 let remove = { [weak self] in
1225 self?.setEditing(false, animated: true)
1226 let ids = selection.filter { item in
1227 item.version == nil || !selection.contains { $0.version == nil && $0.id == item.row.id }
1228 }.map(\.id)
1229 section.delete(ids)
1230 }
1231 if selection.contains(where: { $0.version != nil }) {
1232 let alert = UIAlertController(title: selection.count == 1 ? "Delete Page?" : "Delete \(selection.count) Pages?", message: "Conflict pages will be deleted permanently.", preferredStyle: .alert)
1233 alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
1234 alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { _ in remove() })
1235 present(alert, animated: true)
1236 } else { remove() }
1237 })
1238 delete.tintColor = .systemRed
1239 delete.isEnabled = !Arranging.busy && !selection.isEmpty
1240 var destinations: [UIAction] = []
1241 if let section, !selection.isEmpty, selection.allSatisfy({ $0.version == nil }) {
1242 destinations = section.notebook.sections(besides: section.tab.path).map { tab in
1243 UIAction(title: tab.name) { [weak self] _ in
1244 self?.setEditing(false, animated: true)
1245 Arranging.move(pages: selection.map(\.id), from: section, to: tab)
1246 }
1247 }
1248 }
1249 let move = UIBarButtonItem(title: "Move to Section", image: UIImage(systemName: "folder"), menu: UIMenu(children: destinations))
1250 move.isEnabled = !Arranging.busy && !destinations.isEmpty
1251 toolbarItems = [move, .flexibleSpace(), delete]
1252 navigationController?.setToolbarHidden(false, animated: false)
1253 }
1254
1255 private func reload() {
1256 let selection = tableView.indexPathsForSelectedRows?.map { items[$0.row].id } ?? []
1257 items = (section?.rows ?? []).flatMap { row in
1258 [Item(row: row, version: nil)] + row.versions.map { Item(row: row, version: $0) }
1259 }
1260 tableView.reloadData()
1261 if isEditing {
1262 for (index, item) in items.enumerated() where selection.contains(item.id) {
1263 tableView.selectRow(at: IndexPath(row: index, section: 0), animated: false, scrollPosition: .none)
1264 }
1265 updateSelectionActions()
1266 } else if let selected { select(selected) }
1267 var empty = UIContentUnavailableConfiguration.empty()
1268 empty.text = "No Pages"
1269 contentUnavailableConfiguration = section != nil && items.isEmpty ? empty : nil
1270 }
1271
1272 @objc private func changed(_ notification: Notification) {
1273 guard notification.object as AnyObject? === section,
1274 notification.userInfo?["unchanged"] as? Bool != true else { return }
1275 reload()
1276 }
1277
1278 private func newPage(under parent: String?) {
1279 guard let section, let id = section.newPage(under: parent) else { return }
1280 (view.window?.windowScene?.delegate as? SceneDelegate)?.show(section: section, page: id, titleFocus: true)
1281 }
1282
1283 private func delete(_ item: Item) {
1284 section?.delete([item.id])
1285 }
1286
1287 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { items.count }
1288
1289 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
1290 let item = items[indexPath.row]
1291 let cell = tableView.dequeueReusableCell(withIdentifier: "page", for: indexPath)
1292 var content = cell.defaultContentConfiguration()
1293 let level = CGFloat(item.row.level - 1)
1294 if let version = item.version {
1295 // OneNote lists a conflict page by whose version it is and when the merge made it.
1296 content.text = version.user.isEmpty ? "Conflicting Version" : version.user
1297 content.secondaryText = version.created.map {
1298 DateFormatter.localizedString(
1299 from: Date(timeIntervalSince1970: $0), dateStyle: .short, timeStyle: .short)
1300 }
1301 content.image = UIImage(systemName: "doc.on.doc")
1302 content.imageProperties.tintColor = .systemOrange
1303 content.textProperties.color = .secondaryLabel
1304 content.directionalLayoutMargins.leading += (level + 1) * 20
1305 } else {
1306 content.text = item.row.title.isEmpty ? "Untitled Page" : item.row.title
1307 if item.row.title.isEmpty || item.row.level > 1 { content.textProperties.color = .secondaryLabel }
1308 content.directionalLayoutMargins.leading += level * 20
1309 if !item.row.versions.isEmpty {
1310 content.image = UIImage(systemName: "exclamationmark.triangle.fill")
1311 content.imageProperties.tintColor = .systemOrange
1312 }
1313 }
1314 cell.contentConfiguration = content
1315 cell.isAccessibilityElement = true
1316 cell.accessibilityLabel = [content.text, content.secondaryText].compactMap { $0 }.joined(separator: ", ")
1317 cell.accessibilityActivateBlock = { [weak self, weak cell] in
1318 guard let self, let cell, let indexPath = self.tableView.indexPath(for: cell) else { return false }
1319 if self.isEditing && cell.isSelected {
1320 self.tableView.deselectRow(at: indexPath, animated: true)
1321 self.tableView(self.tableView, didDeselectRowAt: indexPath)
1322 } else {
1323 self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
1324 self.tableView(self.tableView, didSelectRowAt: indexPath)
1325 }
1326 return true
1327 }
1328 cell.accessibilityCustomActions = arrangeActions(item)
1329 return cell
1330 }
1331
1332 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
1333 if isEditing { return updateSelectionActions() }
1334 guard let section else { return }
1335 selected = items[indexPath.row].id
1336 onOpen?(section, items[indexPath.row].id)
1337 }
1338
1339 override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
1340 if isEditing { updateSelectionActions() }
1341 }
1342
1343 override func tableView(
1344 _ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath
1345 ) -> UISwipeActionsConfiguration? {
1346 // A swipe across the list changes section instead; the context menu deletes.
1347 if isEditing || Prototype.sectionStrip { return nil }
1348 let item = items[indexPath.row]
1349 let delete = UIContextualAction(style: .destructive, title: "Delete") { [weak self] _, _, done in
1350 self?.delete(item)
1351 done(true)
1352 }
1353 delete.image = UIImage(systemName: "trash")
1354 return UISwipeActionsConfiguration(actions: [delete])
1355 }
1356
1357 override func tableView(
1358 _ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint
1359 ) -> UIContextMenuConfiguration? {
1360 guard !isEditing else { return nil }
1361 let item = items[indexPath.row]
1362 return UIContextMenuConfiguration(actionProvider: { [weak self] _ in
1363 var actions: [UIMenuElement] = []
1364 if item.version == nil {
1365 actions.append(UIAction(title: "New Subpage", image: UIImage(systemName: "text.badge.plus")) { _ in
1366 self?.newPage(under: item.row.id)
1367 })
1368 actions += self?.arrangeMenu(item) ?? []
1369 }
1370 actions.append(
1371 UIAction(
1372 title: item.version == nil ? "Delete Page" : "Delete Conflict Page",
1373 image: UIImage(systemName: "trash"), attributes: .destructive
1374 ) { _ in self?.delete(item) })
1375 return UIMenu(children: actions)
1376 })
1377 }
1378}
1379
1380/// A page `sb_search` found.
1381struct Found: Decodable {
1382 let notebook: Int
1383 let section: String
1384 let page: String
1385 let title: String
1386 let inTitle: Bool
1387 let titleHits: [[Int]]
1388 let snippet: String
1389 let snippetHits: [[Int]]
1390}
1391
1392/// The desktop's search over every open notebook's pages: title matches, then body matches,
1393/// each with its notebook and section. Searched from a section, it offers OneNote's scopes,
1394/// starting at This Section.
1395final class SearchViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate,
1396 UISearchControllerDelegate
1397{
1398 private enum Scope: Int, CaseIterable {
1399 case section, notebook, all
1400
1401 var title: String {
1402 switch self {
1403 case .section: "This Section"
1404 case .notebook: "This Notebook"
1405 case .all: "All Notebooks"
1406 }
1407 }
1408 }
1409
1410 /// The section searched from, which the scopes narrow to.
1411 private let place: () -> Section?
1412 private weak var search: UISearchController?
1413 private var found: [(found: Found, notebook: Notebook)] = []
1414 private var query = ""
1415 private var searching: DispatchWorkItem?
1416
1417 private init(place: @escaping () -> Section?) {
1418 self.place = place
1419 super.init(style: .insetGrouped)
1420 }
1421
1422 required init?(coder: NSCoder) { fatalError() }
1423
1424 /// A search bar whose results this shows, with scopes where `place` gives the section
1425 /// it is searched from.
1426 static func controller(place: (() -> Section?)? = nil) -> UISearchController {
1427 let results = SearchViewController(place: place ?? { nil })
1428 let search = UISearchController(searchResultsController: results)
1429 results.search = search
1430 search.searchResultsUpdater = results
1431 search.delegate = results
1432 search.searchBar.delegate = results
1433 search.searchBar.placeholder = "Search"
1434 if place != nil { search.searchBar.scopeButtonTitles = Scope.allCases.map(\.title) }
1435 return search
1436 }
1437
1438 override func viewDidLoad() {
1439 super.viewDidLoad()
1440 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "found")
1441 }
1442
1443 func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
1444 if let search { updateSearchResults(for: search) }
1445 }
1446
1447 /// A scope chosen lasts for the search; the next starts at This Section again.
1448 func didDismissSearchController(_ searchController: UISearchController) {
1449 searchController.searchBar.selectedScopeButtonIndex = Scope.section.rawValue
1450 }
1451
1452 func updateSearchResults(for controller: UISearchController) {
1453 searching?.cancel()
1454 let query = controller.searchBar.text?.trimmingCharacters(in: .whitespaces) ?? ""
1455 guard !query.isEmpty else { return show([], query: query) }
1456 let open = place()
1457 let scope = open == nil ? .all : Scope(rawValue: controller.searchBar.selectedScopeButtonIndex) ?? .all
1458 let notebooks = scope == .all ? Notebooks.all : open.map { [$0.notebook] } ?? []
1459 let searched = notebooks.filter { $0.handle != nil }
1460 let libraries = searched.map { Int(bitPattern: $0.handle) }
1461 let section = scope == .section ? open?.tab.path : nil
1462 // Each keystroke waits for the next before the notebooks are read.
1463 let work = DispatchWorkItem { [weak self] in
1464 if self?.found.isEmpty == true {
1465 var loading = UIContentUnavailableConfiguration.loading()
1466 loading.text = "Searching…"
1467 self?.contentUnavailableConfiguration = loading
1468 }
1469 background({
1470 let pointers = libraries.map { OpaquePointer(bitPattern: $0) }
1471 return decode([Found].self, sb_search(pointers, pointers.count, section, query)) ?? []
1472 }) { [weak self] found in
1473 let now = controller.searchBar.text?.trimmingCharacters(in: .whitespaces)
1474 guard now == query, open == nil || controller.searchBar.selectedScopeButtonIndex == scope.rawValue
1475 else { return }
1476 self?.show(found.map { ($0, searched[$0.notebook]) }, query: query)
1477 }
1478 }
1479 searching = work
1480 DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: work)
1481 }
1482
1483 private func show(_ found: [(found: Found, notebook: Notebook)], query: String) {
1484 self.found = found
1485 self.query = query
1486 tableView.reloadData()
1487 contentUnavailableConfiguration =
1488 found.isEmpty && !query.isEmpty ? UIContentUnavailableConfiguration.search() : nil
1489 }
1490
1491 /// The results in the title's group or the body's, as the desktop's headings split them.
1492 private func group(_ section: Int) -> ArraySlice<(found: Found, notebook: Notebook)> {
1493 let titled = found.prefix { $0.found.inTitle }
1494 return titled.isEmpty || section == 1 ? found.dropFirst(titled.count) : titled
1495 }
1496
1497 override func numberOfSections(in tableView: UITableView) -> Int {
1498 (found.first?.found.inTitle == true ? 1 : 0) + (found.last?.found.inTitle == false ? 1 : 0)
1499 }
1500
1501 override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
1502 let pages = group(section)
1503 return "\(pages.first?.found.inTitle == true ? "Title" : "Body") contains: \(query) (\(pages.count))"
1504 }
1505
1506 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
1507 group(section).count
1508 }
1509
1510 private func result(_ indexPath: IndexPath) -> (found: Found, notebook: Notebook) {
1511 let pages = group(indexPath.section)
1512 return pages[pages.startIndex + indexPath.row]
1513 }
1514
1515 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
1516 let (page, notebook) = result(indexPath)
1517 let cell = tableView.dequeueReusableCell(withIdentifier: "found", for: indexPath)
1518 var content = UIListContentConfiguration.subtitleCell()
1519 let font = UIFont.preferredFont(forTextStyle: .body)
1520 content.attributedText =
1521 page.title.isEmpty
1522 ? NSAttributedString(string: "Untitled Page", attributes: [.font: font])
1523 : marked(page.title, page.titleHits, font: font, color: .label)
1524 let tab = notebook.tabs.first { $0.path == page.section }
1525 content.image = UIImage(systemName: "rectangle.portrait.fill")
1526 content.imageProperties.tintColor = tab?.uiColor ?? .systemGray
1527 // Where the page is, as the desktop names it: notebook, groups and section.
1528 let groups: [String] = tab?.group.split(separator: "/").map(String.init) ?? []
1529 let place = ([notebook.name] + groups + [tab?.name ?? ""]).filter { !$0.isEmpty }.joined(separator: " › ")
1530 let detail = NSMutableAttributedString(
1531 string: place + "\n",
1532 attributes: [.font: UIFont.preferredFont(forTextStyle: .footnote), .foregroundColor: UIColor.secondaryLabel])
1533 detail.append(
1534 marked(
1535 page.snippet, page.snippetHits, font: .preferredFont(forTextStyle: .subheadline),
1536 color: .secondaryLabel))
1537 content.secondaryAttributedText = detail
1538 content.secondaryTextProperties.numberOfLines = 3
1539 cell.contentConfiguration = content
1540 return cell
1541 }
1542
1543 /// `text` with `hits`, UTF-16 ranges, marked in OneNote's yellow as the desktop marks them.
1544 private func marked(_ text: String, _ hits: [[Int]], font: UIFont, color: UIColor) -> NSAttributedString {
1545 let marked = NSMutableAttributedString(string: text, attributes: [.font: font, .foregroundColor: color])
1546 for hit in hits where hit.count == 2 && hit[1] <= marked.length {
1547 marked.addAttributes(
1548 [.backgroundColor: UIColor(red: 1, green: 0.82, blue: 0, alpha: 0.45), .foregroundColor: UIColor.label],
1549 range: NSRange(location: hit[0], length: hit[1] - hit[0]))
1550 }
1551 return marked
1552 }
1553
1554 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
1555 let (page, notebook) = result(indexPath)
1556 (view.window?.windowScene?.delegate as? SceneDelegate)?
1557 .open(page.section, of: notebook, page: page.page, reveal: .text(query))
1558 }
1559}