| 1 | import UIKit |
| 2 | import 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. |
| 6 | final 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 | let image = UIImage(systemName: "xmark.circle") |
| 562 | let close = UIAction(title: "Close Notebook", image: image, attributes: .destructive) { [weak self] _ in |
| 563 | Notebooks.remove(notebook) |
| 564 | self?.reload() |
| 565 | } |
| 566 | return UIMenu(children: status + actions + [close]) |
| 567 | } |
| 568 | let file = [ |
| 569 | UIAction(title: "Rename", image: UIImage(systemName: "pencil")) { [weak self] _ in |
| 570 | self?.rename(folder, of: notebook) |
| 571 | }, |
| 572 | UIAction(title: "Duplicate", image: UIImage(systemName: "plus.square.on.square")) { [weak self] _ in |
| 573 | self?.duplicate(folder, of: notebook) |
| 574 | }, |
| 575 | UIAction(title: "Share", image: UIImage(systemName: "square.and.arrow.up")) { [weak self] _ in |
| 576 | self?.share(folder, from: notebook) |
| 577 | }, |
| 578 | UIAction(title: "Show in Files", image: UIImage(systemName: "folder")) { _ in |
| 579 | // Files opens the folder a `shareddocuments` URL names. |
| 580 | if let url = URL(string: "shareddocuments://" + folder.path) { UIApplication.shared.open(url) } |
| 581 | }, |
| 582 | ] |
| 583 | let delete = UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: .destructive) { |
| 584 | [weak self] _ in self?.delete(folder, of: notebook) |
| 585 | } |
| 586 | return UIMenu(children: status + [ |
| 587 | UIMenu(options: .displayInline, children: actions), UIMenu(options: .displayInline, children: file), delete, |
| 588 | ]) |
| 589 | } |
| 590 | |
| 591 | private func swipeActions(for notebook: Notebook, at indexPath: IndexPath) -> [UIContextualAction] { |
| 592 | guard let folder = folder(of: notebook) else { |
| 593 | let close = UIContextualAction(style: .destructive, title: "Close") { [weak self] _, _, done in |
| 594 | Notebooks.remove(notebook) |
| 595 | self?.reload() |
| 596 | done(true) |
| 597 | } |
| 598 | close.image = UIImage(systemName: "xmark.circle") |
| 599 | return [close] |
| 600 | } |
| 601 | let delete = UIContextualAction(style: .destructive, title: "Delete") { [weak self] _, _, done in |
| 602 | self?.delete(folder, of: notebook) |
| 603 | done(true) |
| 604 | } |
| 605 | delete.image = UIImage(systemName: "trash") |
| 606 | let share = UIContextualAction(style: .normal, title: "Share") { [weak self] _, _, done in |
| 607 | self?.share(folder, from: notebook) |
| 608 | done(true) |
| 609 | } |
| 610 | share.image = UIImage(systemName: "square.and.arrow.up") |
| 611 | share.backgroundColor = .systemBlue |
| 612 | return [delete, share] |
| 613 | } |
| 614 | |
| 615 | /// The notebook's folder or section file On My iPhone; nil for one opened elsewhere. |
| 616 | private func folder(of notebook: Notebook) -> URL? { |
| 617 | guard case .documents(let path) = notebook.source else { return nil } |
| 618 | return documentsDirectory.appendingPathComponent(path) |
| 619 | } |
| 620 | |
| 621 | /// Publishes the notebook's edits and lets go of it, closing any section of it shown, |
| 622 | /// then runs `act`; refuses with why while an edit can't be published, as moving the |
| 623 | /// folder then would strand it. |
| 624 | private func close(_ notebook: Notebook, refusing title: String, then act: @escaping () -> Void) { |
| 625 | guard let release = Arranging.reserve() else { return } |
| 626 | for scene in UIApplication.shared.connectedScenes { |
| 627 | (scene.delegate as? SceneDelegate)?.close(notebook) |
| 628 | } |
| 629 | guard let handle = notebook.handle else { |
| 630 | defer { release() } |
| 631 | return act() |
| 632 | } |
| 633 | let pointer = Int(bitPattern: handle) |
| 634 | background({ () -> String? in |
| 635 | var error: UnsafeMutablePointer<CChar>? |
| 636 | let closed = sb_library_close(OpaquePointer(bitPattern: pointer), 10, &error) |
| 637 | let problem = take(error) |
| 638 | return closed ? nil : problem ?? "" |
| 639 | }) { [weak self] problem in |
| 640 | defer { release() } |
| 641 | if let problem { |
| 642 | self?.alert(title, problem) |
| 643 | return |
| 644 | } |
| 645 | notebook.pause() |
| 646 | act() |
| 647 | } |
| 648 | } |
| 649 | |
| 650 | private func rename(_ folder: URL, of notebook: Notebook) { |
| 651 | let alert = UIAlertController(title: "Rename", message: nil, preferredStyle: .alert) |
| 652 | let isFile = folder.pathExtension.lowercased() == "one" |
| 653 | let rename = UIAlertAction(title: "Rename", style: .default) { [weak self, weak alert] _ in |
| 654 | let name = alert?.textFields?.first?.text?.trimmingCharacters(in: .whitespaces) ?? "" |
| 655 | let target = folder.deletingLastPathComponent().appendingPathComponent( |
| 656 | isFile ? name + "." + folder.pathExtension : name) |
| 657 | guard target != folder else { return } |
| 658 | guard !FileManager.default.fileExists(atPath: target.path) else { |
| 659 | self?.alert("“\(name)” Already Exists", "Choose a different name.") |
| 660 | return |
| 661 | } |
| 662 | self?.close(notebook, refusing: "Can’t Rename") { |
| 663 | do { |
| 664 | try FileManager.default.moveItem(at: folder, to: target) |
| 665 | _ = sb_notebook_moved(cacheDirectory.path, folder.path, target.path, nil) |
| 666 | } catch { |
| 667 | self?.alert("Can’t Rename", error.localizedDescription) |
| 668 | } |
| 669 | self?.rescan() |
| 670 | } |
| 671 | } |
| 672 | alert.addTextField { field in |
| 673 | field.text = folder.deletingPathExtension().lastPathComponent |
| 674 | field.autocapitalizationType = .words |
| 675 | field.clearButtonMode = .whileEditing |
| 676 | NotificationCenter.default.addObserver( |
| 677 | forName: UITextField.textDidChangeNotification, object: field, queue: .main |
| 678 | ) { _ in rename.isEnabled = Self.namesFile(field) } |
| 679 | } |
| 680 | alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) |
| 681 | alert.addAction(rename) |
| 682 | alert.preferredAction = rename |
| 683 | present(alert, animated: true) |
| 684 | } |
| 685 | |
| 686 | /// Whether `field` holds a name a notebook's folder can take. |
| 687 | private static func namesFile(_ field: UITextField) -> Bool { |
| 688 | let name = (field.text ?? "").trimmingCharacters(in: .whitespaces) |
| 689 | return !name.isEmpty && !name.hasPrefix(".") && !name.contains("/") |
| 690 | } |
| 691 | |
| 692 | /// Copies the notebook beside itself, named as Files names a duplicate. |
| 693 | private func duplicate(_ folder: URL, of notebook: Notebook) { |
| 694 | // The copy takes what the open sections have stored. |
| 695 | for section in Section.all where section.notebook === notebook && !section.flush(10) { |
| 696 | return alert("Can’t Duplicate", "Some changes haven’t been saved to the notebook yet.") |
| 697 | } |
| 698 | let base = folder.deletingPathExtension().lastPathComponent |
| 699 | let ext = folder.pathExtension |
| 700 | var copy = folder |
| 701 | for n in 2... { |
| 702 | let name = base + " \(n)" |
| 703 | copy = folder.deletingLastPathComponent().appendingPathComponent(ext.isEmpty ? name : name + "." + ext) |
| 704 | if !FileManager.default.fileExists(atPath: copy.path) { break } |
| 705 | } |
| 706 | let target = copy |
| 707 | background({ () -> String? in |
| 708 | do { try FileManager.default.copyItem(at: folder, to: target) } catch { return error.localizedDescription } |
| 709 | return nil |
| 710 | }) { [weak self] problem in |
| 711 | if let problem { self?.alert("Can’t Duplicate", problem) } |
| 712 | self?.rescan() |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | private func share(_ folder: URL, from notebook: Notebook) { |
| 717 | let sheet = UIActivityViewController(activityItems: [folder], applicationActivities: nil) |
| 718 | if let popover = sheet.popoverPresentationController { |
| 719 | if let indexPath = dataSource.indexPath(for: .notebook(notebook.id)), |
| 720 | let cell = collectionView.cellForItem(at: indexPath) |
| 721 | { |
| 722 | popover.sourceView = cell |
| 723 | popover.sourceRect = cell.bounds |
| 724 | } else { |
| 725 | popover.sourceView = view |
| 726 | } |
| 727 | } |
| 728 | present(sheet, animated: true) |
| 729 | } |
| 730 | |
| 731 | /// Moves the notebook to Recently Deleted, or, where the system keeps none, removes it |
| 732 | /// once confirmed. |
| 733 | private func delete(_ folder: URL, of notebook: Notebook) { |
| 734 | close(notebook, refusing: "Can’t Delete") { [weak self] in self?.remove(folder, of: notebook) } |
| 735 | } |
| 736 | |
| 737 | private func remove(_ folder: URL, of notebook: Notebook) { |
| 738 | if (try? FileManager.default.trashItem(at: folder, resultingItemURL: nil)) != nil { |
| 739 | if let window = view.window { |
| 740 | SyncToast.show( |
| 741 | "“\(notebook.name)” Deleted", "Restore it from Recently Deleted in Files", symbol: "trash", |
| 742 | hint: "Opens Files", in: window |
| 743 | ) { |
| 744 | if let files = URL(string: "shareddocuments://" + folder.deletingLastPathComponent().path) { |
| 745 | UIApplication.shared.open(files) |
| 746 | } |
| 747 | } |
| 748 | } |
| 749 | return rescan() |
| 750 | } |
| 751 | let name = folder.deletingPathExtension().lastPathComponent |
| 752 | let alert = UIAlertController( |
| 753 | title: "Delete “\(name)”?", message: "This notebook will be deleted immediately. You can’t undo this action.", |
| 754 | preferredStyle: .alert) |
| 755 | alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { [weak self] _ in |
| 756 | notebook.open { self?.reload() } |
| 757 | }) |
| 758 | alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { [weak self] _ in |
| 759 | self?.close(notebook, refusing: "Can’t Delete") { |
| 760 | do { try FileManager.default.removeItem(at: folder) } catch { |
| 761 | self?.alert("Can’t Delete", error.localizedDescription) |
| 762 | } |
| 763 | self?.rescan() |
| 764 | } |
| 765 | }) |
| 766 | present(alert, animated: true) |
| 767 | } |
| 768 | |
| 769 | override func collectionView( |
| 770 | _ collectionView: UICollectionView, contextMenuConfigurationForItemsAt indexPaths: [IndexPath], point: CGPoint |
| 771 | ) -> UIContextMenuConfiguration? { |
| 772 | guard !isEditing, indexPaths.count == 1, let item = dataSource.itemIdentifier(for: indexPaths[0]) else { return nil } |
| 773 | guard case .notebook(let id) = item, let notebook = notebook(id) else { |
| 774 | let actions = arrangeMenu(item) + deleteAction(item) |
| 775 | return actions.isEmpty ? nil : UIContextMenuConfiguration(actionProvider: { _ in UIMenu(children: actions) }) |
| 776 | } |
| 777 | return UIContextMenuConfiguration(actionProvider: { [weak self] _ in |
| 778 | UIMenu(children: (self?.menu(for: notebook).children ?? []) + (self?.arrangeMenu(item) ?? [])) |
| 779 | }) |
| 780 | } |
| 781 | |
| 782 | /// Delete for a section or group. |
| 783 | private func deleteAction(_ item: Item) -> [UIMenuElement] { |
| 784 | switch item { |
| 785 | case .section(let id, let path), .group(let id, let path): |
| 786 | guard let notebook = notebook(id), notebook.hasRecycleBin else { return [] } |
| 787 | return [ |
| 788 | UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: .destructive) { [weak self] _ in |
| 789 | self?.confirmRecycling([path], of: notebook) |
| 790 | } |
| 791 | ] |
| 792 | default: return [] |
| 793 | } |
| 794 | } |
| 795 | |
| 796 | /// Moves the sections and groups at `paths` to the notebook's recycle bin once confirmed. |
| 797 | private func confirmRecycling(_ paths: [String], of notebook: Notebook) { |
| 798 | let path = paths[0] |
| 799 | let tab = notebook.tabs.first { $0.path == path } |
| 800 | let title = paths.count > 1 |
| 801 | ? "Delete \(paths.count) Items?" : "Delete “\(tab?.name ?? path.split(separator: "/").last.map(String.init) ?? path)”?" |
| 802 | let message = |
| 803 | paths.count > 1 ? "They move to this notebook’s Recycle Bin." |
| 804 | : tab == nil ? "Its sections move to this notebook’s Recycle Bin." : "It moves to this notebook’s Recycle Bin." |
| 805 | let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) |
| 806 | alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) |
| 807 | alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { [weak self] _ in |
| 808 | self?.setEditing(false, animated: true) |
| 809 | self?.recycle(paths[...], of: notebook) |
| 810 | }) |
| 811 | present(alert, animated: true) |
| 812 | } |
| 813 | |
| 814 | private func recycle(_ paths: ArraySlice<String>, of notebook: Notebook) { |
| 815 | guard let path = paths.first, let library = notebook.handle, let release = Arranging.reserve() else { return } |
| 816 | for scene in UIApplication.shared.connectedScenes { |
| 817 | _ = (scene.delegate as? SceneDelegate)?.release(path, of: notebook) |
| 818 | } |
| 819 | let pointer = Int(bitPattern: library) |
| 820 | background({ sb_library_delete(OpaquePointer(bitPattern: pointer), path) }) { [weak self] deleted in |
| 821 | notebook.reload { |
| 822 | release() |
| 823 | NotificationCenter.default.post(name: Notebook.listed, object: notebook) |
| 824 | guard deleted else { |
| 825 | self?.alert("Can’t Delete", "Check that the notebook can be reached, then try again.") |
| 826 | return |
| 827 | } |
| 828 | self?.recycle(paths.dropFirst(), of: notebook) |
| 829 | } |
| 830 | } |
| 831 | } |
| 832 | |
| 833 | override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { |
| 834 | guard let item = dataSource.itemIdentifier(for: indexPath) else { return false } |
| 835 | if isEditing { |
| 836 | switch item { |
| 837 | case .notebook, .group, .section: return true |
| 838 | default: return false |
| 839 | } |
| 840 | } |
| 841 | switch item { |
| 842 | case .section(let id, let path): |
| 843 | let tab = notebook(id)?.tabs.first(where: { $0.path == path }) |
| 844 | return tab?.readable == true || tab?.locked == true |
| 845 | case .status(let id): |
| 846 | guard let notebook = notebook(id), notebook.problem != nil else { return false } |
| 847 | let spinner = UIActivityIndicatorView(style: .medium) |
| 848 | spinner.startAnimating() |
| 849 | (collectionView.cellForItem(at: indexPath) as? UICollectionViewListCell)?.accessories = [ |
| 850 | .customView(configuration: .init(customView: spinner, placement: .trailing())) |
| 851 | ] |
| 852 | notebook.open { [weak self] in self?.reload() } |
| 853 | case .notebook, .group: |
| 854 | // The row opens and closes, as a folder of Files' sidebar does. |
| 855 | guard let location = dataSource.sectionIdentifier(for: indexPath.section) else { return false } |
| 856 | var list = dataSource.snapshot(for: location) |
| 857 | if list.isExpanded(item) { |
| 858 | list.collapse([item]) |
| 859 | collapsed.insert(item) |
| 860 | } else { |
| 861 | list.expand([item]) |
| 862 | collapsed.remove(item) |
| 863 | } |
| 864 | dataSource.apply(list, to: location) |
| 865 | case .location: break |
| 866 | } |
| 867 | return false |
| 868 | } |
| 869 | |
| 870 | override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { |
| 871 | if isEditing { return updateSelectionActions() } |
| 872 | guard case .section(let id, let path) = dataSource.itemIdentifier(for: indexPath), let notebook = notebook(id), |
| 873 | let tab = notebook.tabs.first(where: { $0.path == path }) |
| 874 | else { return } |
| 875 | if tab.locked { return unlock(tab, of: notebook, wrong: false) } |
| 876 | onOpen?(tab, notebook) |
| 877 | } |
| 878 | |
| 879 | override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { |
| 880 | if isEditing { updateSelectionActions() } |
| 881 | } |
| 882 | |
| 883 | /// Asks for a protected section's password, as OneNote's Protected Section dialog does, |
| 884 | /// and opens it once unlocked. |
| 885 | private func unlock(_ tab: Tab, of notebook: Notebook, wrong: Bool) { |
| 886 | let alert = UIAlertController( |
| 887 | title: "Protected Section", |
| 888 | message: wrong ? "Password is incorrect." : "Section “\(tab.name)” is password protected.", |
| 889 | preferredStyle: .alert) |
| 890 | alert.addTextField { field in |
| 891 | field.isSecureTextEntry = true |
| 892 | field.placeholder = "Password" |
| 893 | } |
| 894 | alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) |
| 895 | alert.addAction(UIAlertAction(title: "OK", style: .default) { [weak self, weak alert] _ in |
| 896 | let password = alert?.textFields?.first?.text ?? "" |
| 897 | notebook.unlock(tab.path, password: password) { unlocked in |
| 898 | self?.reload() |
| 899 | if unlocked, let opened = notebook.tabs.first(where: { $0.path == tab.path }) { |
| 900 | self?.onOpen?(opened, notebook) |
| 901 | } else { |
| 902 | self?.unlock(tab, of: notebook, wrong: true) |
| 903 | } |
| 904 | } |
| 905 | }) |
| 906 | present(alert, animated: true) |
| 907 | } |
| 908 | |
| 909 | private func add(_ notebook: Notebook) { |
| 910 | Notebooks.add(notebook) |
| 911 | openFirstSection(of: notebook) |
| 912 | } |
| 913 | |
| 914 | private func openFirstSection(of notebook: Notebook) { |
| 915 | reload() |
| 916 | notebook.open { [weak self] in |
| 917 | self?.reload() |
| 918 | if let tab = notebook.tabs.first(where: \.readable) { self?.onOpen?(tab, notebook) } |
| 919 | } |
| 920 | } |
| 921 | |
| 922 | /// Creates a notebook in iCloud Drive or On My iPhone, as OneNote's New Notebook does, and |
| 923 | /// opens it. |
| 924 | private func newNotebook(inCloud: Bool) { |
| 925 | guard let author = Author.name else { |
| 926 | return Author.ask(from: self) { [weak self] in self?.newNotebook(inCloud: inCloud) } |
| 927 | } |
| 928 | let alert = UIAlertController( |
| 929 | title: inCloud ? "New iCloud Notebook" : "New Notebook", message: nil, preferredStyle: .alert) |
| 930 | let create = UIAlertAction(title: "Create", style: .default) { [weak self, weak alert] _ in |
| 931 | let name = alert?.textFields?.first?.text?.trimmingCharacters(in: .whitespaces) ?? "" |
| 932 | self?.create(name, by: author, inCloud: inCloud) |
| 933 | } |
| 934 | alert.addTextField { field in |
| 935 | field.placeholder = "Name" |
| 936 | // A notebook in iCloud Drive starts named for it, so the list tells it apart. |
| 937 | if inCloud { |
| 938 | let taken = Set(Notebooks.inCloud.map(\.name)) |
| 939 | field.text = (1...).lazy.map { $0 == 1 ? "iCloud Notebook" : "iCloud Notebook \($0)" } |
| 940 | .first { !taken.contains($0) } |
| 941 | } |
| 942 | create.isEnabled = field.text?.isEmpty == false |
| 943 | field.autocapitalizationType = .words |
| 944 | NotificationCenter.default.addObserver( |
| 945 | forName: UITextField.textDidChangeNotification, object: field, queue: .main |
| 946 | ) { _ in create.isEnabled = Self.namesFile(field) } |
| 947 | } |
| 948 | alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) |
| 949 | alert.addAction(create) |
| 950 | alert.preferredAction = create |
| 951 | present(alert, animated: true) |
| 952 | } |
| 953 | |
| 954 | private func create(_ name: String, by author: String, inCloud: Bool) { |
| 955 | let place = inCloud ? ICloud.documents : documentsDirectory |
| 956 | guard let folder = place?.appendingPathComponent(name) else { return } |
| 957 | guard !FileManager.default.fileExists(atPath: folder.path) else { |
| 958 | return alert("“\(name)” Already Exists", "Choose a different name.") |
| 959 | } |
| 960 | let (date, time) = titleDate() |
| 961 | background({ () -> String? in |
| 962 | var error: UnsafeMutablePointer<CChar>? |
| 963 | let made = sb_notebook_create(folder.path, cacheDirectory.path, author, date, time, &error) |
| 964 | let problem = take(error) |
| 965 | return made ? nil : problem ?? "" |
| 966 | }) { [weak self] problem in |
| 967 | guard let self else { return } |
| 968 | if let problem { return alert("Can’t Create Notebook", problem) } |
| 969 | if !inCloud && !Notebooks.showsOnDevice { Notebooks.showsOnDevice = true } |
| 970 | rescan(opening: inCloud ? .icloud(path: name) : .documents(path: name)) |
| 971 | } |
| 972 | } |
| 973 | |
| 974 | /// Copies the guide the app carries to On My iPhone and opens the copy, so the carried one |
| 975 | /// stays as shipped. |
| 976 | private func openGuide() { |
| 977 | let copy = documentsDirectory.appendingPathComponent(Notebooks.guide) |
| 978 | background({ () -> String? in |
| 979 | guard !FileManager.default.fileExists(atPath: copy.path) else { return nil } |
| 980 | guard let carried = Bundle.main.url(forResource: Notebooks.guide, withExtension: nil) else { |
| 981 | return "The guide is missing from this copy of Snowbound." |
| 982 | } |
| 983 | do { try FileManager.default.copyItem(at: carried, to: copy) } catch { return error.localizedDescription } |
| 984 | return nil |
| 985 | }) { [weak self] problem in |
| 986 | guard let self else { return } |
| 987 | if let problem { return alert("Can’t Open the Guide", problem) } |
| 988 | if !Notebooks.showsOnDevice { Notebooks.showsOnDevice = true } |
| 989 | rescan(opening: .documents(path: Notebooks.guide)) |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | private func openFolder() { |
| 994 | let picker = UIDocumentPickerViewController( |
| 995 | forOpeningContentTypes: [.folder, UTType(filenameExtension: "one") ?? .data]) |
| 996 | picker.delegate = self |
| 997 | present(picker, animated: true) |
| 998 | } |
| 999 | |
| 1000 | func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { |
| 1001 | if let url = urls.first { open(document: url) } |
| 1002 | } |
| 1003 | |
| 1004 | /// Opens the folder or section file at `url`, chosen here or opened from Files, at its first |
| 1005 | /// section, listing it unless it is listed. |
| 1006 | func open(document url: URL) { |
| 1007 | let accessing = url.startAccessingSecurityScopedResource() |
| 1008 | defer { if accessing { url.stopAccessingSecurityScopedResource() } } |
| 1009 | let listed = Notebooks.all.first { notebook in |
| 1010 | guard case .files(let bookmark) = notebook.source else { return false } |
| 1011 | var stale = false |
| 1012 | let location = try? URL(resolvingBookmarkData: bookmark, bookmarkDataIsStale: &stale) |
| 1013 | return location?.standardizedFileURL == url.standardizedFileURL |
| 1014 | } |
| 1015 | if let listed { |
| 1016 | // A notebook still opening at launch lists no sections yet. |
| 1017 | if let tab = listed.tabs.first(where: \.readable) { onOpen?(tab, listed) } else { openFirstSection(of: listed) } |
| 1018 | return |
| 1019 | } |
| 1020 | guard let bookmark = try? url.bookmarkData() else { return } |
| 1021 | add(Notebook(name: url.deletingPathExtension().lastPathComponent, source: .files(bookmark: bookmark))) |
| 1022 | } |
| 1023 | |
| 1024 | private func connect() { |
| 1025 | let server = ServerViewController() |
| 1026 | server.onOpen = { [weak self] notebook in |
| 1027 | self?.dismiss(animated: true) |
| 1028 | self?.add(notebook) |
| 1029 | } |
| 1030 | present(UINavigationController(rootViewController: server), animated: true) |
| 1031 | } |
| 1032 | |
| 1033 | private func newSection(in notebook: Notebook) { |
| 1034 | let alert = UIAlertController(title: "New Section", message: nil, preferredStyle: .alert) |
| 1035 | alert.addTextField { field in |
| 1036 | field.placeholder = "Name" |
| 1037 | field.autocapitalizationType = .words |
| 1038 | } |
| 1039 | alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) |
| 1040 | alert.addAction(UIAlertAction(title: "Create", style: .default) { [weak self, weak alert] _ in |
| 1041 | let name = alert?.textFields?.first?.text?.trimmingCharacters(in: .whitespaces) ?? "" |
| 1042 | guard !name.isEmpty, let handle = notebook.handle else { return } |
| 1043 | let (date, time) = titleDate() |
| 1044 | let path = take(sb_library_new_section(handle, "", name, Author.name ?? "", date, time)) |
| 1045 | notebook.reload { |
| 1046 | self?.reload() |
| 1047 | if let tab = notebook.tabs.first(where: { $0.path == path }) { self?.onOpen?(tab, notebook) } |
| 1048 | } |
| 1049 | }) |
| 1050 | present(alert, animated: true) |
| 1051 | } |
| 1052 | } |
| 1053 | |
| 1054 | extension UIFont { |
| 1055 | func withTraits(_ traits: UIFontDescriptor.SymbolicTraits) -> UIFont { |
| 1056 | fontDescriptor.withSymbolicTraits(traits).map { UIFont(descriptor: $0, size: 0) } ?? self |
| 1057 | } |
| 1058 | } |
| 1059 | |
| 1060 | /// A section's pages, subpages indented, each page's conflict pages beneath it. |
| 1061 | final class PagesViewController: UITableViewController { |
| 1062 | private let listInputView = UIView(frame: .zero) |
| 1063 | override var inputView: UIView? { listInputView } |
| 1064 | |
| 1065 | struct Item { |
| 1066 | let row: Row |
| 1067 | let version: Row.Version? |
| 1068 | var id: String { version?.id ?? row.id } |
| 1069 | } |
| 1070 | |
| 1071 | private(set) var section: Section? |
| 1072 | private(set) var items: [Item] = [] |
| 1073 | private var selected: String? |
| 1074 | private lazy var search = SearchViewController.controller { [weak self] in self?.section } |
| 1075 | /// Opens a page of the section. |
| 1076 | var onOpen: ((Section, String) -> Void)? |
| 1077 | |
| 1078 | /// The section strip prototype, over the pages. |
| 1079 | private lazy var strip = SectionStrip { [weak self] tab, notebook in |
| 1080 | (self?.view.window?.windowScene?.delegate as? SceneDelegate)?.open(tab, of: notebook) |
| 1081 | } |
| 1082 | |
| 1083 | init() { |
| 1084 | super.init(style: .plain) |
| 1085 | } |
| 1086 | |
| 1087 | required init?(coder: NSCoder) { fatalError() } |
| 1088 | |
| 1089 | override func viewDidLoad() { |
| 1090 | super.viewDidLoad() |
| 1091 | tableView.register(UITableViewCell.self, forCellReuseIdentifier: "page") |
| 1092 | navigationItem.searchController = search |
| 1093 | navigationItem.hidesSearchBarWhenScrolling = false |
| 1094 | if #available(iOS 26, *) { |
| 1095 | navigationItem.preferredSearchBarPlacement = .integrated |
| 1096 | } |
| 1097 | updateSelectionActions() |
| 1098 | NotificationCenter.default.addObserver( |
| 1099 | self, selector: #selector(changed), name: Section.changed, object: nil) |
| 1100 | setUpArranging() |
| 1101 | if Prototype.sectionStrip { |
| 1102 | for direction in [UISwipeGestureRecognizer.Direction.left, .right] { |
| 1103 | let swipe = UISwipeGestureRecognizer(target: self, action: #selector(swiped)) |
| 1104 | swipe.direction = direction |
| 1105 | tableView.addGestureRecognizer(swipe) |
| 1106 | } |
| 1107 | } |
| 1108 | } |
| 1109 | |
| 1110 | @objc private func swiped(_ swipe: UISwipeGestureRecognizer) { |
| 1111 | if let tab = strip.neighbour(swipe.direction == .left ? 1 : -1) { strip.pick(tab) } |
| 1112 | } |
| 1113 | |
| 1114 | override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { |
| 1115 | Prototype.sectionStrip && strip.notebook != nil ? strip : nil |
| 1116 | } |
| 1117 | |
| 1118 | override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { |
| 1119 | Prototype.sectionStrip && strip.notebook != nil ? 50 : 0 |
| 1120 | } |
| 1121 | |
| 1122 | override func viewWillAppear(_ animated: Bool) { |
| 1123 | super.viewWillAppear(animated) |
| 1124 | navigationController?.setToolbarHidden(section == nil, animated: false) |
| 1125 | } |
| 1126 | |
| 1127 | func loading(_ tab: Tab) { |
| 1128 | if isEditing { setEditing(false, animated: false) } |
| 1129 | section = nil |
| 1130 | items = [] |
| 1131 | title = tab.name |
| 1132 | if Prototype.sectionStrip, let notebook = strip.notebook { |
| 1133 | title = notebook.name |
| 1134 | strip.select(tab.path) |
| 1135 | } |
| 1136 | tableView.reloadData() |
| 1137 | var loading = UIContentUnavailableConfiguration.loading() |
| 1138 | loading.text = "Opening…" |
| 1139 | contentUnavailableConfiguration = loading |
| 1140 | navigationController?.setToolbarHidden(true, animated: false) |
| 1141 | } |
| 1142 | |
| 1143 | /// Lets go of the section shown, as when its notebook goes. |
| 1144 | func clear() { |
| 1145 | if isEditing { setEditing(false, animated: false) } |
| 1146 | section = nil |
| 1147 | items = [] |
| 1148 | title = nil |
| 1149 | tableView.reloadData() |
| 1150 | contentUnavailableConfiguration = nil |
| 1151 | navigationController?.setToolbarHidden(true, animated: false) |
| 1152 | } |
| 1153 | |
| 1154 | func failed(_ problem: String?) { |
| 1155 | var empty = UIContentUnavailableConfiguration.empty() |
| 1156 | empty.text = "Can’t Open Section" |
| 1157 | empty.secondaryText = problem |
| 1158 | contentUnavailableConfiguration = empty |
| 1159 | } |
| 1160 | |
| 1161 | func load(_ section: Section) { |
| 1162 | self.section = section |
| 1163 | title = section.tab.name |
| 1164 | if Prototype.sectionStrip { |
| 1165 | title = section.notebook.name |
| 1166 | strip.show(section.notebook, selected: section.tab.path) |
| 1167 | } |
| 1168 | navigationController?.setToolbarHidden(false, animated: false) |
| 1169 | reload() |
| 1170 | } |
| 1171 | |
| 1172 | func select(_ id: String) { |
| 1173 | selected = id |
| 1174 | guard !isEditing else { return } |
| 1175 | if let index = items.firstIndex(where: { $0.id == id }) { |
| 1176 | tableView.selectRow(at: IndexPath(row: index, section: 0), animated: false, scrollPosition: .none) |
| 1177 | } |
| 1178 | } |
| 1179 | |
| 1180 | func startSearching() { |
| 1181 | search.isActive = true |
| 1182 | DispatchQueue.main.async { self.search.searchBar.becomeFirstResponder() } |
| 1183 | } |
| 1184 | |
| 1185 | override func setEditing(_ editing: Bool, animated: Bool) { |
| 1186 | super.setEditing(editing, animated: animated) |
| 1187 | for index in tableView.indexPathsForSelectedRows ?? [] { tableView.deselectRow(at: index, animated: false) } |
| 1188 | tableView.dragInteractionEnabled = !editing |
| 1189 | if !editing, let selected { select(selected) } |
| 1190 | updateSelectionActions() |
| 1191 | } |
| 1192 | |
| 1193 | private func updateSelectionActions() { |
| 1194 | guard isEditing else { |
| 1195 | let add = UIBarButtonItem(title: "New Page", image: UIImage(systemName: "plus"), primaryAction: UIAction { [weak self] _ in |
| 1196 | self?.newPage(under: nil) |
| 1197 | }) |
| 1198 | if #available(iOS 26, *) { |
| 1199 | toolbarItems = [navigationItem.searchBarPlacementBarButtonItem, .fixedSpace(), add] |
| 1200 | } else { toolbarItems = [.flexibleSpace(), add] } |
| 1201 | return |
| 1202 | } |
| 1203 | let selection = (tableView.indexPathsForSelectedRows ?? []).sorted().map { items[$0.row] } |
| 1204 | let delete = UIBarButtonItem(title: "Delete", image: UIImage(systemName: "trash"), primaryAction: UIAction { [weak self] _ in |
| 1205 | guard let self, let section else { return } |
| 1206 | let remove = { [weak self] in |
| 1207 | self?.setEditing(false, animated: true) |
| 1208 | let ids = selection.filter { item in |
| 1209 | item.version == nil || !selection.contains { $0.version == nil && $0.id == item.row.id } |
| 1210 | }.map(\.id) |
| 1211 | section.delete(ids) |
| 1212 | } |
| 1213 | if selection.contains(where: { $0.version != nil }) { |
| 1214 | let alert = UIAlertController(title: selection.count == 1 ? "Delete Page?" : "Delete \(selection.count) Pages?", message: "Conflict pages will be deleted permanently.", preferredStyle: .alert) |
| 1215 | alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) |
| 1216 | alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { _ in remove() }) |
| 1217 | present(alert, animated: true) |
| 1218 | } else { remove() } |
| 1219 | }) |
| 1220 | delete.tintColor = .systemRed |
| 1221 | delete.isEnabled = !Arranging.busy && !selection.isEmpty |
| 1222 | var destinations: [UIAction] = [] |
| 1223 | if let section, !selection.isEmpty, selection.allSatisfy({ $0.version == nil }) { |
| 1224 | destinations = section.notebook.sections(besides: section.tab.path).map { tab in |
| 1225 | UIAction(title: tab.name) { [weak self] _ in |
| 1226 | self?.setEditing(false, animated: true) |
| 1227 | Arranging.move(pages: selection.map(\.id), from: section, to: tab) |
| 1228 | } |
| 1229 | } |
| 1230 | } |
| 1231 | let move = UIBarButtonItem(title: "Move to Section", image: UIImage(systemName: "folder"), menu: UIMenu(children: destinations)) |
| 1232 | move.isEnabled = !Arranging.busy && !destinations.isEmpty |
| 1233 | toolbarItems = [move, .flexibleSpace(), delete] |
| 1234 | navigationController?.setToolbarHidden(false, animated: false) |
| 1235 | } |
| 1236 | |
| 1237 | private func reload() { |
| 1238 | let selection = tableView.indexPathsForSelectedRows?.map { items[$0.row].id } ?? [] |
| 1239 | items = (section?.rows ?? []).flatMap { row in |
| 1240 | [Item(row: row, version: nil)] + row.versions.map { Item(row: row, version: $0) } |
| 1241 | } |
| 1242 | tableView.reloadData() |
| 1243 | if isEditing { |
| 1244 | for (index, item) in items.enumerated() where selection.contains(item.id) { |
| 1245 | tableView.selectRow(at: IndexPath(row: index, section: 0), animated: false, scrollPosition: .none) |
| 1246 | } |
| 1247 | updateSelectionActions() |
| 1248 | } else if let selected { select(selected) } |
| 1249 | var empty = UIContentUnavailableConfiguration.empty() |
| 1250 | empty.text = "No Pages" |
| 1251 | contentUnavailableConfiguration = section != nil && items.isEmpty ? empty : nil |
| 1252 | } |
| 1253 | |
| 1254 | @objc private func changed(_ notification: Notification) { |
| 1255 | guard notification.object as AnyObject? === section, |
| 1256 | notification.userInfo?["unchanged"] as? Bool != true else { return } |
| 1257 | reload() |
| 1258 | } |
| 1259 | |
| 1260 | private func newPage(under parent: String?) { |
| 1261 | guard let section, let id = section.newPage(under: parent) else { return } |
| 1262 | (view.window?.windowScene?.delegate as? SceneDelegate)?.show(section: section, page: id, titleFocus: true) |
| 1263 | } |
| 1264 | |
| 1265 | private func delete(_ item: Item) { |
| 1266 | section?.delete([item.id]) |
| 1267 | } |
| 1268 | |
| 1269 | override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { items.count } |
| 1270 | |
| 1271 | override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { |
| 1272 | let item = items[indexPath.row] |
| 1273 | let cell = tableView.dequeueReusableCell(withIdentifier: "page", for: indexPath) |
| 1274 | var content = cell.defaultContentConfiguration() |
| 1275 | let level = CGFloat(item.row.level - 1) |
| 1276 | if let version = item.version { |
| 1277 | // OneNote lists a conflict page by whose version it is and when the merge made it. |
| 1278 | content.text = version.user.isEmpty ? "Conflicting Version" : version.user |
| 1279 | content.secondaryText = version.created.map { |
| 1280 | DateFormatter.localizedString( |
| 1281 | from: Date(timeIntervalSince1970: $0), dateStyle: .short, timeStyle: .short) |
| 1282 | } |
| 1283 | content.image = UIImage(systemName: "doc.on.doc") |
| 1284 | content.imageProperties.tintColor = .systemOrange |
| 1285 | content.textProperties.color = .secondaryLabel |
| 1286 | content.directionalLayoutMargins.leading += (level + 1) * 20 |
| 1287 | } else { |
| 1288 | content.text = item.row.title.isEmpty ? "Untitled Page" : item.row.title |
| 1289 | if item.row.title.isEmpty || item.row.level > 1 { content.textProperties.color = .secondaryLabel } |
| 1290 | content.directionalLayoutMargins.leading += level * 20 |
| 1291 | if !item.row.versions.isEmpty { |
| 1292 | content.image = UIImage(systemName: "exclamationmark.triangle.fill") |
| 1293 | content.imageProperties.tintColor = .systemOrange |
| 1294 | } |
| 1295 | } |
| 1296 | cell.contentConfiguration = content |
| 1297 | cell.isAccessibilityElement = true |
| 1298 | cell.accessibilityLabel = [content.text, content.secondaryText].compactMap { $0 }.joined(separator: ", ") |
| 1299 | cell.accessibilityActivateBlock = { [weak self, weak cell] in |
| 1300 | guard let self, let cell, let indexPath = self.tableView.indexPath(for: cell) else { return false } |
| 1301 | if self.isEditing && cell.isSelected { |
| 1302 | self.tableView.deselectRow(at: indexPath, animated: true) |
| 1303 | self.tableView(self.tableView, didDeselectRowAt: indexPath) |
| 1304 | } else { |
| 1305 | self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) |
| 1306 | self.tableView(self.tableView, didSelectRowAt: indexPath) |
| 1307 | } |
| 1308 | return true |
| 1309 | } |
| 1310 | cell.accessibilityCustomActions = arrangeActions(item) |
| 1311 | return cell |
| 1312 | } |
| 1313 | |
| 1314 | override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { |
| 1315 | if isEditing { return updateSelectionActions() } |
| 1316 | guard let section else { return } |
| 1317 | selected = items[indexPath.row].id |
| 1318 | onOpen?(section, items[indexPath.row].id) |
| 1319 | } |
| 1320 | |
| 1321 | override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { |
| 1322 | if isEditing { updateSelectionActions() } |
| 1323 | } |
| 1324 | |
| 1325 | override func tableView( |
| 1326 | _ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath |
| 1327 | ) -> UISwipeActionsConfiguration? { |
| 1328 | // A swipe across the list changes section instead; the context menu deletes. |
| 1329 | if isEditing || Prototype.sectionStrip { return nil } |
| 1330 | let item = items[indexPath.row] |
| 1331 | let delete = UIContextualAction(style: .destructive, title: "Delete") { [weak self] _, _, done in |
| 1332 | self?.delete(item) |
| 1333 | done(true) |
| 1334 | } |
| 1335 | delete.image = UIImage(systemName: "trash") |
| 1336 | return UISwipeActionsConfiguration(actions: [delete]) |
| 1337 | } |
| 1338 | |
| 1339 | override func tableView( |
| 1340 | _ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint |
| 1341 | ) -> UIContextMenuConfiguration? { |
| 1342 | guard !isEditing else { return nil } |
| 1343 | let item = items[indexPath.row] |
| 1344 | return UIContextMenuConfiguration(actionProvider: { [weak self] _ in |
| 1345 | var actions: [UIMenuElement] = [] |
| 1346 | if item.version == nil { |
| 1347 | actions.append(UIAction(title: "New Subpage", image: UIImage(systemName: "text.badge.plus")) { _ in |
| 1348 | self?.newPage(under: item.row.id) |
| 1349 | }) |
| 1350 | actions += self?.arrangeMenu(item) ?? [] |
| 1351 | } |
| 1352 | actions.append( |
| 1353 | UIAction( |
| 1354 | title: item.version == nil ? "Delete Page" : "Delete Conflict Page", |
| 1355 | image: UIImage(systemName: "trash"), attributes: .destructive |
| 1356 | ) { _ in self?.delete(item) }) |
| 1357 | return UIMenu(children: actions) |
| 1358 | }) |
| 1359 | } |
| 1360 | } |
| 1361 | |
| 1362 | /// A page `sb_search` found. |
| 1363 | struct Found: Decodable { |
| 1364 | let notebook: Int |
| 1365 | let section: String |
| 1366 | let page: String |
| 1367 | let title: String |
| 1368 | let inTitle: Bool |
| 1369 | let titleHits: [[Int]] |
| 1370 | let snippet: String |
| 1371 | let snippetHits: [[Int]] |
| 1372 | } |
| 1373 | |
| 1374 | /// The desktop's search over every open notebook's pages: title matches, then body matches, |
| 1375 | /// each with its notebook and section. Searched from a section, it offers OneNote's scopes, |
| 1376 | /// starting at This Section. |
| 1377 | final class SearchViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate, |
| 1378 | UISearchControllerDelegate |
| 1379 | { |
| 1380 | private enum Scope: Int, CaseIterable { |
| 1381 | case section, notebook, all |
| 1382 | |
| 1383 | var title: String { |
| 1384 | switch self { |
| 1385 | case .section: "This Section" |
| 1386 | case .notebook: "This Notebook" |
| 1387 | case .all: "All Notebooks" |
| 1388 | } |
| 1389 | } |
| 1390 | } |
| 1391 | |
| 1392 | /// The section searched from, which the scopes narrow to. |
| 1393 | private let place: () -> Section? |
| 1394 | private weak var search: UISearchController? |
| 1395 | private var found: [(found: Found, notebook: Notebook)] = [] |
| 1396 | private var query = "" |
| 1397 | private var searching: DispatchWorkItem? |
| 1398 | |
| 1399 | private init(place: @escaping () -> Section?) { |
| 1400 | self.place = place |
| 1401 | super.init(style: .insetGrouped) |
| 1402 | } |
| 1403 | |
| 1404 | required init?(coder: NSCoder) { fatalError() } |
| 1405 | |
| 1406 | /// A search bar whose results this shows, with scopes where `place` gives the section |
| 1407 | /// it is searched from. |
| 1408 | static func controller(place: (() -> Section?)? = nil) -> UISearchController { |
| 1409 | let results = SearchViewController(place: place ?? { nil }) |
| 1410 | let search = UISearchController(searchResultsController: results) |
| 1411 | results.search = search |
| 1412 | search.searchResultsUpdater = results |
| 1413 | search.delegate = results |
| 1414 | search.searchBar.delegate = results |
| 1415 | search.searchBar.placeholder = "Search" |
| 1416 | if place != nil { search.searchBar.scopeButtonTitles = Scope.allCases.map(\.title) } |
| 1417 | return search |
| 1418 | } |
| 1419 | |
| 1420 | override func viewDidLoad() { |
| 1421 | super.viewDidLoad() |
| 1422 | tableView.register(UITableViewCell.self, forCellReuseIdentifier: "found") |
| 1423 | } |
| 1424 | |
| 1425 | func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { |
| 1426 | if let search { updateSearchResults(for: search) } |
| 1427 | } |
| 1428 | |
| 1429 | /// A scope chosen lasts for the search; the next starts at This Section again. |
| 1430 | func didDismissSearchController(_ searchController: UISearchController) { |
| 1431 | searchController.searchBar.selectedScopeButtonIndex = Scope.section.rawValue |
| 1432 | } |
| 1433 | |
| 1434 | func updateSearchResults(for controller: UISearchController) { |
| 1435 | searching?.cancel() |
| 1436 | let query = controller.searchBar.text?.trimmingCharacters(in: .whitespaces) ?? "" |
| 1437 | guard !query.isEmpty else { return show([], query: query) } |
| 1438 | let open = place() |
| 1439 | let scope = open == nil ? .all : Scope(rawValue: controller.searchBar.selectedScopeButtonIndex) ?? .all |
| 1440 | let notebooks = scope == .all ? Notebooks.all : open.map { [$0.notebook] } ?? [] |
| 1441 | let searched = notebooks.filter { $0.handle != nil } |
| 1442 | let libraries = searched.map { Int(bitPattern: $0.handle) } |
| 1443 | let section = scope == .section ? open?.tab.path : nil |
| 1444 | // Each keystroke waits for the next before the notebooks are read. |
| 1445 | let work = DispatchWorkItem { [weak self] in |
| 1446 | if self?.found.isEmpty == true { |
| 1447 | var loading = UIContentUnavailableConfiguration.loading() |
| 1448 | loading.text = "Searching…" |
| 1449 | self?.contentUnavailableConfiguration = loading |
| 1450 | } |
| 1451 | background({ |
| 1452 | let pointers = libraries.map { OpaquePointer(bitPattern: $0) } |
| 1453 | return decode([Found].self, sb_search(pointers, pointers.count, section, query)) ?? [] |
| 1454 | }) { [weak self] found in |
| 1455 | let now = controller.searchBar.text?.trimmingCharacters(in: .whitespaces) |
| 1456 | guard now == query, open == nil || controller.searchBar.selectedScopeButtonIndex == scope.rawValue |
| 1457 | else { return } |
| 1458 | self?.show(found.map { ($0, searched[$0.notebook]) }, query: query) |
| 1459 | } |
| 1460 | } |
| 1461 | searching = work |
| 1462 | DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: work) |
| 1463 | } |
| 1464 | |
| 1465 | private func show(_ found: [(found: Found, notebook: Notebook)], query: String) { |
| 1466 | self.found = found |
| 1467 | self.query = query |
| 1468 | tableView.reloadData() |
| 1469 | contentUnavailableConfiguration = |
| 1470 | found.isEmpty && !query.isEmpty ? UIContentUnavailableConfiguration.search() : nil |
| 1471 | } |
| 1472 | |
| 1473 | /// The results in the title's group or the body's, as the desktop's headings split them. |
| 1474 | private func group(_ section: Int) -> ArraySlice<(found: Found, notebook: Notebook)> { |
| 1475 | let titled = found.prefix { $0.found.inTitle } |
| 1476 | return titled.isEmpty || section == 1 ? found.dropFirst(titled.count) : titled |
| 1477 | } |
| 1478 | |
| 1479 | override func numberOfSections(in tableView: UITableView) -> Int { |
| 1480 | (found.first?.found.inTitle == true ? 1 : 0) + (found.last?.found.inTitle == false ? 1 : 0) |
| 1481 | } |
| 1482 | |
| 1483 | override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { |
| 1484 | let pages = group(section) |
| 1485 | return "\(pages.first?.found.inTitle == true ? "Title" : "Body") contains: \(query) (\(pages.count))" |
| 1486 | } |
| 1487 | |
| 1488 | override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { |
| 1489 | group(section).count |
| 1490 | } |
| 1491 | |
| 1492 | private func result(_ indexPath: IndexPath) -> (found: Found, notebook: Notebook) { |
| 1493 | let pages = group(indexPath.section) |
| 1494 | return pages[pages.startIndex + indexPath.row] |
| 1495 | } |
| 1496 | |
| 1497 | override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { |
| 1498 | let (page, notebook) = result(indexPath) |
| 1499 | let cell = tableView.dequeueReusableCell(withIdentifier: "found", for: indexPath) |
| 1500 | var content = UIListContentConfiguration.subtitleCell() |
| 1501 | let font = UIFont.preferredFont(forTextStyle: .body) |
| 1502 | content.attributedText = |
| 1503 | page.title.isEmpty |
| 1504 | ? NSAttributedString(string: "Untitled Page", attributes: [.font: font]) |
| 1505 | : marked(page.title, page.titleHits, font: font, color: .label) |
| 1506 | let tab = notebook.tabs.first { $0.path == page.section } |
| 1507 | content.image = UIImage(systemName: "rectangle.portrait.fill") |
| 1508 | content.imageProperties.tintColor = tab?.uiColor ?? .systemGray |
| 1509 | // Where the page is, as the desktop names it: notebook, groups and section. |
| 1510 | let groups: [String] = tab?.group.split(separator: "/").map(String.init) ?? [] |
| 1511 | let place = ([notebook.name] + groups + [tab?.name ?? ""]).filter { !$0.isEmpty }.joined(separator: " › ") |
| 1512 | let detail = NSMutableAttributedString( |
| 1513 | string: place + "\n", |
| 1514 | attributes: [.font: UIFont.preferredFont(forTextStyle: .footnote), .foregroundColor: UIColor.secondaryLabel]) |
| 1515 | detail.append( |
| 1516 | marked( |
| 1517 | page.snippet, page.snippetHits, font: .preferredFont(forTextStyle: .subheadline), |
| 1518 | color: .secondaryLabel)) |
| 1519 | content.secondaryAttributedText = detail |
| 1520 | content.secondaryTextProperties.numberOfLines = 3 |
| 1521 | cell.contentConfiguration = content |
| 1522 | return cell |
| 1523 | } |
| 1524 | |
| 1525 | /// `text` with `hits`, UTF-16 ranges, marked in OneNote's yellow as the desktop marks them. |
| 1526 | private func marked(_ text: String, _ hits: [[Int]], font: UIFont, color: UIColor) -> NSAttributedString { |
| 1527 | let marked = NSMutableAttributedString(string: text, attributes: [.font: font, .foregroundColor: color]) |
| 1528 | for hit in hits where hit.count == 2 && hit[1] <= marked.length { |
| 1529 | marked.addAttributes( |
| 1530 | [.backgroundColor: UIColor(red: 1, green: 0.82, blue: 0, alpha: 0.45), .foregroundColor: UIColor.label], |
| 1531 | range: NSRange(location: hit[0], length: hit[1] - hit[0])) |
| 1532 | } |
| 1533 | return marked |
| 1534 | } |
| 1535 | |
| 1536 | override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { |
| 1537 | let (page, notebook) = result(indexPath) |
| 1538 | (view.window?.windowScene?.delegate as? SceneDelegate)? |
| 1539 | .open(page.section, of: notebook, page: page.page, reveal: .text(query)) |
| 1540 | } |
| 1541 | } |