// 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)importCottonKitimportCottonMailboximportCottonPaperimportCottonValuesimport PDFKitimportReadiumNavigatorimportReadiumSharedimportReadiumStreamerimport osimportSwiftUIimport UIKit// MARK: - The screen/// One book, from the core's answer to its first page.structBookReaderScreen: View {let opening: ReaderOpeninglet close: () -> Void @Environment(\.cottonCore) privatevar core @Environment(\.readerPresenter) privatevar presenter @Environment(\.recordsRevision) privatevar revision @State privatevar reading: BookReading?/// The line said in place of the book when it does not open. @State privatevar refusal: String?var body: someView { ZStack { (reading?.face ?? .paper).ground.ignoresSafeArea()iflet 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) }iflet writing = reading.noting {DeckLineInput(writing: writing, commit: { reading.note($0) }, dismiss: { reading.stopNoting() }) } } elseiflet 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 { awaitopen() } .onChange(of: revision) { _, _ inTask { await reading?.readSettings() } } .onChange(of: presenter?.jump) { _, jump inguardlet jump, jump.id == opening.id, let at = jump.at else { return } presenter?.jump = nilTask { await reading?.go(to: at) } } }privatefuncopen() async {guard reading == nil, let core else { return }do { reading = tryawaitBookReading.open(opening, core: core) } catchlet refused asReaderRefused { refusal = refused.line } catch {Log.write("reader: \(opening.id) did not open: \(String(describing: error))") refusal = ShellLines.line("cards", "book.could_not_open") } }privatefunc done() { reading?.closing() close() }}/// The book does not open, and the core's line says why.structReaderRefused: 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 @ObservablefinalclassBookReading {privatestaticlet 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.privatestaticlet lightEvery: TimeInterval = 15let book: Stringlet title: Stringlet 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 privatevar lightClock: Timer?/// The core asked to be told again (`again_ms`): a place waits to be written. @ObservationIgnored privatevar dueClock: Timer? @ObservationIgnored privatevar watchers: [NSObjectProtocol] = [] @ObservationIgnored privatelet delegate = BookNavigatorDelegate() @ObservationIgnored privatevar turns: DirectionalNavigationAdapter? @ObservationIgnored privatevar dimming: ReaderDimming?/// The book's contents, until a report has carried them to the core. @ObservationIgnored privatevar unsentContents: ReaderReport.Contents?/// The reports in the order made: each goes once the one before is answered. @ObservationIgnored privatevar reporting: Task<Void, Never>?/// When the open was asked, until the first page says where it is. @ObservationIgnored privatevar 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: ReaderSettingsprivate(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: Boolprivate(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 privatevar 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<Void, Never>? @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.staticfuncopen(_ opening: ReaderOpening, core: any CottonCalling) asyncthrows -> BookReading {let began = ContinuousClock.nowlet phoneDark = UIScreen.main.traitCollection.userInterfaceStyle == .darklet answer = tryawait core.call(ReaderCalls.reader, ReaderReport(book: opening.id, at: opening.at, dark: phoneDark), as: ReaderAnswer.self)iflet refusal = answer.refusal { throwReaderRefused(line: refusal) }guardlet file = answer.file, let format = answer.bookFormat, let settings = answer.settings, let fan = answer.fan,let refusals = answer.refusals else { throwCocoaError(.fileReadCorruptFile) }let url = tryawaitBookKeeper.shared.file(for: file)let publication: Publicationdo { publication = tryawaitBookNavigators.publication(at: url, format: format) } catchisBookLocked {throwReaderRefused(line: refusals.locked) } catch {Log.write("reader: \(opening.id) did not open: \(String(describing: error))")throwReaderRefused(line: refusals.unopened) }let start = try answer.at.map { tryLocator(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 = tryBookNavigators.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 = beganawait reading.readContents() reading.draw()return reading }privateinit(answer: ReaderAnswer, title: String, format: BookFormat, publication: Publication, navigator: VisualNavigator & UIViewController, core: any CottonCalling, settings: ReaderSettings, fan: ReaderFanAnswer, phoneDark: Bool) { book = answer.bookself.title = titleself.format = formatself.publication = publicationself.navigator = navigatorself.core = coreself.settings = settingsself.fan = fanself.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 = selfiflet epub = navigator as? EPUBNavigatorViewController { epub.delegate = delegate epub.observeDecorationInteractions(inGroup: Self.decorations) { [weakself] event inself?.openHighlight(event.decoration.id) } }iflet 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 { [weakself] _ inguardletselfelse { returnfalse }ifself.tiers.closes { self.closeFan() } else {self.chromeShown.toggle()ifself.chromeShown { self.readSeek() } }returntrue }) dim() watch() }// MARK: Where the reader isprivatevar appActive: Bool { UIApplication.shared.applicationState == .active }/// The navigator moved: the place, and a PDF page's printed label, go to the core.fileprivatefunc moved(to locator: Locator) {iflet began {// The first page's latency, for a walk or a report to read.let elapsed = ContinuousClock.now - beganLog.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()guardlet 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 = reportiflet contents = unsentContents { report.contents = contents unsentContents = nil }let previous = reportinglet core = core reporting = Task { [weakself] inawait previous?.valuedo {let answer = tryawait core.call(ReaderCalls.moved, report, as: ReaderMovedAnswer.self)self?.heard(answer) } catch {Log.write("reader: the place was not reported: \(String(describing: error))") } } }privatefunc heard(_ answer: ReaderMovedAnswer) {iflet 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 = nilguardlet ms = answer.againMs else { return } dueClock = Timer.scheduledTimer(withTimeInterval: Double(ms) / 1000, repeats: false) { [weakself] _ inMainActor.assumeIsolated {guardletselfelse { 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.privatefunc readContents() async {// Readium's contents service is read off the main actor; the// publication is only read there, never changed. nonisolated(unsafe) let publication = publicationguardlet 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 = [] }privatefunc 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) { [weakself] _ inMainActor.assumeIsolated { self?.readPhoneLight() } }let center = NotificationCenter.default watchers.append(center.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { [weakself] _ inMainActor.assumeIsolated {guardletselfelse { return }self.send(ReaderReport(book: self.book, active: false)) } }) watchers.append(center.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weakself] _ inMainActor.assumeIsolated {guardletselfelse { 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.privatefunc readPhoneLight() {let dark = UIScreen.main.traitCollection.userInterfaceStyle == .darkguard dark != phoneDark else { return } phoneDark = darkTask { await readSettings() } }/// `reader.open { at }` on a book already open: the navigator goes there.func go(to at: String) async {guardlet 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 = tryawait core.call(ReaderCalls.reader, ReaderReport(book: book, dark: phoneDark), as: ReaderAnswer.self)guardlet 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)) }privatefunc choose(_ report: ReaderReport) async {do {let answer = tryawait 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.privatefunc wearing(_ settings: ReaderSettings, _ fan: ReaderFanAnswer) {let changed = settings != self.settingsself.fan = fanguard changed else { return }self.settings = settings apply() refreshTier() }/// The page in the face and knobs as they stand.privatefunc apply() {let face = self.faceiflet epub = navigator as? EPUBNavigatorViewController { epub.submitPreferences(ReaderLook.epub(settings, face: face)) } elseiflet 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.privatefunc 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.viewif 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 }iflet dimming { host.bringSubviewToFront(dimming) } } else { dimming?.removeFromSuperview() dimming = nil } }// MARK: Highlightsstaticlet decorations: DecorationGroup = "highlights"/// The page's pencil lines, as the highlights stand.fileprivatefunc draw() {guardlet epub = navigator as? EPUBNavigatorViewController else { return }let decorations = highlights.compactMap { highlight -> Decoration? inlet place: Locator?do { place = tryLocator(jsonString: highlight.at) } catch {Log.write("reader: highlight \(highlight.id) has no place to draw at: \(String(describing: error))")returnnil }guardlet place else { Log.write("reader: highlight \(highlight.id) has no place to draw at"); returnnil }returnDecoration(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.fileprivatefunc selected(_ selection: Selection) {guardlet 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) {guardlet 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 = tryawait 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) {guardlet 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 { _ = tryawait 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() }guardlet 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.privatefunc change(_ report: ReaderReport) {Task {do {let changed = tryawait core.call(ReaderCalls.highlight, report, as: BookHighlight.self)iflet 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.@MainActorfinalclassBookNavigatorDelegate: NSObject, EPUBNavigatorDelegate, PDFNavigatorDelegate {weakvar 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) {iflet landing, let epub = navigator as? EPUBNavigatorViewController {self.landing = nilTask { awaitBookNavigators.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) }returntrue }}/// The navigator as a SwiftUI page.privatestructBookPages: UIViewControllerRepresentable {let reading: BookReadingfunc 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.structBookLocked: Error {/// The font obfuscations an EPUB may name and Readium undoes itself.staticlet obfuscations: Set<String> = ["http://www.idpf.org/2008/embedding", "http://ns.adobe.com/pdf/enc#RC"]staticfunc 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.@MainActorenumBookNavigators {/// 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.staticlet 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.staticfunc publication(at url: URL, format: BookFormat) asyncthrows -> Publication {guardlet file = FileURL(url: url) else { throwCocoaError(.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 = tryawait assets.retrieve(url: file, mediaType: mediaType).get()let publication = tryawait opener.open(asset: asset, allowUserInteraction: false).get()ifBookLocked.holds(publication) || (format == .pdf && PDFDocument(url: url)?.isLocked == true) { throwBookLocked() }return publication }/// A place Readium reaches too early to land on: one past a chapter's/// start, in an EPUB.staticfunc 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.staticfunc land(_ epub: EPUBNavigatorViewController, at place: Locator) async {for _ in0..<3 {for _ in0..<50 {ifcase .success(let ready asBool) = await epub.evaluateJavaScript("document.readyState === 'complete' && document.fonts.status === 'loaded'"), ready { break }try? awaitTask.sleep(for: .milliseconds(100)) } _ = await epub.go(to: place)try? awaitTask.sleep(for: .milliseconds(600))guardlet want = place.locations.progression,let at = epub.currentLocation?.locations.progression else { return }if abs(at - want) < 0.05 { return } } }staticfunc 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)]returntry EPUBNavigatorViewController(publication: publication, initialLocation: start, config: config)case .pdf:returntry PDFNavigatorViewController(publication: publication, initialLocation: start, config: .init(preferences: ReaderLook.pdf(settings, face: face))) } }}#endif