| 1 | import PhotosUI |
| 2 | import UIKit |
| 3 | |
| 4 | /// What a page shows selected as it opens. |
| 5 | enum Reveal { |
| 6 | /// The first match of a search. |
| 7 | case text(String) |
| 8 | /// A paragraph the Tags Summary lists, by id. |
| 9 | case paragraph(String) |
| 10 | } |
| 11 | |
| 12 | final class PageViewController: UIViewController, PHPickerViewControllerDelegate, |
| 13 | UIImagePickerControllerDelegate, UINavigationControllerDelegate |
| 14 | { |
| 15 | /// Posted when the app leaves the screen or quits: marked text is committed so it saves. |
| 16 | static let leaving = Notification.Name("SnowboundLeaving") |
| 17 | |
| 18 | private var section: Section? |
| 19 | private let page: String |
| 20 | var notebook: Notebook? { section?.notebook } |
| 21 | private let reveal: Reveal? |
| 22 | private let titleFocus: Bool |
| 23 | private lazy var canvas = CanvasView(section: section, page: page) |
| 24 | private let bar = ConflictBar() |
| 25 | /// What records or plays on this page, over its foot. |
| 26 | private let media = MediaBar() |
| 27 | private var playback: Playback? |
| 28 | private var mediaClock: Timer? |
| 29 | /// Reading View, beside the page menu where the page has one. |
| 30 | private var reader: UIBarButtonItem? |
| 31 | /// Opens another page or conflict page of the section. |
| 32 | var onOpen: ((String) -> Void)? |
| 33 | private lazy var undo = UIBarButtonItem( |
| 34 | title: "undo", image: UIImage(systemName: "arrow.uturn.backward"), primaryAction: UIAction { [weak self] _ in self?.canvas.undo(redo: false) }) |
| 35 | private lazy var redo = UIBarButtonItem( |
| 36 | title: "redo", image: UIImage(systemName: "arrow.uturn.forward"), primaryAction: UIAction { [weak self] _ in self?.canvas.undo(redo: true) }) |
| 37 | /// Shows the drawing tools, which a finger then draws with too. |
| 38 | private lazy var draw = UIBarButtonItem( |
| 39 | title: "Draw", image: UIImage(systemName: "pencil.tip.crop.circle"), |
| 40 | primaryAction: UIAction { [weak self] _ in |
| 41 | guard let canvas = self?.canvas else { return } |
| 42 | canvas.showPicker(!canvas.pickerShown) |
| 43 | }) |
| 44 | private lazy var more = UIBarButtonItem( |
| 45 | title: "Page", image: UIImage(systemName: "ellipsis.circle"), |
| 46 | menu: UIMenu(children: [UIDeferredMenuElement.uncached { [weak self] done in done(self?.pageMenu() ?? []) }])) |
| 47 | |
| 48 | init(section: Section, page: String, reveal: Reveal? = nil, titleFocus: Bool = false) { |
| 49 | self.section = section |
| 50 | self.page = page |
| 51 | self.reveal = reveal |
| 52 | self.titleFocus = titleFocus |
| 53 | super.init(nibName: nil, bundle: nil) |
| 54 | navigationItem.largeTitleDisplayMode = .never |
| 55 | navigationItem.rightBarButtonItems = [more, draw] |
| 56 | showTitle(section.row(of: page)?.row.title ?? "") |
| 57 | } |
| 58 | |
| 59 | required init?(coder: NSCoder) { fatalError() } |
| 60 | |
| 61 | /// Releases the canvas view, display link, timers, and section reference immediately so |
| 62 | /// the underlying section replica can close without waiting on UIKit transition cleanup. |
| 63 | func tearDown() { |
| 64 | NotificationCenter.default.removeObserver(self) |
| 65 | mediaClock?.invalidate() |
| 66 | mediaClock = nil |
| 67 | onOpen = nil |
| 68 | if isViewLoaded { canvas.tearDown() } |
| 69 | section = nil |
| 70 | } |
| 71 | |
| 72 | override func loadView() { |
| 73 | let view = UIView() |
| 74 | view.backgroundColor = .systemBackground |
| 75 | canvas.translatesAutoresizingMaskIntoConstraints = false |
| 76 | bar.translatesAutoresizingMaskIntoConstraints = false |
| 77 | view.addSubview(canvas) |
| 78 | view.addSubview(bar) |
| 79 | media.translatesAutoresizingMaskIntoConstraints = false |
| 80 | view.addSubview(media) |
| 81 | let wide = media.widthAnchor.constraint(equalToConstant: 480) |
| 82 | wide.priority = .required - 1 |
| 83 | NSLayoutConstraint.activate([ |
| 84 | wide, |
| 85 | media.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), |
| 86 | media.leadingAnchor.constraint(greaterThanOrEqualTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 12), |
| 87 | media.bottomAnchor.constraint(equalTo: view.keyboardLayoutGuide.topAnchor, constant: -12), |
| 88 | canvas.leadingAnchor.constraint(equalTo: view.leadingAnchor), |
| 89 | canvas.trailingAnchor.constraint(equalTo: view.trailingAnchor), |
| 90 | canvas.topAnchor.constraint(equalTo: view.topAnchor), |
| 91 | canvas.bottomAnchor.constraint(equalTo: view.bottomAnchor), |
| 92 | bar.leadingAnchor.constraint(equalTo: view.leadingAnchor), |
| 93 | bar.trailingAnchor.constraint(equalTo: view.trailingAnchor), |
| 94 | bar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), |
| 95 | ]) |
| 96 | self.view = view |
| 97 | canvas.onChange = { [weak self] in self?.editingChanged() } |
| 98 | canvas.onOpened = { [weak self] in self?.opened() } |
| 99 | canvas.onDate = { [weak self] field, date in self?.pickDate(field, date) } |
| 100 | canvas.onPlay = { [weak self] request in self?.play(request) } |
| 101 | media.onPause = { [weak self] in self?.pauseMedia() } |
| 102 | media.onStop = { [weak self] in self?.stopMedia() } |
| 103 | NotificationCenter.default.addObserver(self, selector: #selector(showMedia), name: Recorder.changed, object: nil) |
| 104 | canvas.formatBar.insert = { [weak self] in self?.insertActions() ?? [] } |
| 105 | canvas.formatBar.onPaper = { [weak self] in |
| 106 | // The keyboard would cover the picker's sheet. |
| 107 | _ = self?.canvas.resignFirstResponder() |
| 108 | self?.showPaper() |
| 109 | } |
| 110 | bar.onAction = { [weak self] in self?.conflictAction() } |
| 111 | NotificationCenter.default.addObserver( |
| 112 | self, selector: #selector(sectionChanged), name: Section.changed, object: section) |
| 113 | NotificationCenter.default.addObserver(self, selector: #selector(leaving), name: Self.leaving, object: nil) |
| 114 | conflictChanged() |
| 115 | registerForTraitChanges([UITraitHorizontalSizeClass.self]) { (controller: PageViewController, _) in |
| 116 | controller.fitTitle() |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | /// The page is on screen: a found word or tagged paragraph is selected, a new page's |
| 121 | /// title takes the caret. |
| 122 | private func opened() { |
| 123 | let revealed = |
| 124 | switch reveal { |
| 125 | case .text(let query): canvas.find(query) |
| 126 | case .paragraph(let id): canvas.selectParagraph(id) |
| 127 | case nil: false |
| 128 | } |
| 129 | if revealed || titleFocus && canvas.focusTitle() { |
| 130 | _ = canvas.becomeFirstResponder() |
| 131 | } |
| 132 | if canvas.reading?.offered == true { |
| 133 | reader = UIBarButtonItem( |
| 134 | title: "Reading View", image: UIImage(systemName: "text.justify.left"), |
| 135 | primaryAction: UIAction { [weak self] _ in self?.toggleReading() }) |
| 136 | editingChanged() |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | private func showTitle(_ title: String) { |
| 141 | self.title = title.isEmpty ? "Untitled Page" : title |
| 142 | } |
| 143 | |
| 144 | /// A phone's bar has no room for the title beside the editing buttons, and the page |
| 145 | /// shows it anyway, as Notes leaves it out. |
| 146 | private func fitTitle() { |
| 147 | let crowded = canvas.isFirstResponder && traitCollection.horizontalSizeClass == .compact |
| 148 | navigationItem.titleView = crowded ? UIView() : nil |
| 149 | } |
| 150 | |
| 151 | /// Undo and redo join the bar while editing or drawing; the format bar puts the keyboard |
| 152 | /// away. |
| 153 | private func editingChanged() { |
| 154 | if !canvas.readOnly, let title = canvas.pageTitle { |
| 155 | showTitle(title) |
| 156 | section?.retitle(page, title) |
| 157 | } |
| 158 | fitTitle() |
| 159 | draw.isSelected = canvas.pickerShown |
| 160 | draw.isEnabled = !canvas.readOnly |
| 161 | undo.isEnabled = canvas.canUndo(redo: false) |
| 162 | redo.isEnabled = canvas.canUndo(redo: true) |
| 163 | // Drawing keeps undo at hand, as typing does. |
| 164 | reader?.isSelected = canvas.readingShown |
| 165 | guard canvas.isFirstResponder || canvas.pickerShown else { |
| 166 | let resting = [more, draw] + (reader.map { [$0] } ?? []) |
| 167 | if navigationItem.rightBarButtonItems != resting { navigationItem.rightBarButtonItems = resting } |
| 168 | return |
| 169 | } |
| 170 | let editing = [more, draw, redo, undo] |
| 171 | if navigationItem.rightBarButtonItems != editing { navigationItem.rightBarButtonItems = editing } |
| 172 | } |
| 173 | |
| 174 | // MARK: Page menu |
| 175 | |
| 176 | /// The desktop's page commands that suit a touch screen. |
| 177 | private func pageMenu() -> [UIMenuElement] { |
| 178 | let scene = view.window?.windowScene?.delegate as? SceneDelegate |
| 179 | return [readingAction()] + [ |
| 180 | themeMenu(), |
| 181 | UIAction(title: "Tags Summary", image: UIImage(systemName: "tag")) { [weak self] _ in |
| 182 | guard let self, let section else { return } |
| 183 | scene?.showTags(of: section.notebook, from: self) |
| 184 | }, |
| 185 | UIMenu(options: .displayInline, children: [ |
| 186 | UIAction(title: "Print", image: UIImage(systemName: "printer")) { [weak self] _ in |
| 187 | self?.printPage(export: false) |
| 188 | }, |
| 189 | UIAction(title: "Export as PDF", image: UIImage(systemName: "doc.richtext")) { [weak self] _ in |
| 190 | self?.printPage(export: true) |
| 191 | }, |
| 192 | ]), |
| 193 | UIMenu(options: .displayInline, children: [ |
| 194 | UIAction(title: "New Subpage", image: UIImage(systemName: "text.badge.plus")) { _ in |
| 195 | scene?.newPage(subpage: true) |
| 196 | }, |
| 197 | UIAction(title: "Delete Page", image: UIImage(systemName: "trash"), attributes: .destructive) { |
| 198 | [weak self] _ in |
| 199 | guard let self, let section else { return } |
| 200 | section.delete([page]) |
| 201 | }, |
| 202 | ]), |
| 203 | ] |
| 204 | } |
| 205 | |
| 206 | /// The desktop's Insert tab, as the format bar's `+` offers it. |
| 207 | private func insertActions() -> [UIMenuElement] { |
| 208 | [ |
| 209 | UIAction(title: "Photo Library", image: UIImage(systemName: "photo.on.rectangle")) { [weak self] _ in |
| 210 | self?.pickPicture(camera: false) |
| 211 | }, |
| 212 | UIAction( |
| 213 | title: "Take Photo", image: UIImage(systemName: "camera"), |
| 214 | attributes: UIImagePickerController.isSourceTypeAvailable(.camera) ? [] : .disabled |
| 215 | ) { [weak self] _ in self?.pickPicture(camera: true) }, |
| 216 | UIMenu(options: .displayInline, children: [ |
| 217 | UIAction(title: "Date", image: UIImage(systemName: "calendar")) { [weak self] _ in |
| 218 | self?.canvas.insertDate(true, time: false) |
| 219 | }, |
| 220 | UIAction(title: "Time", image: UIImage(systemName: "clock")) { [weak self] _ in |
| 221 | self?.canvas.insertDate(false, time: true) |
| 222 | }, |
| 223 | UIAction(title: "Date & Time", image: UIImage(systemName: "calendar.badge.clock")) { [weak self] _ in |
| 224 | self?.canvas.insertDate(true, time: true) |
| 225 | }, |
| 226 | ]), |
| 227 | UIAction(title: "Space", image: UIImage(systemName: "arrow.up.and.down.text.horizontal")) { [weak self] _ in |
| 228 | self?.canvas.insertSpace() |
| 229 | }, |
| 230 | UIMenu(options: .displayInline, children: [ |
| 231 | UIAction( |
| 232 | title: "Record Audio", image: UIImage(systemName: "mic"), |
| 233 | attributes: Recorder.current == nil ? [] : .disabled |
| 234 | ) { [weak self] _ in self?.record(video: false) }, |
| 235 | UIAction( |
| 236 | title: "Record Video", image: UIImage(systemName: "video"), |
| 237 | attributes: Recorder.current == nil && Recorder.canRecordVideo ? [] : .disabled |
| 238 | ) { [weak self] _ in self?.record(video: true) }, |
| 239 | ]), |
| 240 | ] |
| 241 | } |
| 242 | |
| 243 | /// Reading View: the page reflowed into the screen's width where it reflows. |
| 244 | private func readingAction() -> UIAction { |
| 245 | let reading = canvas.reading |
| 246 | return UIAction( |
| 247 | title: "Reading View", |
| 248 | image: UIImage(systemName: "text.justify.left"), |
| 249 | attributes: reading?.offered == true || canvas.readingShown ? [] : .disabled, |
| 250 | state: canvas.readingShown ? .on : .off |
| 251 | ) { [weak self] _ in self?.toggleReading() } |
| 252 | } |
| 253 | |
| 254 | private func toggleReading() { |
| 255 | // A recording goes on the page as laid out. |
| 256 | guard Recorder.current?.canvas !== canvas else { return } |
| 257 | canvas.showReading(!canvas.readingShown) |
| 258 | } |
| 259 | |
| 260 | /// The page's theme, its section's and its notebook's, each pickable; the page wears a |
| 261 | /// new one when it opens again. |
| 262 | private func themeMenu() -> UIMenu { |
| 263 | guard let section, let themes = section.themes(of: page) else { |
| 264 | return UIMenu(title: "Theme", image: UIImage(systemName: "textformat"), children: []) |
| 265 | } |
| 266 | let scopes: [(String, String?)] = [ |
| 267 | ("This Page", themes.page), ("This Section", themes.section), ("This Notebook", themes.notebook), |
| 268 | ] |
| 269 | let page = page |
| 270 | let menus = scopes.enumerated().map { scope, entry in |
| 271 | let (title, current) = entry |
| 272 | let choices = [(nil as String?, "None")] + themes.themes.map { ($0.id, $0.name) } |
| 273 | return UIMenu(title: title, children: choices.map { id, name in |
| 274 | UIAction(title: name, state: id == current ? .on : .off) { [weak self] _ in |
| 275 | guard let self, let section = self.section else { return } |
| 276 | section.setTheme(id, scope: UInt8(scope), of: page) { [weak self] _ in |
| 277 | self?.onOpen?(page) |
| 278 | } |
| 279 | } |
| 280 | }) |
| 281 | } |
| 282 | return UIMenu(title: "Theme", image: UIImage(systemName: "textformat"), children: menus) |
| 283 | } |
| 284 | |
| 285 | /// Prints the page through the system's print sheet, or with `export` offers its PDF in |
| 286 | /// the share sheet, laid out as OneNote 2010 prints it on the region's paper. |
| 287 | private func printPage(export: Bool) { |
| 288 | guard let section else { return } |
| 289 | let letter = ["US", "CA", "MX", "PR", "PH", "CL", "CO", "VE", "GT", "CR", "PA", "DO", "SV", "NI", "HN", "BZ"] |
| 290 | .contains(Locale.current.region?.identifier ?? "US") |
| 291 | let paper = letter ? CGSize(width: 612, height: 792) : CGSize(width: 595.276, height: 841.89) |
| 292 | let title = canvas.pageTitle ?? section.row(of: page)?.row.title ?? "" |
| 293 | guard let pdf = canvas.pdf(paper: paper, section: section.tab.name) else { |
| 294 | return alert( |
| 295 | export ? "Couldn't Export the PDF" : "Couldn't Print", "The page could not be laid out on paper.") |
| 296 | } |
| 297 | if export { |
| 298 | let name = title.components(separatedBy: CharacterSet(charactersIn: "/\\:")).joined(separator: "-") |
| 299 | .trimmingCharacters(in: .whitespaces) |
| 300 | let file = FileManager.default.temporaryDirectory |
| 301 | .appendingPathComponent((name.isEmpty ? "Untitled" : name) + ".pdf") |
| 302 | do { |
| 303 | try pdf.write(to: file) |
| 304 | } catch { |
| 305 | return |
| 306 | } |
| 307 | let share = UIActivityViewController(activityItems: [file], applicationActivities: nil) |
| 308 | share.popoverPresentationController?.barButtonItem = more |
| 309 | present(share, animated: true) |
| 310 | } else { |
| 311 | let info = UIPrintInfo.printInfo() |
| 312 | info.jobName = title |
| 313 | let printer = UIPrintInteractionController.shared |
| 314 | printer.printInfo = info |
| 315 | printer.printingItem = pdf |
| 316 | printer.present(from: more, animated: true) |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | private func showPaper() { |
| 321 | let navigation = UINavigationController(rootViewController: PaperViewController(canvas: canvas)) |
| 322 | navigation.sheetPresentationController?.detents = [.medium(), .large()] |
| 323 | navigation.sheetPresentationController?.prefersGrabberVisible = true |
| 324 | navigation.sheetPresentationController?.largestUndimmedDetentIdentifier = .medium |
| 325 | present(navigation, animated: true) |
| 326 | } |
| 327 | |
| 328 | @objc private func leaving() { canvas.commitComposition() } |
| 329 | |
| 330 | override func viewWillDisappear(_ animated: Bool) { |
| 331 | super.viewWillDisappear(animated) |
| 332 | // A recording goes on the page it started on, as the desktop's does on leaving it. |
| 333 | if Recorder.current?.canvas === canvas { Recorder.current?.stop() } |
| 334 | stopPlayback() |
| 335 | } |
| 336 | |
| 337 | // MARK: Recording and playback |
| 338 | |
| 339 | func record(video: Bool) { |
| 340 | stopPlayback() |
| 341 | Recorder.start(video: video, on: canvas) { [weak self] title, message in self?.alert(title, message) } |
| 342 | } |
| 343 | |
| 344 | func stopRecording() { |
| 345 | if Recorder.current?.canvas === canvas { Recorder.current?.stop() } |
| 346 | } |
| 347 | |
| 348 | private func play(_ request: PlayRequest) { |
| 349 | guard Recorder.current == nil else { return } |
| 350 | playback = Playback(request) |
| 351 | showMedia() |
| 352 | } |
| 353 | |
| 354 | private func stopPlayback() { |
| 355 | guard playback != nil else { return } |
| 356 | playback = nil |
| 357 | canvas.played(at: nil) |
| 358 | showMedia() |
| 359 | } |
| 360 | |
| 361 | private func pauseMedia() { |
| 362 | if let recorder = Recorder.current, recorder.canvas === canvas { |
| 363 | recorder.pause(!(recorder.elapsed?.paused ?? false)) |
| 364 | } else { |
| 365 | playback?.toggle() |
| 366 | } |
| 367 | showMedia() |
| 368 | } |
| 369 | |
| 370 | private func stopMedia() { |
| 371 | if Recorder.current?.canvas === canvas { |
| 372 | Recorder.current?.stop() |
| 373 | } else { |
| 374 | stopPlayback() |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | /// The bar shows the clock of what records or plays, and a video's picture as it plays. |
| 379 | @objc private func showMedia() { |
| 380 | if let recorder = Recorder.current, recorder.canvas === canvas { |
| 381 | media.picture.isHidden = true |
| 382 | if recorder.saving { |
| 383 | media.showSaving(recorder.video ? "Saving video…" : "Saving audio…") |
| 384 | } else if let elapsed = recorder.elapsed { |
| 385 | let state = elapsed.paused ? "Paused" : recorder.video ? "Recording video" : "Recording" |
| 386 | media.show( |
| 387 | "\(state) \(MediaBar.clock(elapsed.ms))", recording: true, |
| 388 | paused: recorder.pausable ? elapsed.paused : nil) |
| 389 | } |
| 390 | } else if let playback { |
| 391 | if playback.failed { |
| 392 | stopPlayback() |
| 393 | return alert("Couldn't Play the Recording", "This kind of recording doesn't play on this device.") |
| 394 | } |
| 395 | let total = playback.durationMs.map { " / " + MediaBar.clock($0) } ?? "" |
| 396 | media.show( |
| 397 | "\(playback.request.name) \(MediaBar.clock(playback.ms))\(total)", recording: false, |
| 398 | paused: !playback.playing, playing: true) |
| 399 | if let picture = playback.picture() { media.picture.image = picture } |
| 400 | media.picture.isHidden = playback.request.video == nil |
| 401 | canvas.played(at: playback.ms) |
| 402 | } else { |
| 403 | media.isHidden = true |
| 404 | canvas.bottomInset = 0 |
| 405 | mediaClock?.invalidate() |
| 406 | mediaClock = nil |
| 407 | return |
| 408 | } |
| 409 | // The line being written stays above the bar. |
| 410 | canvas.bottomInset = view.keyboardLayoutGuide.layoutFrame.minY - media.frame.minY |
| 411 | if mediaClock == nil { |
| 412 | mediaClock = Timer.scheduledTimer(withTimeInterval: 1.0 / 15, repeats: true) { [weak self] _ in |
| 413 | self?.showMedia() |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | @objc private func sectionChanged(_ notification: Notification) { |
| 419 | let flags = notification.userInfo?["flags"] as? UInt32 ?? 0 |
| 420 | if flags & Section.rejected != 0 { |
| 421 | let kept = canvas.keep() |
| 422 | canvas.reload(discard: true) |
| 423 | alert("Change Not Saved", "The page shows what was last saved." |
| 424 | + (kept ? " Your version is kept as a separate page." : "")) |
| 425 | } else if flags & Section.remote != 0 { |
| 426 | canvas.reload(discard: false) |
| 427 | } else { |
| 428 | canvas.reload(discard: false, pendingOnly: true) |
| 429 | if notification.userInfo?["unchanged"] as? Bool == true { return } |
| 430 | } |
| 431 | if flags & Section.listed != 0, let section { |
| 432 | if section.row(of: page) == nil { |
| 433 | // Deleted elsewhere, or a conflict page resolved: back to what the section lists. |
| 434 | if let first = section.rows.first { onOpen?(first.id) } |
| 435 | return |
| 436 | } |
| 437 | conflictChanged() |
| 438 | } |
| 439 | showStatus() |
| 440 | } |
| 441 | |
| 442 | /// Only trouble shows: saving goes on quietly, as Notes saves. |
| 443 | private func showStatus() { |
| 444 | let status: String? = |
| 445 | switch section?.status { |
| 446 | case .offline: "Offline" |
| 447 | case .notSaving: "Not Saving" |
| 448 | default: nil |
| 449 | } |
| 450 | if #available(iOS 26, *) { |
| 451 | navigationItem.subtitle = status |
| 452 | } else { |
| 453 | navigationItem.prompt = status |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | // MARK: Conflicts |
| 458 | |
| 459 | private func conflictChanged() { |
| 460 | guard let section, let (row, version) = section.row(of: page) else { return bar.show(nil) } |
| 461 | if version != nil { |
| 462 | // Deleting a conflict page cannot be undone, so the button asks first. |
| 463 | let delete = UIAction( |
| 464 | title: "Delete Conflict Page", image: UIImage(systemName: "trash"), attributes: .destructive |
| 465 | ) { [weak self] _ in self?.conflictAction() } |
| 466 | bar.show( |
| 467 | "Changes in red couldn’t be merged. This version can’t be edited.", action: "Delete", |
| 468 | menu: UIMenu(children: [delete])) |
| 469 | } else if !row.versions.isEmpty { |
| 470 | bar.show("This page has changes that couldn’t be merged.", action: "See Version") |
| 471 | } else { |
| 472 | bar.show(nil) |
| 473 | } |
| 474 | canvas.topInset = bar.isHidden ? 0 : bar.systemLayoutSizeFitting(view.bounds.size).height |
| 475 | } |
| 476 | |
| 477 | private func conflictAction() { |
| 478 | guard let section, let (row, version) = section.row(of: page) else { return } |
| 479 | if version != nil { |
| 480 | section.delete([page]) { [weak self] in self?.onOpen?(row.id) } |
| 481 | } else if let newest = row.versions.max(by: { ($0.created ?? 0) < ($1.created ?? 0) }) { |
| 482 | onOpen?(newest.id) |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | // MARK: Date |
| 487 | |
| 488 | /// Changes the page's date or time, as OneNote's date and time under the title do. |
| 489 | private func pickDate(_ field: DateField, _ shown: Date) { |
| 490 | let picker = UIDatePicker() |
| 491 | picker.datePickerMode = field == .date ? .date : .time |
| 492 | picker.preferredDatePickerStyle = field == .date ? .inline : .wheels |
| 493 | picker.date = shown |
| 494 | picker.minimumDate = Date(timeIntervalSince1970: -11_644_473_600) |
| 495 | picker.accessibilityLabel = field == .date ? "Page date" : "Page time" |
| 496 | let controller = UIViewController() |
| 497 | controller.title = field == .date ? "Change Page Date" : "Change Page Time" |
| 498 | picker.translatesAutoresizingMaskIntoConstraints = false |
| 499 | controller.view.backgroundColor = .systemBackground |
| 500 | controller.view.addSubview(picker) |
| 501 | NSLayoutConstraint.activate([ |
| 502 | picker.centerXAnchor.constraint(equalTo: controller.view.centerXAnchor), |
| 503 | picker.topAnchor.constraint(equalTo: controller.view.safeAreaLayoutGuide.topAnchor, constant: 8), |
| 504 | picker.widthAnchor.constraint(lessThanOrEqualTo: controller.view.widthAnchor, constant: -32), |
| 505 | ]) |
| 506 | controller.navigationItem.leftBarButtonItem = UIBarButtonItem( |
| 507 | systemItem: .cancel, primaryAction: UIAction { [weak self] _ in self?.dismiss(animated: true) }) |
| 508 | controller.navigationItem.rightBarButtonItem = UIBarButtonItem( |
| 509 | title: "Apply", |
| 510 | primaryAction: UIAction { [weak self] _ in |
| 511 | // The field not being changed keeps what the page had. |
| 512 | let calendar = Calendar.current |
| 513 | let kept: Set<Calendar.Component> = field == .date ? [.hour, .minute, .second] : [.era, .year, .month, .day] |
| 514 | let changed: Set<Calendar.Component> = field == .date ? [.era, .year, .month, .day] : [.hour, .minute] |
| 515 | var components = calendar.dateComponents(kept, from: shown) |
| 516 | let chosen = calendar.dateComponents(changed, from: picker.date) |
| 517 | for component in changed { components.setValue(chosen.value(for: component), for: component) } |
| 518 | if field == .time { components.second = calendar.component(.second, from: shown) } |
| 519 | self?.dismiss(animated: true) |
| 520 | if let date = calendar.date(from: components) { self?.canvas.changeDate(date) } |
| 521 | }) |
| 522 | let navigation = UINavigationController(rootViewController: controller) |
| 523 | navigation.sheetPresentationController?.detents = field == .date ? [.large()] : [.medium()] |
| 524 | present(navigation, animated: true) |
| 525 | } |
| 526 | |
| 527 | // MARK: Pictures |
| 528 | |
| 529 | private func pickPicture(camera: Bool) { |
| 530 | if camera { |
| 531 | guard UIImagePickerController.isSourceTypeAvailable(.camera) else { return } |
| 532 | let picker = UIImagePickerController() |
| 533 | picker.sourceType = .camera |
| 534 | picker.delegate = self |
| 535 | present(picker, animated: true) |
| 536 | } else { |
| 537 | var configuration = PHPickerConfiguration() |
| 538 | configuration.filter = .images |
| 539 | let picker = PHPickerViewController(configuration: configuration) |
| 540 | picker.delegate = self |
| 541 | present(picker, animated: true) |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) { |
| 546 | picker.dismiss(animated: true) |
| 547 | guard let provider = results.first?.itemProvider, provider.canLoadObject(ofClass: UIImage.self) else { return } |
| 548 | provider.loadObject(ofClass: UIImage.self) { [weak self] image, _ in |
| 549 | guard let image = image as? UIImage else { return } |
| 550 | DispatchQueue.main.async { self?.canvas.insertPicture(image) } |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | func imagePickerController( |
| 555 | _ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] |
| 556 | ) { |
| 557 | picker.dismiss(animated: true) |
| 558 | if let image = info[.originalImage] as? UIImage { canvas.insertPicture(image) } |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | /// OneNote's information bar above a page whose changes could not all be merged. |
| 563 | final class ConflictBar: UIView { |
| 564 | private let label = UILabel() |
| 565 | private let button = UIButton(configuration: .bordered()) |
| 566 | var onAction: (() -> Void)? |
| 567 | |
| 568 | init() { |
| 569 | super.init(frame: .zero) |
| 570 | backgroundColor = UIColor { $0.userInterfaceStyle == .dark ? UIColor(red: 0.35, green: 0.28, blue: 0.1, alpha: 1) : UIColor(red: 1, green: 0.93, blue: 0.76, alpha: 1) } |
| 571 | let icon = UIImageView(image: UIImage(systemName: "exclamationmark.triangle.fill")) |
| 572 | icon.tintColor = .systemOrange |
| 573 | icon.setContentHuggingPriority(.required, for: .horizontal) |
| 574 | label.font = .preferredFont(forTextStyle: .footnote) |
| 575 | label.numberOfLines = 0 |
| 576 | button.addAction( |
| 577 | UIAction { [weak self] _ in |
| 578 | if self?.button.menu == nil { self?.onAction?() } |
| 579 | }, for: .primaryActionTriggered) |
| 580 | button.setContentHuggingPriority(.required, for: .horizontal) |
| 581 | let stack = UIStackView(arrangedSubviews: [icon, label, button]) |
| 582 | stack.spacing = 10 |
| 583 | stack.alignment = .center |
| 584 | stack.translatesAutoresizingMaskIntoConstraints = false |
| 585 | addSubview(stack) |
| 586 | NSLayoutConstraint.activate([ |
| 587 | stack.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor), |
| 588 | stack.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor), |
| 589 | stack.topAnchor.constraint(equalTo: topAnchor, constant: 8), |
| 590 | stack.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8), |
| 591 | ]) |
| 592 | isHidden = true |
| 593 | } |
| 594 | |
| 595 | required init?(coder: NSCoder) { fatalError() } |
| 596 | |
| 597 | /// Shows `message` with a button titled `action`, which opens `menu` when there is one. |
| 598 | func show(_ message: String?, action: String = "", menu: UIMenu? = nil) { |
| 599 | isHidden = message == nil |
| 600 | label.text = message |
| 601 | button.configuration?.title = action |
| 602 | button.menu = menu |
| 603 | button.showsMenuAsPrimaryAction = menu != nil |
| 604 | } |
| 605 | } |