SPB Git

Repository Public License

EngineTests.swift 42.5 KB 638 lines swift

1// ORIX Convert — Packages/EngineVector/Tests/EngineVectorTests/EngineTests.swift2// Description: Tests of the ConversionEngine: every declared path converts a real fixture and validates, options,3//              preflight honesty, malformed input, cancellation, and SVG rendering through WebKit (vector PDF,4//              bitmap size / scale / alpha, scripts not executed, remote references never fetched).5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import ConvertCore7import CoreGraphics8import Foundation9import ImageIO10import Network11import Testing12@testable import EngineVector1314final class WarningLog: @unchecked Sendable {15    private let lock = NSLock()16    private var items: [ConversionWarning] = []17    private var fractions: [Double?] = []18    func add(_ w: ConversionWarning) { lock.lock(); items.append(w); lock.unlock() }19    func add(_ p: ProgressUpdate) { lock.lock(); fractions.append(p.fraction); lock.unlock() }20    var warnings: [ConversionWarning] { lock.lock(); defer { lock.unlock() }; return items }21    var progress: [Double?] { lock.lock(); defer { lock.unlock() }; return fractions }22    var codes: Set<String> { Set(warnings.map(\.code)) }23}2425struct Run {26    let output: ConversionOutput27    let checks: [ValidationCheck]28    let log: WarningLog29    var file: URL { output.files[0] }30}3132enum EngineHarness {33    static let engine = VectorEngine()3435    static func run(_ source: URL, _ from: FormatID, _ to: FormatID, operation: String? = nil, options: [String: OptionValue] = [:], in dir: URL) async throws -> Run {36        let request = ConversionRequest(source: source, sourceFormat: from, destinationFormat: to, operation: operation, options: ConversionOptions(options))37        let work = dir.appendingPathComponent("work-\(UUID().uuidString)", isDirectory: true)38        try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)39        let log = WarningLog()40        let context = ConversionContext(workDirectory: work, progress: { log.add($0) }, warn: { log.add($0) })41        let inspection = try await engine.inspect(source, format: from)42        let output = try await engine.convert(request, context: context)43        #expect(output.files.count == 1)44        #expect(output.files[0].path.hasPrefix(work.path), "the engine writes only inside the work directory")45        let checks = try await engine.validate(output, request: request, source: inspection)46        return Run(output: output, checks: checks, log: log)47    }4849    /// Encodes a fixture in `format` (WebP comes from the bundled fixture: ImageIO cannot encode it).50    static func encode(_ image: CGImage, as format: FormatID, in dir: URL) throws -> URL {51        let url = dir.appendingPathComponent("fixture-\(format.rawValue).\(FormatCatalog.format(format)?.preferredExtension ?? format.rawValue)")52        if format == .webp {53            let bundled = try #require(Bundle.module.url(forResource: "shapes", withExtension: "webp", subdirectory: "Fixtures"))54            try FileManager.default.copyItem(at: bundled, to: url)55            return url56        }57        let types: [FormatID: String] = [.png: "public.png", .jpeg: "public.jpeg", .tiff: "public.tiff", .bmp: "com.microsoft.bmp", .gif: "com.compuserve.gif",58                                         .heic: "public.heic", .avif: "public.avif", .jp2: "public.jpeg-2000", .tga: "com.truevision.tga-image", .psd: "com.adobe.photoshop-image"]59        let type = try #require(types[format])60        #expect(Fixture.write(image, type: type, to: url, properties: [kCGImageDestinationLossyCompressionQuality: 0.95]), "ImageIO could not encode \(format)")61        return url62    }6364    static func write(_ svg: String, _ name: String, in dir: URL) throws -> URL {65        let url = dir.appendingPathComponent(name)66        try Data(svg.utf8).write(to: url)67        return url68    }69}7071@Suite("Engine: tracing paths") struct EngineTracingTests {72    let engine = EngineHarness.engine7374    @Test func declaredPaths() {75        let paths = engine.paths76        #expect(paths.count == VectorEngine.rasterSources.count * 2 + 4)77        #expect(Set(paths.map(\.id)).count == paths.count)78        #expect(paths.allSatisfy { $0.engine == "vector" && $0.status == .supported && !$0.limitations.isEmpty })79        #expect(paths.filter { $0.operation == VectorEngine.vectorizeOperation }.allSatisfy { $0.destination == .svg || $0.destination == .pdf })80        #expect(paths.filter { $0.source == .svg }.map(\.destination).sorted() == [.jpeg, .pdf, .png, .tiff])81        #expect(engine.availability() == .available)82        #expect(makeEngines().count == 1 && makeEngines()[0].id == "vector")83        #expect(engine.inspectableFormats == Set(VectorEngine.rasterSources + [.svg]))84        for path in paths {85            let options = engine.options(for: path)86            #expect(!options.isEmpty)87            #expect(Set(options.map(\.id)).count == options.count)88            #expect(options.allSatisfy { $0.id == $0.id.lowercased() && !$0.label.isEmpty })89        }90        let tracing = engine.options(for: paths[0]).map(\.id)91        for key in ["mode", "colors", "threshold.mode", "threshold", "edge.sensitivity", "curve.smoothness", "simplify", "region.min",92                    "background.remove", "transparency", "detail", "precision"] {93            #expect(tracing.contains(key), "missing option \(key)")94        }95    }9697    @Test("Every raster source traces to SVG and to vector PDF", arguments: VectorEngine.rasterSources)98    func tracesEverySource(_ format: FormatID) async throws {99        let dir = Fixture.temporaryDirectory("trace-\(format.rawValue)")100        defer { try? FileManager.default.removeItem(at: dir) }101        // Opaque fixture: several formats (JPEG, BMP) have no alpha.102        let image = Fixture.illustration(160)103        let source = try EngineHarness.encode(image, as: format, in: dir)104        let (w, h) = format == .webp ? (96, 96) : (160, 160)105        let reference: CGImage = format == .webp ? try RasterDecoder.decode(source).image : image106107        let svg = try await EngineHarness.run(source, format, .svg, operation: VectorEngine.vectorizeOperation, options: ["mode": .string("illustration")], in: dir)108        #expect(svg.file.pathExtension == "svg")109        #expect(!svg.checks.isEmpty && svg.checks.allSatisfy { $0.passed }, "\(svg.checks.filter { !$0.passed })")110        let text = try String(contentsOf: svg.file, encoding: .utf8)111        #expect(text.contains("<path") && !text.contains("<image") && !text.contains("base64"))112        let parsed = try TracedSVGReader.read(text)113        #expect(parsed.document.width == w && parsed.document.height == h)114        let rendering = try #require(parsed.document.makeImage(pixelWidth: w, pixelHeight: h))115        // Lossy sources (JPEG, HEIC, AVIF, JPEG 2000) add their own compression error; GIF is palettised.116        #expect(Fixture.meanAbsoluteError(reference, rendering) < 2.5, "\(format): \(Fixture.meanAbsoluteError(reference, rendering))")117        let facts = svg.output.facts118        for key in ["paths", "nodes", "svgBytes", "colors", "regions", "similarity.meanDeltaE", "similarity.matchingPixels", "similarity.edgeRecall", "content.kind", "width", "height"] {119            #expect(facts[key] != nil, "missing fact \(key)")120        }121        #expect(facts["svgBytes"] == "\(text.utf8.count)")122        #expect(facts["paths"] == "\(parsed.report.pathCount)")123        #expect(Int(facts["nodes"] ?? "") ?? 0 >= parsed.report.nodeCount)124        #expect((Double(facts["similarity.meanDeltaE"] ?? "") ?? 99) < 2.0)125        #expect(svg.log.progress.last == .some(1))126        #expect(svg.log.progress.compactMap { $0 }.allSatisfy { $0 >= 0 && $0 <= 1 })127128        let pdf = try await EngineHarness.run(source, format, .pdf, operation: VectorEngine.vectorizeOperation,129                                              options: ["mode": .string("illustration"), "pdf.dpi": .double(144)], in: dir)130        #expect(pdf.file.pathExtension == "pdf")131        #expect(!pdf.checks.isEmpty && pdf.checks.allSatisfy { $0.passed }, "\(pdf.checks.filter { !$0.passed })")132        let report = try #require(PDFInspector.inspect(pdf.file))133        #expect(report.isPureVector)134        #expect(report.pageCount == 1)135        #expect(abs(report.pageWidth - Double(w) / 2) < 0.01 && abs(report.pageHeight - Double(h) / 2) < 0.01)136    }137138    @Test func transparencySurvivesInSVGAndPDF() async throws {139        let dir = Fixture.temporaryDirectory("alpha")140        defer { try? FileManager.default.removeItem(at: dir) }141        let source = try EngineHarness.encode(Fixture.transparentIcon(), as: .png, in: dir)142        let inspection = try await engine.inspect(source, format: .png)143        #expect(inspection.pixelWidth == 128 && inspection.pixelHeight == 128 && inspection.hasAlpha == true)144        let svg = try await EngineHarness.run(source, .png, .svg, operation: VectorEngine.vectorizeOperation, options: ["mode": .string("icon")], in: dir)145        #expect(svg.checks.allSatisfy { $0.passed })146        let parsed = try TracedSVGReader.read(String(contentsOf: svg.file, encoding: .utf8)).document147        #expect(Probe.pixel(parsed.makeImage(pixelWidth: 128, pixelHeight: 128)!, 3, 3)[3] == 0)148        let pdf = try await EngineHarness.run(source, .png, .pdf, operation: VectorEngine.vectorizeOperation, options: ["mode": .string("icon")], in: dir)149        let page = try #require(CGPDFDocument(pdf.file as CFURL)?.page(at: 1))150        let rendered = Fixture.render(128, 128, background: nil) { ctx in ctx.translateBy(x: 0, y: 128); ctx.scaleBy(x: 1, y: -1); ctx.drawPDFPage(page) }151        #expect(Probe.pixel(rendered, 3, 3)[3] == 0)152        #expect(Probe.pixel(rendered, 20, 64) == [10, 132, 255, 255])153    }154155    @Test func modesArePresetsThatExplicitOptionsOverride() async throws {156        let logo = try VectorSettings(options: ConversionOptions(["mode": .string("logo")]))157        #expect(logo == VectorSettings.preset(.logo))158        let tuned = try VectorSettings(options: ConversionOptions(["mode": .string("line-art"), "colors": .int(3), "detail": .int(10), "background.remove": .string("keep"),159                                                                    "threshold.mode": .string("manual"), "threshold": .int(30), "background.color": .string("#102030")]))160        #expect(tuned.mode == .lineArt && tuned.colorCount == 3 && abs(tuned.detail - 0.1) < 1e-9)161        #expect(tuned.backgroundRemoval == .keep && !tuned.automaticThreshold && abs(tuned.threshold - 0.3) < 1e-9)162        #expect(tuned.backgroundFill == VectorColor(red: 16, green: 32, blue: 48))163        #expect(tuned.curveSmoothness == VectorSettings.preset(.lineArt).curveSmoothness)164        for mode in VectorMode.allCases {165            let roundTrip = try VectorSettings(options: VectorEngine.presetOptions(for: mode))166            #expect(roundTrip == VectorSettings.preset(mode).normalized(), "\(mode)")167        }168        #expect(throws: ConversionError.self) { _ = try VectorSettings(options: ConversionOptions(["mode": .string("magic")])) }169        #expect(throws: ConversionError.self) { _ = try VectorSettings(options: ConversionOptions(["denoise": .string("ai")])) }170        #expect(throws: ConversionError.self) { _ = try VectorSettings(options: ConversionOptions(["background.color": .string("mauve-ish")])) }171        #expect(try VectorSettings(options: ConversionOptions(["colors": .int(999)])).colorCount == 64)172173        // Each mode converts a logo through the engine.174        let dir = Fixture.temporaryDirectory("modes")175        defer { try? FileManager.default.removeItem(at: dir) }176        let source = try EngineHarness.encode(Fixture.text("Ax", width: 260, height: 150, fontSize: 110), as: .png, in: dir)177        for mode in VectorMode.allCases {178            let run = try await EngineHarness.run(source, .png, .svg, operation: VectorEngine.vectorizeOperation, options: ["mode": .string(mode.rawValue)], in: dir)179            #expect(run.checks.allSatisfy { $0.passed }, "\(mode): \(run.checks.filter { !$0.passed })")180            #expect(run.output.facts["mode"] == mode.rawValue)181            #expect(run.output.facts["backgroundRemoved"] == (mode.isMonochrome ? "true" : "false"))182            if mode.isMonochrome { #expect(run.output.facts["colors"] == "1" && run.output.facts["threshold"] != nil) }183        }184    }185186    @Test func preflightAndConvertWarnHonestly() async throws {187        let dir = Fixture.temporaryDirectory("honesty")188        defer { try? FileManager.default.removeItem(at: dir) }189        let photo = try EngineHarness.encode(Fixture.photoLike(), as: .jpeg, in: dir)190        let request = ConversionRequest(source: photo, sourceFormat: .jpeg, destinationFormat: .svg, operation: VectorEngine.vectorizeOperation)191        let warnings = engine.preflight(request, inspection: nil)192        let warning = try #require(warnings.first { $0.code == "photographic-content" })193        #expect(warning.severity == .caution)194        #expect(warning.message.contains("photograph"))195        let run = try await EngineHarness.run(photo, .jpeg, .svg, operation: VectorEngine.vectorizeOperation, options: ["mode": .string("illustration")], in: dir)196        #expect(run.log.codes.contains("photographic-content"))197        #expect(run.output.facts["content.kind"] == "photographic")198        #expect((Double(run.output.facts["similarity.meanDeltaE"] ?? "") ?? 0) > 2)199        #expect((Int(run.output.facts["nodes"] ?? "") ?? 0) > 300)200        #expect(run.checks.allSatisfy { $0.passed })201202        let logo = try EngineHarness.encode(Fixture.text(), as: .png, in: dir)203        let clean = engine.preflight(ConversionRequest(source: logo, sourceFormat: .png, destinationFormat: .svg, operation: VectorEngine.vectorizeOperation), inspection: nil)204        #expect(clean.isEmpty, "\(clean)")205        let mono = engine.preflight(ConversionRequest(source: try EngineHarness.encode(Fixture.illustration(), as: .tiff, in: dir), sourceFormat: .tiff, destinationFormat: .svg,206                                                      operation: VectorEngine.vectorizeOperation, options: ConversionOptions(["mode": .string("monochrome")])), inspection: nil)207        #expect(mono.contains { $0.code == "colours-reduced" && $0.severity == .dataLoss })208209        // Animated GIF: only the first frame, and it is said.210        let gif = dir.appendingPathComponent("anim.gif")211        let destination = try #require(CGImageDestinationCreateWithURL(gif as CFURL, "com.compuserve.gif" as CFString, 2, nil))212        CGImageDestinationAddImage(destination, Fixture.disc(96, radius: 30), nil)213        CGImageDestinationAddImage(destination, Fixture.polygons(96), nil)214        #expect(CGImageDestinationFinalize(destination))215        #expect(try await engine.inspect(gif, format: .gif).frameCount == 2)216        let animated = try await EngineHarness.run(gif, .gif, .svg, operation: VectorEngine.vectorizeOperation, options: ["mode": .string("monochrome")], in: dir)217        #expect(animated.log.warnings.contains { $0.code == "animation-first-frame" && $0.severity == .dataLoss })218        #expect(engine.preflight(ConversionRequest(source: gif, sourceFormat: .gif, destinationFormat: .svg, operation: VectorEngine.vectorizeOperation), inspection: nil)219            .contains { $0.code == "animation-first-frame" })220        #expect(animated.output.facts["subpaths"] == "1", "the first frame is the disc")221    }222223    @Test func malformedInputAndUnsupportedRequests() async throws {224        let dir = Fixture.temporaryDirectory("bad")225        defer { try? FileManager.default.removeItem(at: dir) }226        let context = ConversionContext(workDirectory: dir)227        let garbage = dir.appendingPathComponent("garbage.png")228        try Data((0..<5000).map { UInt8(truncatingIfNeeded: $0 &* 17) }).write(to: garbage)229        await #expect(throws: ConversionError.self) {230            _ = try await engine.convert(ConversionRequest(source: garbage, sourceFormat: .png, destinationFormat: .svg, operation: VectorEngine.vectorizeOperation), context: context)231        }232        // A PNG cut in the middle of its data.233        let whole = try EngineHarness.encode(Fixture.photoLike(128), as: .png, in: dir)234        let cut = dir.appendingPathComponent("cut.png")235        try Data(contentsOf: whole).prefix(60).write(to: cut)236        await #expect(throws: ConversionError.self) {237            _ = try await engine.convert(ConversionRequest(source: cut, sourceFormat: .png, destinationFormat: .svg, operation: VectorEngine.vectorizeOperation), context: context)238        }239        await #expect(throws: ConversionError.self) { _ = try await engine.inspect(garbage, format: .png) }240        #expect(engine.preflight(ConversionRequest(source: garbage, sourceFormat: .png, destinationFormat: .svg, operation: VectorEngine.vectorizeOperation), inspection: nil).isEmpty)241        // Not a declared path: plain PNG → SVG without the operation, or PNG → PNG.242        await #expect(throws: ConversionError.unsupportedPath(source: .png, destination: .svg)) {243            _ = try await engine.convert(ConversionRequest(source: whole, sourceFormat: .png, destinationFormat: .svg), context: context)244        }245        await #expect(throws: ConversionError.self) {246            _ = try await engine.convert(ConversionRequest(source: whole, sourceFormat: .png, destinationFormat: .pdf, operation: VectorEngine.vectorizeOperation,247                                                           options: ConversionOptions(["pdf.dpi": .double(1)])), context: context)248        }249        // Nothing was left behind by the failures.250        let leftovers = try FileManager.default.contentsOfDirectory(atPath: dir.path).filter { $0.hasSuffix(".svg") || $0.hasSuffix(".pdf") }251        #expect(leftovers.isEmpty)252    }253254    @Test func conversionCanBeCancelled() async throws {255        let dir = Fixture.temporaryDirectory("cancel")256        defer { try? FileManager.default.removeItem(at: dir) }257        let source = try EngineHarness.encode(Fixture.photoLike(512), as: .png, in: dir)258        let request = ConversionRequest(source: source, sourceFormat: .png, destinationFormat: .svg, operation: VectorEngine.vectorizeOperation,259                                        options: ConversionOptions(["mode": .string("high-detail")]))260        let context = ConversionContext(workDirectory: dir)261        let engine = self.engine262        let task = Task { try await engine.convert(request, context: context) }263        try await Task.sleep(nanoseconds: 40_000_000)264        task.cancel()265        await #expect(throws: CancellationError.self) { _ = try await task.value }266        let already = Task { () -> ConversionOutput in267            withUnsafeCurrentTask { $0?.cancel() }268            return try await engine.convert(request, context: context)269        }270        await #expect(throws: CancellationError.self) { _ = try await already.value }271    }272}273274/// The reduction path end to end: files above the 4096 × 4096-pixel tracing limit are decoded reduced, traced, and275/// written in the coordinates of the original. It had no engine-level test before 2026-11-21.276@Suite("Engine: images above the tracing limit") struct EngineReductionTests {277    /// The third size (33 MP) takes a while in a debug build: it runs with ORIX_VECTOR_BENCH=1.278    static let sizes: [(Int, Int, Int)] = [(4100, 4100, 3), (6000, 4000, 9)] + (ProcessInfo.processInfo.environment["ORIX_VECTOR_BENCH"] == "1" ? [(8192, 4096, 14)] : [])279280    @Test(arguments: sizes)281    func largeImagesAreTracedReducedAndStayInsideTheViewBox(_ width: Int, _ height: Int, _ seed: Int) async throws {282        let dir = Fixture.temporaryDirectory("reduced")283        defer { try? FileManager.default.removeItem(at: dir) }284        let source = dir.appendingPathComponent("large-\(width)x\(height).png")285        #expect(Fixture.write(Fixture.seeded(width: width, height: height, seed: seed), type: "public.png", to: source))286        #expect(width * height > VectorSettings().maximumTracePixels)287        let run = try await EngineHarness.run(source, .png, .svg, operation: VectorEngine.vectorizeOperation, in: dir)288        #expect(run.checks.contains { $0.name == "svg.withinViewBox" })289        #expect(run.checks.allSatisfy { $0.passed }, "\(run.checks.filter { !$0.passed })")290        #expect(run.log.codes.contains("traced-reduced"))291        let facts = run.output.facts292        #expect(facts["width"] == "\(width)" && facts["height"] == "\(height)")293        let tracedWidth = try #require(facts["tracedWidth"].flatMap(Int.init)), tracedHeight = try #require(facts["tracedHeight"].flatMap(Int.init))294        #expect(tracedWidth < width && tracedWidth * tracedHeight <= VectorSettings().maximumTracePixels)295        let parsed = try TracedSVGReader.read(try String(contentsOf: run.file, encoding: .utf8))296        #expect(parsed.report.viewBoxWidth == Double(width) && parsed.report.viewBoxHeight == Double(height))297        #expect(Fixture.excursion(parsed.document) <= 1e-6, "a contour leaves the canvas by \(Fixture.excursion(parsed.document)) px")298        // The drawing spans the whole original canvas, not the reduced one.299        let xs = parsed.document.layers.flatMap { $0.subpaths.flatMap { [$0.start.x] + $0.segments.map(\.end.x) } }300        #expect((xs.max() ?? 0) > Double(width) - 1.5)301    }302}303304/// Counts TCP connections made to a local port: any fetch of a "remote" reference would show up here.305final class ConnectionCounter: @unchecked Sendable {306    let listener: NWListener307    let counter = Counter()308    var port: UInt16 { listener.port?.rawValue ?? 0 }309310    init() throws {311        let parameters = NWParameters.tcp312        parameters.requiredLocalEndpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: .any)313        listener = try NWListener(using: parameters)314        let counter = self.counter315        listener.newConnectionHandler = { connection in316            _ = counter.increment()317            connection.start(queue: .global())318            connection.receive(minimumIncompleteLength: 1, maximumLength: 4096) { _, _, _, _ in319                let body = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"320                connection.send(content: Data(body.utf8), completion: .contentProcessed { _ in connection.cancel() })321            }322        }323    }324325    func start() async throws {326        let ready = Counter()327        try await withCheckedThrowingContinuation { (c: CheckedContinuation<Void, Error>) in328            listener.stateUpdateHandler = { state in329                switch state {330                case .ready: if ready.increment() == 1 { c.resume() }331                case .failed(let error): if ready.increment() == 1 { c.resume(throwing: error) }332                default: break333                }334            }335            listener.start(queue: .global())336        }337    }338}339340@Suite("Engine: SVG rendering", .serialized) struct EngineRenderingTests {341    let engine = EngineHarness.engine342343    static let sample = """344    <?xml version="1.0" encoding="UTF-8"?>345    <svg xmlns="http://www.w3.org/2000/svg" width="200" height="100" viewBox="0 0 200 100">346      <title>Sample</title>347      <rect x="20" y="20" width="60" height="60" fill="#e02020"/>348      <circle cx="140" cy="50" r="30" fill="#2040d0"/>349      <text x="24" y="96" font-family="Helvetica" font-size="12" fill="#000">Vector</text>350    </svg>351    """352353    @Test func svgInspectionReadsSizeAndFeatures() async throws {354        let info = try SVGInspector.inspect(Data(Self.sample.utf8))355        #expect(info.intrinsicWidth == 200 && info.intrinsicHeight == 100 && info.viewBox == [0, 0, 200, 100])356        #expect(info.title == "Sample" && info.textElementCount == 1 && info.elementCount == 5)357        #expect(!info.hasScripts && !info.hasAnimations && info.externalReferences.isEmpty && !info.usesDefaultSize)358        func size(_ root: String) throws -> (Double, Double, Bool) {359            let i = try SVGInspector.inspect(Data("<svg xmlns='http://www.w3.org/2000/svg' \(root)/>".utf8))360            return (i.intrinsicWidth, i.intrinsicHeight, i.usesDefaultSize)361        }362        #expect(try size("width='2in' height='25.4mm'") == (192, 96, false))363        #expect(try size("width='72pt' height='1pc'") == (96, 16, false))364        #expect(try size("viewBox='0 0 400 100'") == (400, 100, false))365        #expect(try size("width='100' viewBox='0 0 400 100'") == (100, 25, false))366        #expect(try size("height='50' viewBox='0 0 400 100'") == (200, 50, false))367        #expect(try size("width='100%' height='100%' viewBox='0 0 30 60'") == (30, 60, false))368        #expect(try size("") == (300, 150, true))369        let risky = """370        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="10" height="10" onload="x()">371          <style>@import url("https://example.com/a.css"); .a { fill: url(#g); background: url(http://example.com/b.png) }</style>372          <script>alert(1)</script>373          <image xlink:href="https://example.com/c.png" width="5" height="5"/>374          <image href="data:image/png;base64,AAAA" width="5" height="5"/>375          <use href="other.svg#shape"/><use href="#local"/>376          <rect width="5" height="5"><animate attributeName="x" from="0" to="5" dur="1s"/></rect>377          <filter id="f"><feGaussianBlur stdDeviation="2"/></filter>378        </svg>379        """380        let flagged = try SVGInspector.inspect(Data(risky.utf8))381        #expect(flagged.hasScripts && flagged.hasEventHandlers && flagged.hasAnimations && flagged.hasFilters)382        #expect(flagged.embeddedImageCount == 1)383        #expect(Set(flagged.externalReferences) == ["https://example.com/a.css", "http://example.com/b.png", "https://example.com/c.png", "other.svg#shape"])384        let codes = Set(VectorEngine.renderWarnings(flagged, destination: .pdf, options: .init()).map(\.code))385        #expect(codes.isSuperset(of: ["scripts-not-executed", "animation-first-frame", "external-references-not-loaded", "pdf-contains-bitmaps"]))386        #expect(VectorEngine.renderWarnings(flagged, destination: .jpeg, options: .init()).contains { $0.code == "alpha-flattened" })387        #expect(throws: SVGReadError.self) { _ = try SVGInspector.inspect(Data("<html><body/></html>".utf8)) }388        #expect(throws: SVGReadError.self) { _ = try SVGInspector.inspect(Data("<svg xmlns='http://www.w3.org/2000/svg'><g></svg>".utf8)) }389        #expect(throws: SVGReadError.self) { _ = try SVGInspector.inspect(Data()) }390    }391392    @Test func renderPlanFollowsTheOptions() throws {393        let info = try SVGInspector.inspect(Data(Self.sample.utf8))394        func plan(_ o: [String: OptionValue], _ d: FormatID) throws -> SVGRenderPlan { try VectorEngine.renderPlan(info: info, options: ConversionOptions(o), destination: d) }395        let plain = try plan([:], .png)396        #expect(plain.width == 200 && plain.height == 100 && plain.background == nil)397        #expect(try plan(["scale": .double(2.5)], .png).width == 500)398        #expect(try plan(["dpi": .int(192)], .png).width == 400)399        #expect(try plan(["resize.width": .int(50)], .png).height == 25)400        #expect(try plan(["resize.height": .int(300)], .png).width == 600)401        #expect(try plan(["resize.width": .int(64), "resize.height": .int(64)], .png).height == 64)402        let page = try plan([:], .pdf)403        #expect(page.width == 150 && page.height == 75, "96 CSS pixels per inch → 72 points per inch")404        #expect(try plan(["scale": .double(2)], .pdf).width == 300)405        #expect(try plan([:], .jpeg).background == .white)406        #expect(page.background == .white)407        #expect(try plan(["background": .string("#000")], .png).background == .black)408        #expect(throws: ConversionError.self) { _ = try plan(["scale": .double(0)], .png) }409        #expect(throws: ConversionError.self) { _ = try plan(["scale": .double(32), "dpi": .int(1200)], .png) }410        #expect(throws: ConversionError.self) { _ = try plan(["background": .string("nope")], .png) }411        #expect(throws: ConversionError.self) { _ = try plan(["resize.width": .int(-4)], .png) }412    }413414    @Test func svgToVectorPDF() async throws {415        let dir = Fixture.temporaryDirectory("svgpdf")416        defer { try? FileManager.default.removeItem(at: dir) }417        let source = try EngineHarness.write(Self.sample, "sample.svg", in: dir)418        let inspection = try await engine.inspect(source, format: .svg)419        #expect(inspection.pixelWidth == 200 && inspection.pixelHeight == 100)420        let run = try await EngineHarness.run(source, .svg, .pdf, in: dir)421        #expect(!run.checks.isEmpty && run.checks.allSatisfy { $0.passed }, "\(run.checks.filter { !$0.passed })")422        let report = try #require(PDFInspector.inspect(run.file))423        #expect(report.pageCount == 1)424        #expect(abs(report.pageWidth - 150) < 0.5 && abs(report.pageHeight - 75) < 0.5)425        #expect(report.imageDrawCount == 0 && report.imageResourceCount == 0, "no image XObject: the PDF is vector")426        #expect(report.pathPaintCount >= 2, "rectangle and circle are path fills")427        #expect(report.textShowCount >= 1, "text stays text")428        #expect(run.log.codes.contains("fonts-substituted"))429        // The page really shows the drawing, and nothing is painted behind it.430        let page = try #require(CGPDFDocument(run.file as CFURL)?.page(at: 1))431        let rendered = Fixture.render(600, 300, background: nil) { ctx in ctx.translateBy(x: 0, y: 300); ctx.scaleBy(x: 4, y: -4); ctx.drawPDFPage(page) }432        #expect(Probe.pixel(rendered, 150, 150) == [224, 32, 32, 255])433        #expect(Probe.pixel(rendered, 420, 150) == [32, 64, 208, 255])434        #expect(Probe.pixel(rendered, 300, 20) == [255, 255, 255, 255], "the page is opaque white where the SVG draws nothing")435        #expect(run.log.warnings.contains { $0.code == "alpha-flattened" && $0.severity == .dataLoss })436        #expect(run.output.facts["background"] == "#fff")437438        let sized = try await EngineHarness.run(source, .svg, .pdf, options: ["resize.width": .int(400), "background": .string("#ffff00")], in: dir)439        let sizedReport = try #require(PDFInspector.inspect(sized.file))440        #expect(abs(sizedReport.pageWidth - 400) < 0.5 && abs(sizedReport.pageHeight - 200) < 0.5)441        #expect(sized.checks.allSatisfy { $0.passed })442        let sizedPage = try #require(CGPDFDocument(sized.file as CFURL)?.page(at: 1))443        let onYellow = Fixture.render(400, 200, background: nil) { ctx in ctx.translateBy(x: 0, y: 200); ctx.scaleBy(x: 1, y: -1); ctx.drawPDFPage(sizedPage) }444        #expect(Probe.pixel(onYellow, 200, 20) == [255, 255, 0, 255])445    }446447    @Test func svgToBitmapsWithScaleAndAlpha() async throws {448        let dir = Fixture.temporaryDirectory("svgpng")449        defer { try? FileManager.default.removeItem(at: dir) }450        let source = try EngineHarness.write(Self.sample, "sample.svg", in: dir)451452        let png = try await EngineHarness.run(source, .svg, .png, in: dir)453        #expect(png.checks.allSatisfy { $0.passed }, "\(png.checks.filter { !$0.passed })")454        let image = try RasterDecoder.decode(png.file)455        #expect(image.image.width == 200 && image.image.height == 100 && image.hasAlphaChannel)456        #expect(Probe.pixel(image.image, 50, 50) == [224, 32, 32, 255])457        #expect(Probe.pixel(image.image, 140, 50) == [32, 64, 208, 255])458        #expect(Probe.pixel(image.image, 100, 10) == [0, 0, 0, 0], "transparent background")459        // Anti-aliased edge of the circle: partial alpha, not a hard cut.460        let edge = (105...115).map { Probe.pixel(image.image, $0, 50)[3] }461        #expect(edge.first == 0 && edge.last == 255 && edge.contains { $0 > 0 && $0 < 255 })462463        let scaled = try await EngineHarness.run(source, .svg, .png, options: ["scale": .double(3)], in: dir)464        let big = try RasterDecoder.decode(scaled.file)465        #expect(big.image.width == 600 && big.image.height == 300)466        #expect(scaled.output.facts["width"] == "600")467        // Rendered at that size (sharp), not enlarged from 200 × 100: the circle edge is at most 2 pixels wide.468        let sharp = (300...340).map { Probe.pixel(big.image, $0, 150)[3] }.filter { $0 > 8 && $0 < 247 }469        #expect(sharp.count <= 2, "edge spread over \(sharp.count) pixels")470471        let dense = try await EngineHarness.run(source, .svg, .png, options: ["dpi": .int(192), "background": .string("#ffffff")], in: dir)472        let denseImage = try RasterDecoder.decode(dense.file)473        #expect(denseImage.image.width == 400 && denseImage.dpi == 192 && !denseImage.hasAlphaChannel)474        #expect(Probe.pixel(denseImage.image, 200, 20) == [255, 255, 255, 255])475        #expect(dense.checks.allSatisfy { $0.passed })476477        let jpeg = try await EngineHarness.run(source, .svg, .jpeg, options: ["quality": .int(95)], in: dir)478        #expect(jpeg.checks.allSatisfy { $0.passed })479        #expect(jpeg.log.warnings.contains { $0.code == "alpha-flattened" && $0.severity == .dataLoss })480        let jpegImage = try RasterDecoder.decode(jpeg.file)481        #expect(jpegImage.typeIdentifier == "public.jpeg" && jpegImage.image.width == 200)482        let white = Probe.pixel(jpegImage.image, 100, 10)483        #expect(white[0] > 248 && white[1] > 248 && white[2] > 248)484485        let tiff = try await EngineHarness.run(source, .svg, .tiff, options: ["resize.width": .int(80), "resize.height": .int(80)], in: dir)486        #expect(tiff.checks.allSatisfy { $0.passed })487        let tiffImage = try RasterDecoder.decode(tiff.file)488        #expect(tiffImage.typeIdentifier == "public.tiff" && tiffImage.image.width == 80 && tiffImage.image.height == 80)489        #expect(Probe.pixel(tiffImage.image, 40, 5)[3] == 0, "letterboxed: the SVG keeps its proportions inside the box")490491        await #expect(throws: ConversionError.self) { _ = try await EngineHarness.run(source, .svg, .png, options: ["scale": .double(30), "dpi": .int(600)], in: dir) }492    }493494    @Test func tracedSVGRendersTheSameInWebKit() async throws {495        // Independent check of the tracer's output: WebKit, not our own rasteriser, draws the traced SVG.496        let dir = Fixture.temporaryDirectory("roundtrip")497        defer { try? FileManager.default.removeItem(at: dir) }498        let image = Fixture.illustration(200)499        let source = try EngineHarness.encode(image, as: .png, in: dir)500        let traced = try await EngineHarness.run(source, .png, .svg, operation: VectorEngine.vectorizeOperation, options: ["mode": .string("illustration")], in: dir)501        let rendered = try await EngineHarness.run(traced.file, .svg, .png, in: dir)502        let back = try RasterDecoder.decode(rendered.file).image503        #expect(back.width == 200 && back.height == 200)504        #expect(Fixture.meanAbsoluteError(image, back) < 1.0, "\(Fixture.meanAbsoluteError(image, back))")505        let data = Fixture.pixels(back)506        #expect(stride(from: 3, to: data.count, by: 4).allSatisfy { data[$0] == 255 }, "no seam or hole between the traced regions")507    }508509    @Test func scriptsAreNotExecutedAndRemoteReferencesAreNeverFetched() async throws {510        let dir = Fixture.temporaryDirectory("network")511        defer { try? FileManager.default.removeItem(at: dir) }512        let server = try ConnectionCounter()513        try await server.start()514        defer { server.listener.cancel() }515        let port = server.port516        #expect(port != 0)517        // Positive control: the counter does see a connection when something really connects.518        let control = try #require(URL(string: "http://127.0.0.1:\(port)/control"))519        _ = try? await URLSession(configuration: .ephemeral).data(from: control)520        #expect(server.counter.current == 1)521522        let base = "http://127.0.0.1:\(port)"523        let svg = """524        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="120" height="80" viewBox="0 0 120 80" onload="document.getElementById('r').setAttribute('fill','#00ff00')">525          <style>526            @import url("\(base)/import.css");527            @font-face { font-family: Remote; src: url("\(base)/font.woff2"); }528            .bg { fill: url("\(base)/paint.svg#p") #ffffff; }529            text { font-family: Remote, Helvetica; }530          </style>531          <rect id="r" x="10" y="10" width="40" height="40" fill="#ff0000"/>532          <image href="\(base)/image.png" x="60" y="10" width="40" height="40"/>533          <image xlink:href="\(base)/image2.png" x="60" y="10" width="40" height="40"/>534          <use href="\(base)/sprite.svg#s"/>535          <text x="10" y="70" font-size="10">remote font</text>536          <foreignObject width="10" height="10"><img xmlns="http://www.w3.org/1999/xhtml" src="\(base)/fo.png"/></foreignObject>537          <script href="\(base)/script.js"/>538          <script>539            document.getElementById('r').setAttribute('fill', '#00ff00');540            fetch('\(base)/fetch'); new Image().src = '\(base)/beacon.png';541            window.location = '\(base)/navigate';542          </script>543          <a href="\(base)/link"><rect x="100" y="60" width="10" height="10" fill="#0000ff"/></a>544        </svg>545        """546        let source = try EngineHarness.write(svg, "remote.svg", in: dir)547        let request = ConversionRequest(source: source, sourceFormat: .svg, destinationFormat: .png)548        let preflight = Set(engine.preflight(request, inspection: nil).map(\.code))549        #expect(preflight.isSuperset(of: ["scripts-not-executed", "external-references-not-loaded"]))550551        for destination in VectorEngine.renderDestinations {552            let run = try await EngineHarness.run(source, .svg, destination, in: dir)553            #expect(run.checks.allSatisfy { $0.passed }, "\(destination): \(run.checks.filter { !$0.passed })")554            #expect(run.log.codes.isSuperset(of: ["scripts-not-executed", "external-references-not-loaded"]))555            if destination == .png {556                let image = try RasterDecoder.decode(run.file).image557                #expect(Probe.pixel(image, 30, 30) == [255, 0, 0, 255], "the script did not turn the square green")558                #expect(Probe.pixel(image, 80, 30)[3] == 0, "the remote image is simply absent")559            }560        }561        // Give any stray request time to arrive, then look at the counter.562        try await Task.sleep(nanoseconds: 700_000_000)563        #expect(server.counter.current == 1, "the renderer opened \(server.counter.current - 1) connection(s)")564    }565566    // Regression (2026-11-21): the rule list used the filter "^(about|data):"; WebKit's content-rule dialect has no567    // disjunction, the compilation failed and `try?` dropped the list, so it was never installed.568    @Test @MainActor func contentRuleListCompilesAndIsInstalled() async throws {569        let list = try await SVGWebRenderer.blockingRules()570        #expect(list.identifier == SVGWebRenderer.ruleListIdentifier)571        let stored = try await SVGWebRenderer.ruleStore().contentRuleList(forIdentifier: SVGWebRenderer.ruleListIdentifier)572        #expect(stored != nil)573        // Every render attaches it to its web view.574        let before = SVGWebRenderer.viewsWithContentRules575        _ = try await SVGWebRenderer.bitmap(svg: Data(Self.sample.utf8), pixelWidth: 40, pixelHeight: 20, background: .white)576        _ = try await SVGWebRenderer.pdf(svg: Data(Self.sample.utf8), pageWidth: 40, pageHeight: 20)577        #expect(SVGWebRenderer.viewsWithContentRules == before + 2)578        // A rule list WebKit cannot compile is a hard error, never a silent "no rules".579        let old = """580        [{"trigger":{"url-filter":".*"},"action":{"type":"block"}},581         {"trigger":{"url-filter":"^(about|data):"},"action":{"type":"ignore-previous-rules"}}]582        """583        await #expect(throws: SVGRenderError.self) { _ = try await SVGWebRenderer.blockingRules(source: old, identifier: "orix-convert-test-disjunction") }584    }585586    @Test @MainActor func eachNetworkLayerBlocksOnItsOwn() async throws {587        let server = try ConnectionCounter()588        try await server.start()589        defer { server.listener.cancel() }590        let base = "http://127.0.0.1:\(server.port)"591        // A page that would fetch four resources if nothing stopped it (the production page holds one data: image).592        let body = """593        <img src="\(base)/image.png"><link rel="stylesheet" href="\(base)/style.css">\594        <script src="\(base)/script.js"></script><video src="\(base)/video.mp4" autoplay></video>595        """596        func connections(_ layers: SVGWebRenderer.Layers) async throws -> Int {597            let before = server.counter.current598            let (view, loader) = try await SVGWebRenderer.load(body: body, width: 50, height: 50, background: "#fff", layers: layers)599            try await Task.sleep(nanoseconds: 800_000_000)600            _ = (view, loader)601            return server.counter.current - before602        }603        // Positive control: with the rule list and the policy both off, the page does reach the listener.604        let open = try await connections(.init(contentRules: false, contentSecurityPolicy: false, javaScriptDisabled: false))605        #expect(open >= 1, "the probe page fetched nothing even with every layer off: the test proves nothing")606        // The content rule list alone (no Content-Security-Policy, JavaScript allowed).607        #expect(try await connections(.init(contentRules: true, contentSecurityPolicy: false, javaScriptDisabled: false)) == 0)608        // The Content-Security-Policy alone.609        #expect(try await connections(.init(contentRules: false, contentSecurityPolicy: true, javaScriptDisabled: false)) == 0)610        // Everything on, as in production.611        #expect(try await connections(.all) == 0)612    }613614    @Test func malformedSVGIsRejected() async throws {615        let dir = Fixture.temporaryDirectory("badsvg")616        defer { try? FileManager.default.removeItem(at: dir) }617        let context = ConversionContext(workDirectory: dir)618        for (name, content) in [("broken.svg", "<svg xmlns='http://www.w3.org/2000/svg'><rect"), ("html.svg", "<html><body>hello</body></html>"), ("text.svg", "just some text")] {619            let url = try EngineHarness.write(content, name, in: dir)620            for destination in [FormatID.pdf, .png] {621                await #expect(throws: ConversionError.self, "\(name) → \(destination)") {622                    _ = try await engine.convert(ConversionRequest(source: url, sourceFormat: .svg, destinationFormat: destination), context: context)623                }624            }625            await #expect(throws: ConversionError.self) { _ = try await engine.inspect(url, format: .svg) }626        }627        let empty = dir.appendingPathComponent("empty.svg")628        try Data().write(to: empty)629        await #expect(throws: ConversionError.self) { _ = try await engine.convert(ConversionRequest(source: empty, sourceFormat: .svg, destinationFormat: .pdf), context: context) }630        // An SVG without size or viewBox renders at the CSS default, and says so.631        let unsized = try EngineHarness.write("<svg xmlns='http://www.w3.org/2000/svg'><rect width='300' height='150' fill='#00f'/></svg>", "unsized.svg", in: dir)632        let run = try await EngineHarness.run(unsized, .svg, .png, in: dir)633        #expect(run.log.codes.contains("svg-default-size"))634        let image = try RasterDecoder.decode(run.file).image635        #expect(image.width == 300 && image.height == 150 && Probe.pixel(image, 290, 140) == [0, 0, 255, 255])636    }637}638
Files main
Menu

Theme