Cotton code
440 lines · 16.4 KB · SwiftRaw
// A document in the viewer. A PDF reads through PDFKit — pages edge to edge,// a strip of its pages under them, search with every match lit, a jump to a// page, text that selects — and any other kind (Office, text, a picture kept// as a document) through Quick Look's own view, inside the viewer's chrome.// "Open in…" is the acts menu's Share.import CottonKitimport PDFKitimport QuickLookimport SwiftUI#if canImport(UIKit)import UIKit#elseimport AppKitimport QuickLookUI#endif@MainActor @Observablefinal class ViewerPDFModel {    let document: PDFDocument    private(set) var page = 0    var query = ""    private(set) var matches: [PDFSelection] = []    private(set) var match = 0    private(set) var searched = false    @ObservationIgnored weak var view: PDFView?    init(document: PDFDocument) { self.document = document }    var pageCount: Int { document.pageCount }    /// Opens the file off the main actor: PDFKit reads the cross-reference    /// table and the first page, never the whole file.    static func open(_ url: URL) async -> PDFDocument? {        let opened = await Task.detached(priority: .userInitiated) { OpenedPDF(document: PDFDocument(url: url)) }.value        return opened.document    }    func pageChanged() {        guard let view, let current = view.currentPage else { return }        page = document.index(for: current)    }    func go(to index: Int) {        guard let target = document.page(at: min(max(0, index), max(0, pageCount - 1))) else { return }        reveal(target, top: target.bounds(for: .mediaBox).maxY)        page = document.index(for: target)    }    func search() {        let words = query.trimmingCharacters(in: .whitespacesAndNewlines)        searched = !words.isEmpty        matches = words.isEmpty ? [] : document.findString(words, withOptions: [.caseInsensitive, .diacriticInsensitive])        match = 0        view?.highlightedSelections = matches.isEmpty ? nil : matches        show()    }    func step(_ by: Int) {        guard !matches.isEmpty else { return }        match = (match + by + matches.count) % matches.count        show()    }    func clear() {        query = ""        matches = []        searched = false        view?.highlightedSelections = nil        view?.clearSelection()    }    private func show() {        guard matches.indices.contains(match) else { return }        let selection = matches[match]        view?.setCurrentSelection(selection, animate: true)        if let target = selection.pages.first {            reveal(target, top: selection.bounds(for: target).maxY + ViewerKnobs.matchLead)        }        pageChanged()    }    /// Scrolls so `top` (in the page's own space) is the top of the view,    /// which starts below the viewer's head.    private func reveal(_ target: PDFPage, top: CGFloat) {        view?.go(to: PDFDestination(page: target, at: CGPoint(x: 0, y: top)))    }}/// A document opened off the main actor and handed back once: nothing else/// holds it between the two.private struct OpenedPDF: @unchecked Sendable {    let document: PDFDocument?}struct ViewerDocumentPage: View {    let item: ViewerItem    let current: Bool    let words: ViewerWords?    let onTap: () -> Void    let onFile: (URL) -> Void    var onPageGround: (ThemeColor?) -> Void = { _ in }    @Environment(\.cottonCore) private var core    @Environment(\.theme) private var theme    @Environment(\.viewerChromeShown) private var chromeShown    @Environment(\.viewerHeadHeight) private var headHeight    @Environment(\.viewerFootHeight) private var footHeight    @Environment(\.dismiss) private var dismiss    @State private var url: URL?    @State private var pdf: ViewerPDFModel?    /// A web page small enough to run, opened in the sealed web view.    @State private var page: URL?    /// A web page too big to run: a file, shared from the acts menu.    @State private var oversized = false    @State private var refusal: String?    @State private var fetching = false    @State private var jumping = false    @State private var jumpTo = ""    @FocusState private var searching: Bool    @FocusState private var jumpField: Bool    var body: some View {        ZStack {            if let pdf {                VStack(spacing: 0) {                    ViewerPDFView(model: pdf, ground: theme.colors.groundMuted, onTap: onTap, onPullDown: { dismiss() })                        .accessibilityIdentifier("viewer-document")                    if chromeShown { tools(pdf) }                }                .padding(.top, headHeight)            } else if let page {                ViewerWebPage(file: page, ground: theme.colors.groundMuted, onGround: onPageGround)                    .accessibilityIdentifier("viewer-document")                    .padding(.top, headHeight)            } else if oversized {                // Never handed to Quick Look, which would run it unsealed.                AbsentSlip(kind: .document, name: item.title, words: nil)                    .padding(ViewerKnobs.chromeInset)            } else if let url {                ViewerQuickLook(url: url)                    .accessibilityIdentifier("viewer-document")                    .padding(.top, headHeight)            } else if refusal != nil || fetching {                // While it is fetched the slip says so (its Fetch reads                // "Fetching…"): never a blank page with no word for 20 s                // (290 walk, Documents).                AbsentSlip(                    kind: .document, name: item.title, words: words,                    fetching: fetching, onFetch: { Task { await open() } })                    .padding(ViewerKnobs.chromeInset)            }        }        .task(id: current) { if current, url == nil { await open() } }    }    /// The page strip, the page it is on (a tap jumps), and the search.    private func tools(_ pdf: ViewerPDFModel) -> some View {        VStack(spacing: ViewerKnobs.chromeVertical) {            ViewerPageStrip(model: pdf, ground: theme.colors.groundElevated)                .frame(height: ViewerKnobs.stripHeight)                .accessibilityIdentifier("viewer-page-strip")            HStack(spacing: ViewerKnobs.chromeGap) {                Image(systemName: "magnifyingglass")                    .foregroundStyle(theme.colors.ink.opacity(ViewerKnobs.quiet))                TextField(words?.search ?? "", text: Binding(get: { pdf.query }, set: { pdf.query = $0 }))                    .focused($searching)                    .submitLabel(.search)                    .onSubmit { pdf.search() }                    .foregroundStyle(theme.colors.ink.color)                    .accessibilityIdentifier("viewer-search")                if pdf.searched {                    if pdf.matches.isEmpty {                        Text(words?.noMatch ?? "").foregroundStyle(theme.colors.ink.opacity(ViewerKnobs.quiet))                    } else {                        Text(ViewerWords.fill(words?.position ?? "", pdf.match + 1, pdf.matches.count))                            .accessibilityIdentifier("viewer-search-position")                        ViewerButton(symbol: "chevron.up", label: "", identifier: "viewer-search-previous") { pdf.step(-1) }                        ViewerButton(symbol: "chevron.down", label: "", identifier: "viewer-search-next") { pdf.step(1) }                    }                    ViewerButton(symbol: "xmark.circle.fill", label: words?.cancel ?? "", identifier: "viewer-search-clear") {                        pdf.clear()                        searching = false                    }                } else if jumping {                    TextField(words?.goToPage ?? "", text: $jumpTo)                        #if os(iOS)                        .keyboardType(.numberPad)                        #endif                        .focused($jumpField)                        .onSubmit(jump)                        .frame(maxWidth: ViewerKnobs.jumpWidth)                        .accessibilityIdentifier("viewer-page-jump")                    Button(words?.go ?? "", action: jump)                        .buttonStyle(.plain)                        .accessibilityIdentifier("viewer-page-go")                } else {                    Button(words?.page(pdf.page, of: pdf.pageCount) ?? "") {                        jumping = true                        jumpField = true                    }                    .buttonStyle(.plain)                    .accessibilityHint(words?.goToPage ?? "")                    .accessibilityIdentifier("viewer-page")                }            }            .font(theme.type.interface(ViewerKnobs.positionSize).monospacedDigit())            .foregroundStyle(theme.colors.ink.color)            .padding(.horizontal, ViewerKnobs.chromeInset)        }        .padding(.vertical, ViewerKnobs.chromeVertical)        .padding(.bottom, footHeight)        .background(theme.colors.groundElevated.color.ignoresSafeArea(edges: .bottom))    }    /// Goes to the page typed, one-based as the page line says it.    private func jump() {        if let pdf, let number = Int(jumpTo.trimmingCharacters(in: .whitespaces)) { pdf.go(to: number - 1) }        jumpTo = ""        jumping = false        jumpField = false    }    /// The file — fetched if it is not here, because opening it is the asking.    private func open() async {        guard let key = item.key, let core else {            refusal = words?.absent            return        }        guard !fetching else { return }        fetching = true        defer { fetching = false }        do {            guard let file = try await CoreAttachmentStore(core: core).ensure(for: key) else {                refusal = words?.absent                return            }            onFile(file)            refusal = nil            if ViewerSeal.isPage(contentType: item.contentType, name: item.title) {                if let size = ViewerSeal.size(of: file), size <= ViewerSeal.ceilingBytes {                    page = file                } else {                    oversized = true                }                return            }            if let document = await ViewerPDFModel.open(file) {                pdf = ViewerPDFModel(document: document)            }            url = file        } catch {            refusal = (error as? CottonCallError)?.message ?? words?.absent        }    }}// MARK: - PDFKit#if canImport(UIKit)/// PDFKit's view, laid below the viewer's head like every paper page's/// content, never scrolling under it.final class ViewerPDFCanvas: PDFView {    /// A pull down past the first page's top: the viewer closes, as a swipe    /// down closes a picture. PDFKit's scroll view takes every vertical drag,    /// so the zoom transition's own dismissal never sees one.    var pulledDown: (() -> Void)?    private weak var watched: UIScrollView?    override func layoutSubviews() {        super.layoutSubviews()        guard let scroll = subviews.compactMap({ $0 as? UIScrollView }).first, watched !== scroll else { return }        watched = scroll        scroll.contentInsetAdjustmentBehavior = .never        scroll.panGestureRecognizer.addTarget(self, action: #selector(panned(_:)))    }    @objc private func panned(_ pan: UIPanGestureRecognizer) {        guard pan.state == .ended, let scroll = watched else { return }        if scroll.contentOffset.y < -(scroll.adjustedContentInset.top + ViewerKnobs.pullToClose) { pulledDown?() }    }}#endifstruct ViewerPDFView: PlatformViewRepresentable {    let model: ViewerPDFModel    let ground: ThemeColor    let onTap: () -> Void    var onPullDown: () -> Void = {}    func makeCoordinator() -> Coordinator { Coordinator(model: model, onTap: onTap) }    private func made(_ context: Context) -> PDFView {        #if canImport(UIKit)        let view = ViewerPDFCanvas()        #else        let view = PDFView()        #endif        view.displayMode = .singlePageContinuous        view.displayDirection = .vertical        view.autoScales = true        view.displaysPageBreaks = true        view.document = model.document        model.view = view        NotificationCenter.default.addObserver(            context.coordinator, selector: #selector(Coordinator.pageChanged), name: .PDFViewPageChanged, object: view)        return view    }    #if canImport(UIKit)    func makeUIView(context: Context) -> PDFView {        let view = made(context)        (view as? ViewerPDFCanvas)?.pulledDown = onPullDown        view.backgroundColor = ground.uiColor        view.pageShadowsEnabled = false        let tap = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.tapped))        tap.delegate = context.coordinator        view.addGestureRecognizer(tap)        return view    }    func updateUIView(_ view: PDFView, context: Context) {        context.coordinator.onTap = onTap    }    #else    func makeNSView(context: Context) -> PDFView {        let view = made(context)        view.backgroundColor = NSColor(ground.color)        return view    }    func updateNSView(_ view: PDFView, context: Context) {}    #endif    final class Coordinator: NSObject {        let model: ViewerPDFModel        var onTap: () -> Void        init(model: ViewerPDFModel, onTap: @escaping () -> Void) {            self.model = model            self.onTap = onTap        }        @MainActor @objc func pageChanged() { model.pageChanged() }        @objc func tapped() { onTap() }    }}#if canImport(UIKit)extension ViewerPDFView.Coordinator: UIGestureRecognizerDelegate {    /// PDFKit's own taps (a link, a selection, its double-tap zoom) still run.    func gestureRecognizer(_ g: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool { true }}#endif/// The document's pages in a strip: a tap or a drag goes to a page.struct ViewerPageStrip: PlatformViewRepresentable {    let model: ViewerPDFModel    let ground: ThemeColor    private func made() -> PDFThumbnailView {        let strip = PDFThumbnailView()        strip.pdfView = model.view        #if canImport(UIKit)        strip.layoutMode = .horizontal        #endif        strip.thumbnailSize = CGSize(width: ViewerKnobs.stripHeight * 0.7, height: ViewerKnobs.stripHeight - 8)        return strip    }    #if canImport(UIKit)    func makeUIView(context: Context) -> PDFThumbnailView {        let strip = made()        strip.backgroundColor = .clear        // The page view is made in the same pass: the strip is tied to it        // once both exist.        DispatchQueue.main.async { strip.pdfView = model.view }        return strip    }    func updateUIView(_ strip: PDFThumbnailView, context: Context) {        if strip.pdfView !== model.view { strip.pdfView = model.view }    }    #else    func makeNSView(context: Context) -> PDFThumbnailView { made() }    func updateNSView(_ strip: PDFThumbnailView, context: Context) {        if strip.pdfView !== model.view { strip.pdfView = model.view }    }    #endif}// MARK: - Quick Look#if canImport(UIKit)/// Any other kind of document: Quick Look's own view of it.struct ViewerQuickLook: UIViewControllerRepresentable {    let url: URL    func makeCoordinator() -> Coordinator { Coordinator(url: url) }    func makeUIViewController(context: Context) -> QLPreviewController {        let controller = QLPreviewController()        controller.dataSource = context.coordinator        return controller    }    func updateUIViewController(_ controller: QLPreviewController, context: Context) {        if context.coordinator.url != url {            context.coordinator.url = url            controller.reloadData()        }    }    final class Coordinator: NSObject, QLPreviewControllerDataSource {        var url: URL        init(url: URL) { self.url = url }        func numberOfPreviewItems(in controller: QLPreviewController) -> Int { 1 }        func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem { url as NSURL }    }}#elsestruct ViewerQuickLook: NSViewRepresentable {    let url: URL    func makeNSView(context: Context) -> QLPreviewView {        let view = QLPreviewView(frame: .zero, style: .normal) ?? QLPreviewView()        view.previewItem = url as NSURL        return view    }    func updateNSView(_ view: QLPreviewView, context: Context) {        if (view.previewItem as? NSURL) as URL? != url { view.previewItem = url as NSURL }    }}#endifextension ViewerKnobs {    static let jumpWidth: CGFloat = 96}