Cotton code
115 lines · 5.0 KB · SwiftRaw
// What a shared PDF says about itself, read FROM THE FILE on this phone.//// Cotton Books takes an EPUB or a PDF through the share sheet; the drain's// book branch (`ShareIntake.swift`) files it as a `book` row. An EPUB is read// by the core (`cotton_core::media::book_file::read_epub`, run by// `capture.media` for an EPUB sent with its format alone), as Android sends// it. A PDF is read here, as Android's PdfRenderer reads it there: the// document's own title and author attributes (the file's name when it has no// title), its page count, and page 1 drawn as the cover — PDFKit draws it, and// the core has no PDF renderer. Read off the main thread.import CoreGraphicsimport Foundationimport ImageIOimport PDFKitimport UniformTypeIdentifiers/// What a PDF says about itself.public struct BookFacts: Sendable, Equatable {    public var format: BookFormat    public var title: String    public var author: String?    public var language: String?    public var isbn: String?    /// The page count.    public var pages: Int?    /// The first page drawn as JPEG; nil when it draws nothing.    public var cover: Data?    /// The cover's file extension (`jpg`), beside its bytes.    public var coverExtension: String?    public init(format: BookFormat, title: String, author: String? = nil, language: String? = nil, isbn: String? = nil,                pages: Int? = nil, cover: Data? = nil, coverExtension: String? = nil) {        self.format = format        self.title = title        self.author = author        self.language = language        self.isbn = isbn        self.pages = pages        self.cover = cover        self.coverExtension = coverExtension    }}/// Why a PDF could not be read. Said, never swallowed: a book the drain/// cannot read is a share it reports.public enum BookFileTrouble: Error, Equatable, Sendable {    /// A PDF that does not open.    case notAPDF}public enum BookFile {    /// What the PDF at `url` says about itself. Blocking work: call it off    /// the main actor.    public static func read(_ url: URL, fileName: String?) throws -> BookFacts {        try pdf(url, fileName: fileName)    }    /// The name a book with no title of its own is shown under: its file's    /// name without the extension, else the shell's word for an untitled book.    static func titleFromFileName(_ name: String?) -> String {        let base = (name ?? "").split(whereSeparator: { $0 == "/" || $0 == "\\" }).last.map(String.init) ?? ""        let stem = (base as NSString).deletingPathExtension.trimmingCharacters(in: .whitespacesAndNewlines)        return stem.isEmpty ? ShellLines.line("boot", "books.untitled") : stem    }    // MARK: PDF    /// The longest side, in pixels, a PDF's first page is drawn at as its cover.    static let coverSide: CGFloat = 900    static func pdf(_ url: URL, fileName: String?) throws -> BookFacts {        guard let document = PDFDocument(url: url) else { throw BookFileTrouble.notAPDF }        let attributes = document.documentAttributes ?? [:]        let said = { (key: PDFDocumentAttribute) -> String? in            (attributes[key] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty        }        var facts = BookFacts(            format: .pdf,            title: said(.titleAttribute) ?? titleFromFileName(fileName ?? url.lastPathComponent),            author: said(.authorAttribute),            pages: document.pageCount > 0 ? document.pageCount : nil)        if let page = document.page(at: 0), let jpeg = drawn(page) {            facts.cover = jpeg            facts.coverExtension = "jpg"        }        return facts    }    /// `page` drawn white-backed at ``coverSide`` on its longest side, as JPEG.    static func drawn(_ page: PDFPage) -> Data? {        let box = page.bounds(for: .mediaBox)        guard box.width > 0, box.height > 0 else { return nil }        let scale = coverSide / max(box.width, box.height)        let width = Int((box.width * scale).rounded()), height = Int((box.height * scale).rounded())        guard let context = CGContext(            data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,            space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)        else { return nil }        context.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: 1))        context.fill(CGRect(x: 0, y: 0, width: width, height: height))        context.scaleBy(x: scale, y: scale)        context.translateBy(x: -box.minX, y: -box.minY)        page.draw(with: .mediaBox, to: context)        guard let image = context.makeImage() else { return nil }        let out = NSMutableData()        guard let destination = CGImageDestinationCreateWithData(out, UTType.jpeg.identifier as CFString, 1, nil) else { return nil }        CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: 0.85] as CFDictionary)        return CGImageDestinationFinalize(destination) ? out as Data : nil    }}extension String {    fileprivate var nonEmpty: String? { isEmpty ? nil : self }}