// 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.importCoreGraphicsimportFoundationimportImageIOimport PDFKitimportUniformTypeIdentifiers/// What a PDF says about itself.publicstructBookFacts: Sendable, Equatable {publicvar format: BookFormatpublicvar title: Stringpublicvar author: String?publicvar language: String?publicvar isbn: String?/// The page count.publicvar pages: Int?/// The first page drawn as JPEG; nil when it draws nothing.publicvar cover: Data?/// The cover's file extension (`jpg`), beside its bytes.publicvar coverExtension: String?publicinit(format: BookFormat, title: String, author: String? = nil, language: String? = nil, isbn: String? = nil, pages: Int? = nil, cover: Data? = nil, coverExtension: String? = nil) {self.format = formatself.title = titleself.author = authorself.language = languageself.isbn = isbnself.pages = pagesself.cover = coverself.coverExtension = coverExtension }}/// Why a PDF could not be read. Said, never swallowed: a book the drain/// cannot read is a share it reports.publicenumBookFileTrouble: Error, Equatable, Sendable {/// A PDF that does not open.case notAPDF}publicenumBookFile {/// What the PDF at `url` says about itself. Blocking work: call it off/// the main actor.publicstaticfunc 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.staticfunc 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.staticlet coverSide: CGFloat = 900staticfunc pdf(_ url: URL, fileName: String?) throws -> BookFacts {guardlet document = PDFDocument(url: url) else { throwBookFileTrouble.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)iflet 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.staticfunc drawn(_ page: PDFPage) -> Data? {let box = page.bounds(for: .mediaBox)guard box.width > 0, box.height > 0else { returnnil }let scale = coverSide / max(box.width, box.height)let width = Int((box.width * scale).rounded()), height = Int((box.height * scale).rounded())guardlet context = CGContext( data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)else { returnnil } 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)guardlet image = context.makeImage() else { returnnil }let out = NSMutableData()guardlet destination = CGImageDestinationCreateWithData(out, UTType.jpeg.identifier as CFString, 1, nil) else { returnnil } CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: 0.85] as CFDictionary)return CGImageDestinationFinalize(destination) ? out asData : nil }}extensionString {fileprivatevar nonEmpty: String? { isEmpty ? nil : self }}