From 10115489f8988cf6a649707202a51757708883a2 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 00:59:53 -0300 Subject: svg: an image that is an SVG document in a data URI is drawn Typst places an SVG image, and a PDF page imported with image(), as an whose href is the document in base64; svg.zig skipped every , so any Typst object holding one silently lost it. The parser now decodes such a document and walks it into the same drawing, mapped into the image's x, y, width and height (stretched with preserveAspectRatio="none", else fitted and centered, as SVG says), with its own ids, gradients and percentages and nothing inherited from around it but opacity. It is not clipped to its box (a PDF page never draws outside itself, and a clip per shape costs the renderers a pass over every contour). Raster images still draw nothing. The root's view box and size come from one function both documents use. Tests: a unit test at the end of svg.zig (ids of its own, stretched and fitted corners, a PNG skipped); two corpus cases for zig build diff, image.svg (two data-URI images, one stretched and turned, beside an outer gradient that shares an id with an inner one) and typst-image.typ (two SVGs placed by Typst): both renderers match resvg (mean 0.09-0.11). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- src/vector/svg.zig | 96 ++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 83 insertions(+), 13 deletions(-) (limited to 'src/vector') diff --git a/src/vector/svg.zig b/src/vector/svg.zig index 31d9b15..f1b7daf 100644 --- a/src/vector/svg.zig +++ b/src/vector/svg.zig @@ -4,11 +4,12 @@ //! `ellipse`, `line`, `polyline`, `polygon`. Styling: presentation //! attributes and `style="..."`, inherited as SVG specifies; solid colors, //! linear and radial gradients; fill rules; stroke width, caps, joins, miter -//! limit and dashes; `opacity`, `fill-opacity`, `stroke-opacity`. +//! limit and dashes; `opacity`, `fill-opacity`, `stroke-opacity`. Images +//! that are SVG documents in base64 data URIs (Typst's SVG and PDF images). //! //! Not supported: text (Typst outlines it), filters, masks, clipping, -//! patterns, markers, images, CSS stylesheets. Group opacity is approximated -//! by multiplying it into each shape. +//! patterns, markers, raster images, CSS stylesheets. Group opacity is +//! approximated by multiplying it into each shape. const std = @import("std"); const geom = @import("math"); const Drawing = @import("Drawing.zig"); @@ -23,23 +24,26 @@ pub fn parse(arena: std.mem.Allocator, source: []const u8) Error!Drawing { const root = doc.root orelse return error.InvalidSvg; if (!std.mem.eql(u8, doc.nodes.items[root].name, "svg")) return error.InvalidSvg; - var p: Parser = .{ .doc = &doc, .b = .init(arena), .arena = arena, .view = .{} }; - const n = doc.nodes.items[root]; - const w = doc.attr(n, "width"); - const h = doc.attr(n, "height"); + const port = viewport(&doc, doc.nodes.items[root]); + var p: Parser = .{ .doc = &doc, .b = .init(arena), .arena = arena, .view = port.view }; + try p.children(root, .identity, .{}); + return p.b.finish(port.view, port.width, port.height); +} + +/// A root `svg` element's view box and size in pixels, each standing in +/// for the other when missing. +fn viewport(doc: *const Document, n: Node) struct { view: geom.Rect, width: f32, height: f32 } { var view: geom.Rect = .{}; if (doc.attr(n, "viewBox")) |vb| { var nums = Numbers{ .text = vb }; view = .{ .x = nums.next() orelse 0, .y = nums.next() orelse 0, .w = nums.next() orelse 0, .h = nums.next() orelse 0 }; } - var width = if (w) |v| lengthPx(v, view.w) else view.w; - var height = if (h) |v| lengthPx(v, view.h) else view.h; + var width = if (doc.attr(n, "width")) |v| lengthPx(v, view.w) else view.w; + var height = if (doc.attr(n, "height")) |v| lengthPx(v, view.h) else view.h; if (view.w <= 0 or view.h <= 0) view = .{ .w = width, .h = height }; if (width <= 0) width = view.w; if (height <= 0) height = view.h; - p.view = view; - try p.children(root, .identity, .{}); - return p.b.finish(view, width, height); + return .{ .view = view, .width = width, .height = height }; } // --------------------------------------------------------------------------- @@ -183,7 +187,7 @@ const Parser = struct { fn element(p: *Parser, index: u32, parent_transform: Affine, parent: Inherited) Error!void { const n = p.doc.nodes.items[index]; const name = n.name; - const skip = [_][]const u8{ "defs", "symbol", "linearGradient", "radialGradient", "clipPath", "mask", "pattern", "marker", "style", "title", "desc", "metadata", "filter", "text", "image", "foreignObject" }; + const skip = [_][]const u8{ "defs", "symbol", "linearGradient", "radialGradient", "clipPath", "mask", "pattern", "marker", "style", "title", "desc", "metadata", "filter", "text", "foreignObject" }; for (skip) |s| if (std.mem.eql(u8, name, s)) return; if (p.depth > 64) return; var inherited = parent; @@ -229,6 +233,52 @@ const Parser = struct { } return p.element(target, transform, inherited); } + if (std.mem.eql(u8, name, "image")) { + // An SVG as a base64 data URI, Typst's way to place an SVG or a + // PDF page: its document, mapped into the image's box. Raster + // images draw nothing. + const href = p.doc.attr(n, "href") orelse p.doc.attr(n, "xlink:href") orelse return; + const prefix = "data:image/svg+xml;base64,"; + if (!std.mem.startsWith(u8, href, prefix)) return; + const decoder = std.base64.standard.Decoder; + const bytes = try p.arena.alloc(u8, decoder.calcSizeForSlice(href[prefix.len..]) catch return); + decoder.decode(bytes, href[prefix.len..]) catch return; + var doc = Document.parse(p.arena, bytes) catch |err| switch (err) { + error.OutOfMemory => return err, + error.InvalidSvg => return, + }; + const root = doc.root orelse return; + if (!std.mem.eql(u8, doc.nodes.items[root].name, "svg")) return; + const port = viewport(&doc, doc.nodes.items[root]); + const v = port.view; + const w = if (p.doc.attr(n, "width")) |a| lengthPx(a, p.view.w) else port.width; + const h = if (p.doc.attr(n, "height")) |a| lengthPx(a, p.view.h) else port.height; + if (v.w <= 0 or v.h <= 0 or w <= 0 or h <= 0) return; + transform = transform.mul(.translate(p.number(n, "x"), p.number(n, "y"))); + // Stretched with `preserveAspectRatio="none"`, else centered at + // the largest scale that fits; drawn unclipped. + if (std.mem.startsWith(u8, std.mem.trim(u8, p.doc.attr(n, "preserveAspectRatio") orelse "", " "), "none")) { + transform = transform.mul(.scale(w / v.w, h / v.h)); + } else { + const s = @min(w / v.w, h / v.h); + transform = transform.mul(.translate((w - v.w * s) / 2, (h - v.h * s) / 2)).mul(.scale(s, s)); + } + transform = transform.mul(.translate(-v.x, -v.y)); + // A document of its own: its ids, gradients and percentages, and + // nothing inherited but opacity. + const outer = p.*; + defer { + p.doc = outer.doc; + p.view = outer.view; + p.gradients = outer.gradients; + } + p.doc = &doc; + p.view = v; + p.gradients = .empty; + p.depth += 1; + defer p.depth -= 1; + return p.children(root, transform, .{ .style = .{ .opacity = inherited.style.opacity } }); + } const b = &p.b; if (std.mem.eql(u8, name, "path")) { @@ -766,3 +816,23 @@ test "colors and lengths" { try std.testing.expectEqual(@as(f32, 20), parseLength("15pt")); try std.testing.expectEqual(@as(f32, 0.5), parseOpacity("50%")); } + +test "an SVG image in a data URI: its own ids, placed, stretched or fitted" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + // + const inner = "data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAgMjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PHBhdGggaWQ9InAiIGQ9Ik0wIDBoMTB2MjBoLTEweiIvPjwvZGVmcz48dXNlIGhyZWY9IiNwIiBmaWxsPSIjMDBmZjAwIi8+PC9zdmc+"; + const d = try parse(arena.allocator(), "" ++ + "" ++ + "" ++ + ""); + try std.testing.expectEqual(@as(usize, 2), d.shapes.len); + for (d.shapes) |shape| try std.testing.expectEqual(Drawing.Color{ 0, 1, 0, 1 }, shape.style.fill.color); + // The far corner (10, 20) of the image's own path: stretched to the + // box's corner, or fitted into its middle. + for (d.shapes, [_]geom.Vec{ .{ 25, 25 }, .{ 20, 25 } }) |shape, corner| { + const far = d.cubicsOf(d.subpathsOf(shape)[0])[1][3]; + try std.testing.expectEqual(geom.vec(10, 20), far); + try std.testing.expectEqual(corner, shape.transform.apply(far)); + } +} -- cgit v1.3