Cotton code
131 lines · 4.7 KB · SwiftRaw
import CottonKitimport ImageIOimport PDFKitimport SwiftUI/// What a file column's file IS, for its inline drawing. Opened, it is the/// viewer's (`MediaViewer`), which reads it whole.enum FilePreview {  /// What this file IS, decided by asking the two drawers rather than by  /// trusting an extension: a receipt photographed as `IMG_0042` and a PDF  /// saved with no suffix both open, and a `.docx` is refused by both, which  /// is the answer the screen needs.  enum Kind {    case pdf(PDFDocument)    case image(UIImage)    init?(path: String) {      let url = URL(fileURLWithPath: path)      if let document = PDFDocument(url: url) {        self = .pdf(document)        return      }      if let image = FilePreview.bounded(url) {        self = .image(image)        return      }      return nil    }  }  /// A scan, decoded to a size a PHONE can hold.  ///  /// `UIImage(contentsOfFile:)` decodes the file at its own size, and the  /// files here are scans: a page off a flatbed is routinely 8000×11000, which  /// is 350 MB of ARGB before anything is drawn — a jetsam kill with no  /// exception and no Bugsink event, the same shape as the 464 MB snapshot  /// (Cotton note "First launch on a new phone — the whole database, downloaded"). ImageIO reads the header,  /// decodes ONCE at a bounded size and never materialises the full raster.  ///  /// `maxPixels` is the long edge, at 3× the tallest phone this app runs on,  /// so the viewer still has more pixels than the screen can show at full  /// zoom. `ThumbnailFromImageAlways` is what makes it decode the image  /// rather than hand back an embedded thumbnail some cameras write at  /// 160×120.  // `nonisolated` for the same reason `bounded` is: a number is not UIKit's.  nonisolated private static let maxPixels = 4096  /// `nonisolated`, because nothing here is UIKit's: it is a file read and a  /// Core Graphics decode. It sits inside a `UIViewRepresentable`, which is  /// `@MainActor`, and a nested type does not inherit that — so `Kind.init`  /// called it across an isolation boundary it never needed.  nonisolated static func bounded(_ url: URL) -> UIImage? {    guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil }    let options: [CFString: Any] = [      kCGImageSourceCreateThumbnailFromImageAlways: true,      kCGImageSourceCreateThumbnailWithTransform: true,      kCGImageSourceShouldCacheImmediately: true,      kCGImageSourceThumbnailMaxPixelSize: maxPixels,    ]    guard let cg = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else {      return nil    }    return UIImage(cgImage: cg)  }}/// A document's first page on its sheet of paper: the cover a tap opens in/// the viewer, where every page is read.struct FilePagesSheet: View {  @Environment(\.theme) private var theme  let pdf: PDFDocument  let seed: String  var body: some View {    if let page = pdf.page(at: 0) {      Paper(dye: .cream, edge: .cut, seed: "\(seed)-0", tilt: false, inset: FilePreviewKnobs.faceFilePagesInset) {        FilePageImage(page: page)      }    }  }}/// One page, rendered once at the width it is drawn at.struct FilePageImage: View {  @Environment(\.theme) private var theme  let page: PDFPage  @State private var image: UIImage?  /// The page's proportion as it is SHOWN — a page saved rotated a quarter  /// turn is as wide as it is tall the other way round.  private var aspect: CGFloat {    let box = page.bounds(for: .mediaBox)    guard box.width > 0, box.height > 0 else { return FilePreviewKnobs.faceFilePageFallbackAspect }    let quarter = abs(page.rotation) % 180 == 90    return quarter ? box.height / box.width : box.width / box.height  }  var body: some View {    GeometryReader { geo in      ZStack {        if let image {          Image(uiImage: image)            .resizable()            .interpolation(.high)            .blendMode(.multiply)        }      }      .frame(width: geo.size.width, height: geo.size.height)      .task(id: Int(geo.size.width)) {        guard geo.size.width > 1, image == nil else { return }        // Three pixels per point: enough for small print to read on        // the sheet, and bounded — the full viewer is where to zoom.        let width = geo.size.width * 3        image = page.thumbnail(          of: CGSize(width: width, height: width / aspect), for: .mediaBox)      }    }    .aspectRatio(aspect, contentMode: .fit)    .accessibilityHidden(true)  }}/// The sizes, counts and timings FilePreview draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum FilePreviewKnobs {    static let faceFilePageFallbackAspect: CGFloat = 0.707    static let faceFilePagesInset: CGFloat = 6}