// The book reader: an EPUB or a PDF, full screen, paged, in its face. // // What the reader shows is the core's (`shell.reader`, `phone::reader`): // where the book opens, the face worn and the knobs, the bar's words, the // fan's tiers and the highlights. The reader draws it and reports what the // person does — where the page stands (`reader.moved`), a highlight made, // recoloured, noted or removed (`reader.highlight`), a face or a knob chosen // (`reader.settings`) — and the core decides what is written and when: the // two-second rule, the first page's Reading, the face_settings row. // // Both formats open through Readium (`ReadiumStreamer` reads the file into a // `Publication`, `ReadiumNavigator` shows it): the EPUB navigator paginates // each chapter in a web view with Readium CSS, the PDF navigator pages // PDFKit with a page view controller. Either says where the reader is as a // Locator, which goes to the core as it is. // // The page is the whole screen, safe areas included, in the face's ground // (`ReaderFace`): the EPUB's web page takes the face's ground and ink // (`ReaderLook`), a PDF its ground and, on Night, a multiply dimming. A tap // in the middle of the page shows and hides the chrome together // (`ReaderChrome`): the running head, the page number at the foot and the // bar under it — back, the chapter, how far through, and the hand. The hand // opens its one tier at the hub (`ReaderFan`), the faces then the knobs; a // choice is applied at once (`submitPreferences`), never on a reopen. Pages // turn by swipe and by a tap on either edge, through Readium's own input // observers (`DirectionalNavigationAdapter`), never a SwiftUI gesture over // the page. // // A selection in an EPUB offers the pencils at the hub; a pencil makes a // highlight and the page draws it as a pencil line under the words // (Readium's underline decoration). Every highlight of the book is drawn at // open; a tap on one opens its own tier. Readium 3.11.1's PDF navigator // draws no decorations, so a PDF is read without highlights. #if os(iOS) import CottonKit import CottonMailbox import CottonPaper import CottonValues import PDFKit import ReadiumNavigator import ReadiumShared import ReadiumStreamer import os import SwiftUI import UIKit // MARK: - The screen /// One book, from the core's answer to its first page. struct BookReaderScreen: View { let opening: ReaderOpening let close: () -> Void @Environment(\.cottonCore) private var core @Environment(\.readerPresenter) private var presenter @Environment(\.recordsRevision) private var revision @State private var reading: BookReading? /// The line said in place of the book when it does not open. @State private var refusal: String? var body: some View { ZStack { (reading?.face ?? .paper).ground.ignoresSafeArea() if let reading { // The page keeps the safe area: Readium measures its inset from // the view's own top, and the head stands under the status bar. BookPages(reading: reading) ReaderChrome(reading: reading, close: done) ReaderFan(reading: reading) .frame(maxHeight: .infinity, alignment: .bottom) if reading.contentsShown, let seek = reading.seek { ReaderContents(reading: reading, seek: seek) .transition(.opacity) } if let writing = reading.noting { DeckLineInput(writing: writing, commit: { reading.note($0) }, dismiss: { reading.stopNoting() }) } } else if let refusal { VStack(spacing: 0) { ReaderBackButton(ink: ReaderFace.paper.ink, close: done) .frame(maxWidth: .infinity, alignment: .leading) Spacer() } Text(refusal) .font(CottonFonts.caslon(17)) .multilineTextAlignment(.center) .foregroundStyle(ReaderFace.paper.secondary) .padding(.horizontal, 32) } else { ProgressView() } } .animation(.easeOut(duration: 0.15), value: reading?.chromeShown) .animation(.easeOut(duration: 0.2), value: reading?.face) .animation(.easeOut(duration: 0.15), value: reading?.contentsShown) .statusBarHidden(!(reading?.chromeShown ?? true)) .task { await open() } .onChange(of: revision) { _, _ in Task { await reading?.readSettings() } } .onChange(of: presenter?.jump) { _, jump in guard let jump, jump.id == opening.id, let at = jump.at else { return } presenter?.jump = nil Task { await reading?.go(to: at) } } } private func open() async { guard reading == nil, let core else { return } do { reading = try await BookReading.open(opening, core: core) } catch let refused as ReaderRefused { refusal = refused.line } catch { Log.write("reader: \(opening.id) did not open: \(String(describing: error))") refusal = ShellLines.line("cards", "book.could_not_open") } } private func done() { reading?.closing() close() } } /// The book does not open, and the core's line says why. struct ReaderRefused: Error { let line: String } // MARK: - The reading /// One open book: the publication, the navigator, the face it is worn in, /// the fan and the highlights, as the core last answered them. @MainActor @Observable final class BookReading { private static let log = Logger(subsystem: "com.cottondb.books", category: "reader") /// How often the phone's light and dark is read again, for a face that follows it. private static let lightEvery: TimeInterval = 15 let book: String let title: String let format: BookFormat @ObservationIgnored let publication: Publication @ObservationIgnored let navigator: VisualNavigator & UIViewController @ObservationIgnored let core: any CottonCalling /// The fan's tiers over the page's foot (`ReaderFan`), rooted empty: a /// tier stands on it while one is open. @ObservationIgnored let tiers: FanTiers @ObservationIgnored private var lightClock: Timer? /// The core asked to be told again (`again_ms`): a place waits to be written. @ObservationIgnored private var dueClock: Timer? @ObservationIgnored private var watchers: [NSObjectProtocol] = [] @ObservationIgnored private let delegate = BookNavigatorDelegate() @ObservationIgnored private var turns: DirectionalNavigationAdapter? @ObservationIgnored private var dimming: ReaderDimming? /// The book's contents, until a report has carried them to the core. @ObservationIgnored private var unsentContents: ReaderReport.Contents? /// The reports in the order made: each goes once the one before is answered. @ObservationIgnored private var reporting: Task? /// When the open was asked, until the first page says where it is. @ObservationIgnored private var began: ContinuousClock.Instant? /// The chrome stands (`ReaderChrome`); a middle tap shows or hides it. var chromeShown = false /// The bar's words for how far through ("42%"), the chapter, and the page /// number at the foot, as the core says them. private(set) var progressWords: String? private(set) var chapter: String? private(set) var pageWords: String? private(set) var settings: ReaderSettings private(set) var fan: ReaderFanAnswer /// The phone is in dark mode (the system's, which the light shell never /// follows; a face may). private(set) var phoneDark: Bool private(set) var highlights: [BookHighlight] = [] /// A selection the selection tier stands for. private(set) var selection: BookSelection? /// The short-text input over the page while a highlight's note is /// written, and the highlight it writes. private(set) var noting: DeckWriting? @ObservationIgnored private var notingHighlight: String? /// The seek line as the core last answered it (`ReaderSeek`); nil until /// the chrome first shows. var seek: ReaderSeekAnswer? /// The Back a jump left, while it stands. var backSlip: ReaderBackAnswer? /// The slip's words over the finger, while it is down on the line. var seekSlip: String? /// Where a jump was let go, until the line is read again after it lands. var seekLanding: Double? /// The contents stand over the page. var contentsShown = false @ObservationIgnored var backClock: Timer? @ObservationIgnored var seekSaying: Task? @ObservationIgnored var seekWanted: Double? @ObservationIgnored var seekTicksPassed: Int? /// The face the page is worn in now. var face: ReaderFace { settings.worn } /// The core's answer read, the file kept here and opened, the navigator /// made in the face, at the place the core says. static func open(_ opening: ReaderOpening, core: any CottonCalling) async throws -> BookReading { let began = ContinuousClock.now let phoneDark = UIScreen.main.traitCollection.userInterfaceStyle == .dark let answer = try await core.call(ReaderCalls.reader, ReaderReport(book: opening.id, at: opening.at, dark: phoneDark), as: ReaderAnswer.self) if let refusal = answer.refusal { throw ReaderRefused(line: refusal) } guard let file = answer.file, let format = answer.bookFormat, let settings = answer.settings, let fan = answer.fan, let refusals = answer.refusals else { throw CocoaError(.fileReadCorruptFile) } let url = try await BookKeeper.shared.file(for: file) let publication: Publication do { publication = try await BookNavigators.publication(at: url, format: format) } catch is BookLocked { throw ReaderRefused(line: refusals.locked) } catch { Log.write("reader: \(opening.id) did not open: \(String(describing: error))") throw ReaderRefused(line: refusals.unopened) } let start = try answer.at.map { try Locator(jsonString: $0.locator) } Self.log.notice("book \(opening.id, privacy: .public) opens at \(start?.href.string ?? "-", privacy: .public) \(start?.locations.progression ?? 0, privacy: .public)") let navigator = try BookNavigators.navigator(for: publication, format: format, at: start, settings: settings, face: settings.worn) let reading = BookReading(answer: answer, title: answer.title ?? "", format: format, publication: publication, navigator: navigator, core: core, settings: settings, fan: fan, phoneDark: phoneDark) reading.delegate.landing = start.flatMap(BookNavigators.landsLate) reading.began = began await reading.readContents() reading.draw() return reading } private init(answer: ReaderAnswer, title: String, format: BookFormat, publication: Publication, navigator: VisualNavigator & UIViewController, core: any CottonCalling, settings: ReaderSettings, fan: ReaderFanAnswer, phoneDark: Bool) { book = answer.book self.title = title self.format = format self.publication = publication self.navigator = navigator self.core = core self.settings = settings self.fan = fan self.phoneDark = phoneDark progressWords = answer.progressWords chapter = answer.at?.chapter pageWords = answer.at?.pageLabel // A PDF draws no decorations: its highlights are not held. highlights = navigator is EPUBNavigatorViewController ? answer.highlights ?? [] : [] let tiers = FanTiers() tiers.setRoot(FanTier(id: "reader-root", cards: [])) self.tiers = tiers delegate.reading = self if let epub = navigator as? EPUBNavigatorViewController { epub.delegate = delegate epub.observeDecorationInteractions(inGroup: Self.decorations) { [weak self] event in self?.openHighlight(event.decoration.id) } } if let pdf = navigator as? PDFNavigatorViewController { pdf.delegate = delegate } // Edge taps, swipes and the keyboard turn pages; a tap the adapter // did not take (the middle of the page) closes an open tier, else // shows or hides the chrome. let turns = DirectionalNavigationAdapter() turns.bind(to: navigator) self.turns = turns _ = navigator.addObserver(.tap { [weak self] _ in guard let self else { return false } if self.tiers.closes { self.closeFan() } else { self.chromeShown.toggle() if self.chromeShown { self.readSeek() } } return true }) dim() watch() } // MARK: Where the reader is private var appActive: Bool { UIApplication.shared.applicationState == .active } /// The navigator moved: the place, and a PDF page's printed label, go to the core. fileprivate func moved(to locator: Locator) { if let began { // The first page's latency, for a walk or a report to read. let elapsed = ContinuousClock.now - began Log.write("reader: first \(format.rawValue) page in \(elapsed.components.seconds * 1000 + elapsed.components.attoseconds / 1_000_000_000_000_000) ms") self.began = nil } dim() guard let at = try? locator.jsonString() else { return } var report = ReaderReport(book: book, at: at, active: appActive) if format == .pdf, let page = locator.locations.position { let label = (navigator as? PDFNavigatorViewController)?.pdfView?.document?.page(at: page - 1)?.label report.pageLabel = .some(label.flatMap { $0.isEmpty ? nil : $0 }) } send(report) } /// One report, after the ones before it; the core's answer is drawn. func send(_ report: ReaderReport) { var report = report if let contents = unsentContents { report.contents = contents unsentContents = nil } let previous = reporting let core = core reporting = Task { [weak self] in await previous?.value do { let answer = try await core.call(ReaderCalls.moved, report, as: ReaderMovedAnswer.self) self?.heard(answer) } catch { Log.write("reader: the place was not reported: \(String(describing: error))") } } } private func heard(_ answer: ReaderMovedAnswer) { if let at = answer.at { chapter = at.chapter pageWords = at.pageLabel } progressWords = answer.progressWords ?? progressWords stands(answer.back) // The line follows the page while it shows. if chromeShown { readSeek() } dueClock?.invalidate() dueClock = nil guard let ms = answer.againMs else { return } dueClock = Timer.scheduledTimer(withTimeInterval: Double(ms) / 1000, repeats: false) { [weak self] _ in MainActor.assumeIsolated { guard let self else { return } self.send(ReaderReport(book: self.book, active: self.appActive)) } } } /// The contents, flattened in reading order, for the core to say the /// chapter a place is in. private func readContents() async { // Readium's contents service is read off the main actor; the // publication is only read there, never changed. nonisolated(unsafe) let publication = publication guard let toc = try? await publication.tableOfContents().get() else { return } func flat(_ links: [ReadiumShared.Link]) -> [ReaderReport.Contents.Entry] { links.flatMap { [ReaderReport.Contents.Entry(title: $0.title ?? "", href: $0.href)] + flat($0.children) } } // Where each resource begins and, for a PDF, how many pages: the seek line's. let positions = (try? await publication.positionsByReadingOrder().get()) ?? [] let (starts, pages) = ReaderSeekMeasures.of(firsts: positions.map { $0.first?.locations.totalProgression }, resources: publication.readingOrder.count, positions: positions.reduce(0) { $0 + $1.count }, pdf: format == .pdf) unsentContents = ReaderReport.Contents(toc: flat(toc), readingOrder: publication.readingOrder.map(\.href), starts: starts, pages: pages) } /// The reader closes: the core writes the last place, the clocks stop. func closing() { send(ReaderReport(book: book, active: appActive, closing: true)) lightClock?.invalidate() lightClock = nil dueClock?.invalidate() dueClock = nil backClock?.invalidate() backClock = nil watchers.forEach(NotificationCenter.default.removeObserver) watchers = [] } private func watch() { // The phone's light and dark, for a face that follows it, is read // again on a clock and whenever the app is active again (Control // Centre's switch passes through inactive): the screen's own trait, // which the light-only app's windows never take. lightClock = Timer.scheduledTimer(withTimeInterval: Self.lightEvery, repeats: true) { [weak self] _ in MainActor.assumeIsolated { self?.readPhoneLight() } } let center = NotificationCenter.default watchers.append(center.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { guard let self else { return } self.send(ReaderReport(book: self.book, active: false)) } }) watchers.append(center.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { guard let self else { return } self.send(ReaderReport(book: self.book, active: true)) self.readPhoneLight() } }) } /// The phone's light and dark read again: the core says the face worn. private func readPhoneLight() { let dark = UIScreen.main.traitCollection.userInterfaceStyle == .dark guard dark != phoneDark else { return } phoneDark = dark Task { await readSettings() } } /// `reader.open { at }` on a book already open: the navigator goes there. func go(to at: String) async { guard let locator = try? Locator(jsonString: at) else { return } _ = await navigator.go(to: locator) } // MARK: The face and the knobs /// The settings read again (another phone's choice, synced, or the /// phone's light changed): the page wears them at once. func readSettings() async { do { let answer = try await core.call(ReaderCalls.reader, ReaderReport(book: book, dark: phoneDark), as: ReaderAnswer.self) guard let settings = answer.settings, let fan = answer.fan else { return } wearing(settings, fan) } catch { Log.write("reader: the reader's settings were not read: \(String(describing: error))") } } /// A face chosen on the hand's tier. func wear(_ face: String) { Task { await choose(ReaderReport(dark: phoneDark, face: face)) } } /// A knob set to one of its choices. func set(_ knob: String, to value: RecordValue) async { await choose(ReaderReport(dark: phoneDark, knob: knob, value: value)) } private func choose(_ report: ReaderReport) async { do { let answer = try await core.call(ReaderCalls.settings, report, as: ReaderSettingsAnswer.self) wearing(answer.settings, answer.fan) } catch { Log.write("reader: the reader's settings were not written: \(String(describing: error))") } } /// The page in the settings the core answered. private func wearing(_ settings: ReaderSettings, _ fan: ReaderFanAnswer) { let changed = settings != self.settings self.fan = fan guard changed else { return } self.settings = settings apply() refreshTier() } /// The page in the face and knobs as they stand. private func apply() { let face = self.face if let epub = navigator as? EPUBNavigatorViewController { epub.submitPreferences(ReaderLook.epub(settings, face: face)) } else if let pdf = navigator as? PDFNavigatorViewController { pdf.submitPreferences(ReaderLook.pdf(settings, face: face)) } dim() } /// Night on a PDF dims the page through a multiply sheet; every other /// face takes it away. private func dim() { guard format == .pdf else { return } if face == .night { // Pinned, not framed: the navigator has no size yet at open. And // brought forward each time, as Readium lays a new PDF view over it. let host: UIView = navigator.view if dimming == nil { let sheet = ReaderDimming() sheet.translatesAutoresizingMaskIntoConstraints = false host.addSubview(sheet) NSLayoutConstraint.activate([ sheet.topAnchor.constraint(equalTo: host.topAnchor), sheet.bottomAnchor.constraint(equalTo: host.bottomAnchor), sheet.leadingAnchor.constraint(equalTo: host.leadingAnchor), sheet.trailingAnchor.constraint(equalTo: host.trailingAnchor), ]) dimming = sheet } if let dimming { host.bringSubviewToFront(dimming) } } else { dimming?.removeFromSuperview() dimming = nil } } // MARK: Highlights static let decorations: DecorationGroup = "highlights" /// The page's pencil lines, as the highlights stand. fileprivate func draw() { guard let epub = navigator as? EPUBNavigatorViewController else { return } let decorations = highlights.compactMap { highlight -> Decoration? in let place: Locator? do { place = try Locator(jsonString: highlight.at) } catch { Log.write("reader: highlight \(highlight.id) has no place to draw at: \(String(describing: error))") return nil } guard let place else { Log.write("reader: highlight \(highlight.id) has no place to draw at"); return nil } return Decoration(id: highlight.id, locator: place, style: .underline(tint: UIColor(highlight.pencil.colour))) } epub.apply(decorations: decorations, in: Self.decorations) } /// Text selected on the page: the pencils at the hub. Readium's own menu /// still stands beside them, with Copy alone. fileprivate func selected(_ selection: Selection) { guard let text = selection.locator.text.highlight, !text.isEmpty, let at = try? selection.locator.jsonString() else { return } self.selection = BookSelection(words: text, at: at) openSelection() } /// A pencil on the selection (none for Note, which the core makes in /// its own): the core makes the row and the page draws its line; Note /// opens the short-text input for the note. func mark(with pencil: HighlightPencil?, noting: Bool = false) { guard let selection else { return } self.selection = nil (navigator as? SelectableNavigator)?.clearSelection() closeFan() let report = ReaderReport(book: book, at: selection.at, pencil: pencil?.rawValue, words: selection.words) Task { do { let made = try await core.call(ReaderCalls.highlight, report, as: BookHighlight.self) highlights.append(made) draw() if noting { startNoting(made.id) } } catch { Log.write("reader: the highlight was not kept: \(String(describing: error))") } } } /// A drawn highlight recoloured. func recolour(_ id: String, to pencil: HighlightPencil) { guard let at = highlights.firstIndex(where: { $0.id == id }), highlights[at].pencil != pencil else { return } change(ReaderReport(id: id, pencil: pencil.rawValue)) } /// A drawn highlight removed: its line goes, its row is deleted. func remove(_ id: String) { closeFan() Task { do { _ = try await core.callJSON(ReaderCalls.highlight, ["id": RecordValue.text(id), "remove": .bool(true)]) highlights.removeAll { $0.id == id } draw() } catch { Log.write("reader: the highlight was not removed: \(String(describing: error))") } } } func startNoting(_ id: String) { closeFan() let words = highlights.first(where: { $0.id == id })?.note ?? "" notingHighlight = id // The reader's own note (`reader.highlight`), in the shell's writer. noting = DeckWriting(editor: .line, words: words, title: nil, hint: fan.noteHint, keepsWords: false, writes: .object(["kind": "reader_note"])) } /// The note's words committed. func note(_ text: String) { defer { stopNoting() } guard let id = notingHighlight, let words = noting?.words, text.trimmingCharacters(in: .whitespacesAndNewlines) != words.trimmingCharacters(in: .whitespacesAndNewlines) else { return } change(ReaderReport(id: id, note: text)) } func stopNoting() { noting = nil notingHighlight = nil } /// A highlight changed by the core, drawn as it answers. private func change(_ report: ReaderReport) { Task { do { let changed = try await core.call(ReaderCalls.highlight, report, as: BookHighlight.self) if let at = highlights.firstIndex(where: { $0.id == changed.id }) { highlights[at] = changed } draw() } catch { Log.write("reader: the highlight was not changed: \(String(describing: error))") } } } // MARK: The fan /// The hub's close, or a tap on the page while a tier stands: every tier /// goes, and a selection the pencils stood for with it. func closeFan() { while tiers.pop() != nil {} if selection != nil { selection = nil (navigator as? SelectableNavigator)?.clearSelection() } } } /// Readium's delegate, handing the reading what the navigator says. @MainActor final class BookNavigatorDelegate: NSObject, EPUBNavigatorDelegate, PDFNavigatorDelegate { weak var reading: BookReading? /// The place an EPUB opens at, gone to again once its page is laid out /// (`BookNavigators.land`). var landing: Locator? func navigator(_ navigator: ReadiumNavigator.Navigator, locationDidChange locator: Locator) { if let landing, let epub = navigator as? EPUBNavigatorViewController { self.landing = nil Task { await BookNavigators.land(epub, at: landing) } } reading?.moved(to: locator) } func navigator(_ navigator: ReadiumNavigator.Navigator, presentError error: NavigatorError) { Log.write("reader: the navigator said: \(String(describing: error))") } /// A selection in the book: the pencils at the hub, and Readium's menu /// (Copy alone) beside them. A PDF's selection keeps its menu only. func navigator(_ navigator: SelectableNavigator, shouldShowMenuForSelection selection: Selection) -> Bool { if navigator is EPUBNavigatorViewController { reading?.selected(selection) } return true } } /// The navigator as a SwiftUI page. private struct BookPages: UIViewControllerRepresentable { let reading: BookReading func makeUIViewController(context: Context) -> UIViewController { reading.navigator } func updateUIViewController(_ controller: UIViewController, context: Context) {} } // MARK: - Readium /// A book its seller locked: a DRM Readium knows but cannot open here (LCP, /// Adobe), a PDF behind a password, or an EPUB whose container names its /// text encrypted under a scheme nothing here decrypts. Found by opening it; /// nothing is checked when the file comes in, and the book stays on the shelf. struct BookLocked: Error { /// The font obfuscations an EPUB may name and Readium undoes itself. static let obfuscations: Set = ["http://www.idpf.org/2008/embedding", "http://ns.adobe.com/pdf/enc#RC"] static func holds(_ publication: Publication) -> Bool { publication.isRestricted || publication.readingOrder.contains { link in link.properties.encryption.map { !obfuscations.contains($0.algorithm) } ?? false } } } /// Opening a file as a publication, and the navigator that shows it. @MainActor enum BookNavigators { /// The room the chrome stands in over the page's top and foot, inside /// the safe area, kept whether it shows or not, so showing it never /// moves a line. One room in both size classes: the chrome is the same. static let room = (top: 52.0, bottom: 84.0 + Double(ReaderSeekKnobs.touch)) /// The media store names a file by its digest, so the format is said, /// not sniffed from an extension. static func publication(at url: URL, format: BookFormat) async throws -> Publication { guard let file = FileURL(url: url) else { throw CocoaError(.fileReadInvalidFileName) } let mediaType: MediaType = format == .epub ? .epub : .pdf // Made per opening: Readium's openers are not Sendable, and they are // cheap beside the book they open. let http = DefaultHTTPClient() let assets = AssetRetriever(httpClient: http) let opener = PublicationOpener( parser: DefaultPublicationParser(httpClient: http, assetRetriever: assets, pdfFactory: DefaultPDFDocumentFactory()) ) let asset = try await assets.retrieve(url: file, mediaType: mediaType).get() let publication = try await opener.open(asset: asset, allowUserInteraction: false).get() if BookLocked.holds(publication) || (format == .pdf && PDFDocument(url: url)?.isLocked == true) { throw BookLocked() } return publication } /// A place Readium reaches too early to land on: one past a chapter's /// start, in an EPUB. static func landsLate(_ place: Locator) -> Locator? { place.mediaType.isHTML && ((place.locations.progression ?? 0) > 0 || place.text.highlight != nil || !place.locations.fragments.isEmpty) ? place : nil } /// Readium goes to the opening place 0.2 s after a chapter loads, before /// the reader's own font has laid the page out (its TODO in /// `EPUBReflowableSpreadView.spreadDidLoad`), so a place deep in a chapter /// lands on its first pages. Once the page and its fonts are in, it goes /// there again. The first place Readium reports can come before its own /// early go (verify-main 17317: [0.51, 0.0] on a busy Mac), so a landing /// that ends away from the place goes there again, at most three times. static func land(_ epub: EPUBNavigatorViewController, at place: Locator) async { for _ in 0..<3 { for _ in 0..<50 { if case .success(let ready as Bool) = await epub.evaluateJavaScript( "document.readyState === 'complete' && document.fonts.status === 'loaded'"), ready { break } try? await Task.sleep(for: .milliseconds(100)) } _ = await epub.go(to: place) try? await Task.sleep(for: .milliseconds(600)) guard let want = place.locations.progression, let at = epub.currentLocation?.locations.progression else { return } if abs(at - want) < 0.05 { return } } } static func navigator(for publication: Publication, format: BookFormat, at start: Locator?, settings: ReaderSettings, face: ReaderFace) throws -> VisualNavigator & UIViewController { switch format { case .epub: var config = ReaderLook.epubConfiguration(settings, face: face) config.contentInset = [.compact: (top: room.top, bottom: room.bottom), .regular: (top: room.top, bottom: room.bottom)] return try EPUBNavigatorViewController(publication: publication, initialLocation: start, config: config) case .pdf: return try PDFNavigatorViewController(publication: publication, initialLocation: start, config: .init(preferences: ReaderLook.pdf(settings, face: face))) } } } #endif