SPB Git

Repository Public

SlideDocument.swift 6.9 KB 135 lines swift

1// SP Lecture Studio — LecturePDF2// File: Packages/LecturePDF/Sources/SlideDocument.swift3// Description: PDF page loading, geometry (crop box + rotation), rasterization, thumbnails and text search.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import CoreGraphics9import PDFKit1011public enum SlideDocumentError: Error, Equatable { case unreadable, locked, empty }1213public struct SearchHit: Hashable, Sendable, Identifiable {14    public var page: Int15    public var snippet: String16    public var ordinal: Int17    public var id: String { "\(page)-\(ordinal)" }18}1920/// Read-only access to the PDF copy stored in a project. The file is never written.21public final class SlideDocument: @unchecked Sendable {22    public let url: URL23    public let pdf: PDFDocument24    private let cg: CGPDFDocument25    public let pageCount: Int26    private let lock = NSLock()2728    public init(url: URL) throws {29        guard let pdf = PDFDocument(url: url), let cg = CGPDFDocument(url as CFURL) else { throw SlideDocumentError.unreadable }30        if pdf.isLocked || !cg.isUnlocked { throw SlideDocumentError.locked }31        guard pdf.pageCount > 0 else { throw SlideDocumentError.empty }32        self.url = url; self.pdf = pdf; self.cg = cg; pageCount = pdf.pageCount33    }3435    /// Number of pages of a PDF without keeping it open (used at import time). Throws for locked or unreadable files.36    public static func pageCount(of url: URL) throws -> Int { try SlideDocument(url: url).pageCount }3738    /// Displayed size of a page in points (crop box, rotation applied).39    public func pageSize(_ index: Int) -> CGSize {40        guard let page = cg.page(at: index + 1) else { return CGSize(width: 1280, height: 720) }41        let box = page.getBoxRect(.cropBox)42        let rotated = ((page.rotationAngle % 180) + 180) % 180 != 043        let size = rotated ? CGSize(width: box.height, height: box.width) : box.size44        return size.width > 0 && size.height > 0 ? size : CGSize(width: 1280, height: 720)45    }4647    public func aspectRatio(_ index: Int) -> CGFloat { let s = pageSize(index); return s.width / s.height }4849    public func label(_ index: Int) -> String { pdf.page(at: index)?.label ?? String(index + 1) }5051    /// Draws a page into `rect` of a Core Graphics context whose origin is at the bottom-left (bitmap or PDF context).52    /// The page fills the rect exactly; the caller chooses a rect with the page aspect ratio.53    public func draw(page index: Int, in ctx: CGContext, rect: CGRect, background: CGColor? = CGColor(red: 1, green: 1, blue: 1, alpha: 1)) {54        lock.lock(); defer { lock.unlock() }55        guard let page = cg.page(at: index + 1) else { return }56        let box = page.getBoxRect(.cropBox)57        let rot = ((page.rotationAngle % 360) + 360) % 36058        let size = rot % 180 == 0 ? box.size : CGSize(width: box.height, height: box.width)59        guard size.width > 0, size.height > 0 else { return }60        ctx.saveGState()61        if let background { ctx.setFillColor(background); ctx.fill(rect) }62        ctx.clip(to: rect)63        ctx.translateBy(x: rect.minX, y: rect.minY)64        ctx.scaleBy(x: rect.width / size.width, y: rect.height / size.height)65        switch rot {                                   // /Rotate is clockwise66        case 90: ctx.translateBy(x: 0, y: size.height); ctx.rotate(by: -.pi / 2)67        case 180: ctx.translateBy(x: size.width, y: size.height); ctx.rotate(by: .pi)68        case 270: ctx.translateBy(x: size.width, y: 0); ctx.rotate(by: .pi / 2)69        default: break70        }71        ctx.translateBy(x: -box.minX, y: -box.minY)72        ctx.clip(to: box)73        ctx.interpolationQuality = .high74        ctx.drawPDFPage(page)75        ctx.restoreGState()76    }7778    /// Rasterizes a page to exactly `pixelSize` (sRGB, opaque white background).79    public func image(page index: Int, pixelSize: CGSize) -> CGImage? {80        guard let ctx = Bitmap.context(width: Int(pixelSize.width.rounded()), height: Int(pixelSize.height.rounded())) else { return nil }81        draw(page: index, in: ctx, rect: CGRect(origin: .zero, size: CGSize(width: ctx.width, height: ctx.height)))82        return ctx.makeImage()83    }8485    /// Thumbnail no larger than `maxDimension` pixels on its longest side.86    public func thumbnail(page index: Int, maxDimension: CGFloat) -> CGImage? {87        let s = pageSize(index)88        let scale = maxDimension / max(s.width, s.height)89        return image(page: index, pixelSize: CGSize(width: max(1, s.width * scale), height: max(1, s.height * scale)))90    }9192    public func text(page index: Int) -> String { pdf.page(at: index)?.string ?? "" }9394    /// Case and diacritic insensitive text search across the document.95    public func search(_ query: String, limit: Int = 200) -> [SearchHit] {96        let q = query.trimmingCharacters(in: .whitespacesAndNewlines)97        guard q.count >= 2 else { return [] }98        var hits: [SearchHit] = []99        for sel in pdf.findString(q, withOptions: [.caseInsensitive, .diacriticInsensitive]) {100            guard let page = sel.pages.first else { continue }101            let index = pdf.index(for: page)102            let ctxSel = sel.copy() as? PDFSelection103            ctxSel?.extend(atStart: 30); ctxSel?.extend(atEnd: 40)104            let snippet = (ctxSel?.string ?? sel.string ?? q).replacingOccurrences(of: "\n", with: " ").trimmingCharacters(in: .whitespaces)105            hits.append(SearchHit(page: index, snippet: snippet, ordinal: hits.count))106            if hits.count >= limit { break }107        }108        return hits109    }110111    /// Title for a chapter: first non-empty text line of the page, or nil when the page has no text layer.112    public func titleGuess(page index: Int) -> String? {113        let line = text(page: index).split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) }.first { $0.count >= 3 }114        return line.map { String($0.prefix(80)) }115    }116}117118public enum Bitmap {119    public static let sRGB = CGColorSpace(name: CGColorSpace.sRGB)!120    /// BGRA premultiplied bitmap context (same byte layout as `kCVPixelFormatType_32BGRA`).121    public static func context(width: Int, height: Int, data: UnsafeMutableRawPointer? = nil, bytesPerRow: Int = 0) -> CGContext? {122        guard width > 0, height > 0 else { return nil }123        return CGContext(data: data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: sRGB,124                         bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)125    }126}127128/// Largest rect with the given aspect ratio centred in `bounds` (letterbox / pillarbox fit).129public func aspectFit(aspect: CGFloat, in bounds: CGRect) -> CGRect {130    guard aspect > 0, bounds.width > 0, bounds.height > 0 else { return bounds }131    var w = bounds.width, h = w / aspect132    if h > bounds.height { h = bounds.height; w = h * aspect }133    return CGRect(x: bounds.midX - w / 2, y: bounds.midY - h / 2, width: w, height: h)134}135
Files main
Menu

Theme