diff options
Diffstat (limited to 'src/vector/svg.zig')
| -rw-r--r-- | src/vector/svg.zig | 96 |
1 files changed, 83 insertions, 13 deletions
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(); + // <svg viewBox="0 0 10 20"><defs><path id="p" d="M0 0h10v20h-10z"/></defs><use href="#p" fill="#00ff00"/></svg> + const inner = "data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAgMjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PHBhdGggaWQ9InAiIGQ9Ik0wIDBoMTB2MjBoLTEweiIvPjwvZGVmcz48dXNlIGhyZWY9IiNwIiBmaWxsPSIjMDBmZjAwIi8+PC9zdmc+"; + const d = try parse(arena.allocator(), "<svg viewBox=\"0 0 100 100\"><defs><path id=\"p\" d=\"M0 0h1v1z\"/></defs>" ++ + "<image x=\"5\" y=\"5\" width=\"20\" height=\"20\" preserveAspectRatio=\"none\" href=\"" ++ inner ++ "\"/>" ++ + "<image x=\"5\" y=\"5\" width=\"20\" height=\"20\" xlink:href=\"" ++ inner ++ "\"/>" ++ + "<image href=\"data:image/png;base64,AAAA\"/></svg>"); + 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)); + } +} |
