SPB Git

Repository Public License

Support.swift 6.2 KB 117 lines swift

1// ORIX Scan2// File: Packages/ORIXKit/Tests/ORIXKitTests/Support.swift3// Description: Test helpers: synthetic page images drawn with Core Text, temporary stores, fixture PDFs.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import CoreGraphics8import CoreImage9import CoreText10import Foundation11import PDFKit12@testable import ORIXKit1314enum Fixture {15    static let english = """16    ORIX Scan quarterly report17    The quick brown fox jumps over the lazy dog near the river bank.18    Revenue increased by 18 percent compared with the previous quarter.19    Operating costs remained stable while customer satisfaction improved.20    Please review the attached figures before the meeting on Thursday.21    """2223    static let french = """24    Rapport trimestriel de la société25    Les résultats financiers dépassent les prévisions établies en février.26    La clientèle québécoise apprécie la qualité du service à Montréal.27    Nous prévoyons une croissance soutenue pour l'année prochaine.28    Veuillez vérifier les données avant la réunion de jeudi.29    """3031    /// Draws lines of text on a white page. Returns an upright image (first line at the top).32    static func page(_ text: String, width: Int = 1654, height: Int = 2339, fontSize: CGFloat = 40, fontName: String = "Helvetica",33                     margin: CGFloat = 140, background: CGFloat = 1, ink: CGFloat = 0.05, rotationDegrees: CGFloat = 0) -> CGImage {34        let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!,35                            bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!36        ctx.setFillColor(CGColor(red: background, green: background, blue: background, alpha: 1))37        ctx.fill(CGRect(x: 0, y: 0, width: width, height: height))38        if rotationDegrees != 0 {39            ctx.translateBy(x: CGFloat(width) / 2, y: CGFloat(height) / 2)40            ctx.rotate(by: rotationDegrees * .pi / 180)41            ctx.translateBy(x: -CGFloat(width) / 2, y: -CGFloat(height) / 2)42        }43        let font = CTFontCreateWithName(fontName as CFString, fontSize, nil)44        let color = CGColor(red: ink, green: ink, blue: ink, alpha: 1)45        var y = CGFloat(height) - margin - fontSize46        for line in text.split(separator: "\n", omittingEmptySubsequences: false) {47            let attributed = NSAttributedString(string: String(line), attributes: [48                NSAttributedString.Key(kCTFontAttributeName as String): font,49                NSAttributedString.Key(kCTForegroundColorAttributeName as String): color,50            ])51            ctx.textPosition = CGPoint(x: margin, y: y)52            CTLineDraw(CTLineCreateWithAttributedString(attributed), ctx)53            y -= fontSize * 1.754        }55        return ctx.makeImage()!56    }5758    /// Draws cells at fixed column positions (a borderless table).59    static func table(_ rows: [[String]], columnX: [CGFloat], width: Int = 1654, height: Int = 1200, fontSize: CGFloat = 36) -> CGImage {60        let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!,61                            bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!62        ctx.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: 1))63        ctx.fill(CGRect(x: 0, y: 0, width: width, height: height))64        let font = CTFontCreateWithName("Helvetica" as CFString, fontSize, nil)65        var y = CGFloat(height) - 16066        for row in rows {67            for (c, cell) in row.enumerated() {68                let attributed = NSAttributedString(string: cell, attributes: [NSAttributedString.Key(kCTFontAttributeName as String): font])69                ctx.textPosition = CGPoint(x: columnX[c], y: y)70                CTLineDraw(CTLineCreateWithAttributedString(attributed), ctx)71            }72            y -= fontSize * 273        }74        return ctx.makeImage()!75    }7677    static func jpeg(_ image: CGImage, quality: CGFloat = 0.9) -> Data { try! PageRenderer().jpegData(image, quality: quality) }7879    static func blurred(_ image: CGImage, radius: Double) -> CGImage {80        let ci = CIImage(cgImage: image).clampedToExtent().applyingGaussianBlur(sigma: radius).cropped(to: CGRect(x: 0, y: 0, width: image.width, height: image.height))81        return CIContext().createCGImage(ci, from: ci.extent)!82    }8384    /// A vector PDF with real text, one line per page.85    static func textPDF(pages: [String], size: CGSize = CGSize(width: 612, height: 792), password: String? = nil, at url: URL) {86        var box = CGRect(origin: .zero, size: size)87        var info: [CFString: Any] = [kCGPDFContextTitle: "Fixture"]88        if let password { info[kCGPDFContextUserPassword] = password; info[kCGPDFContextOwnerPassword] = password }89        let ctx = CGContext(url as CFURL, mediaBox: &box, info as CFDictionary)!90        let font = CTFontCreateWithName("Helvetica" as CFString, 24, nil)91        for text in pages {92            ctx.beginPDFPage(nil)93            ctx.textPosition = CGPoint(x: 72, y: size.height - 100)94            CTLineDraw(CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: [NSAttributedString.Key(kCTFontAttributeName as String): font])), ctx)95            ctx.endPDFPage()96        }97        ctx.closePDF()98    }99100    static func tempDirectory() -> URL {101        let url = FileManager.default.temporaryDirectory.appendingPathComponent("orix-tests-\(UUID().uuidString)", isDirectory: true)102        try! FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)103        return url104    }105106    static func processor() -> DocumentProcessor {107        DocumentProcessor(store: try! DocumentStore(root: tempDirectory()))108    }109110    /// A committed document made of the given page images.111    static func document(_ images: [CGImage], title: String = "Test", in processor: DocumentProcessor, edit: PageEdit = PageEdit()) async throws -> DocumentManifest {112        var draft = try await processor.store.beginDraft(title: title)113        for image in images { try await processor.store.addImage(jpeg(image), fileExtension: "jpg", edit: edit, to: &draft) }114        return try await processor.store.commit(draft)115    }116}117
Files main
Menu

Theme