//! SVG to `Drawing`: the static subset that documents (Typst's output in //! particular) are made of. Structure: `svg`, `g`, `defs`, `symbol`, `use`. //! Shapes: `path` (every command, arcs included), `rect`, `circle`, //! `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`. //! //! Not supported: text (Typst outlines it), filters, masks, clipping, //! patterns, markers, 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"); const Vec = geom.Vec; const Affine = geom.Affine; pub const Error = error{ InvalidSvg, OutOfMemory }; /// Parses `source` into a drawing allocated with `arena`. pub fn parse(arena: std.mem.Allocator, source: []const u8) Error!Drawing { var doc = try Document.parse(arena, source); 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"); 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; 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); } // --------------------------------------------------------------------------- // A minimal XML reader: elements and attributes into flat arrays. const Attr = struct { name: []const u8, value: []const u8 }; const Node = struct { name: []const u8, attrs: []const Attr, first_child: ?u32 = null, next_sibling: ?u32 = null, }; const Document = struct { nodes: std.ArrayList(Node) = .empty, ids: std.StringHashMapUnmanaged(u32) = .empty, root: ?u32 = null, fn attr(doc: *const Document, n: Node, name: []const u8) ?[]const u8 { _ = doc; for (n.attrs) |a| if (std.mem.eql(u8, a.name, name)) return a.value; return null; } fn parse(arena: std.mem.Allocator, s: []const u8) Error!Document { var doc: Document = .{}; // Open elements, and the last child appended to each. var stack: std.ArrayList(struct { node: u32, last: ?u32 }) = .empty; var i: usize = 0; while (std.mem.indexOfScalarPos(u8, s, i, '<')) |lt| { i = lt + 1; if (std.mem.startsWith(u8, s[i..], "!--")) { i = (std.mem.indexOfPos(u8, s, i, "-->") orelse return error.InvalidSvg) + 3; } else if (std.mem.startsWith(u8, s[i..], "![CDATA[")) { i = (std.mem.indexOfPos(u8, s, i, "]]>") orelse return error.InvalidSvg) + 3; } else if (s.len > i and (s[i] == '?' or s[i] == '!')) { i = (std.mem.indexOfScalarPos(u8, s, i, '>') orelse return error.InvalidSvg) + 1; } else if (s.len > i and s[i] == '/') { i = (std.mem.indexOfScalarPos(u8, s, i, '>') orelse return error.InvalidSvg) + 1; _ = stack.pop() orelse return error.InvalidSvg; } else { const name_end = std.mem.indexOfAnyPos(u8, s, i, " \t\r\n/>") orelse return error.InvalidSvg; const name = localName(s[i..name_end]); i = name_end; var attrs: std.ArrayList(Attr) = .empty; var self_closing = false; while (true) { while (i < s.len and std.ascii.isWhitespace(s[i])) i += 1; if (i >= s.len) return error.InvalidSvg; if (s[i] == '>') { i += 1; break; } if (s[i] == '/') { self_closing = true; i = (std.mem.indexOfScalarPos(u8, s, i, '>') orelse return error.InvalidSvg) + 1; break; } const eq = std.mem.indexOfScalarPos(u8, s, i, '=') orelse return error.InvalidSvg; const attr_name = std.mem.trim(u8, s[i..eq], " \t\r\n"); var q = eq + 1; while (q < s.len and std.ascii.isWhitespace(s[q])) q += 1; if (q >= s.len or (s[q] != '"' and s[q] != '\'')) return error.InvalidSvg; const close = std.mem.indexOfScalarPos(u8, s, q + 1, s[q]) orelse return error.InvalidSvg; try attrs.append(arena, .{ .name = attr_name, .value = try entities(arena, s[q + 1 .. close]) }); i = close + 1; } const index: u32 = @intCast(doc.nodes.items.len); try doc.nodes.append(arena, .{ .name = name, .attrs = attrs.items }); for (attrs.items) |a| if (std.mem.eql(u8, a.name, "id")) try doc.ids.put(arena, a.value, index); if (stack.items.len == 0) { if (doc.root == null) doc.root = index; } else { const parent = &stack.items[stack.items.len - 1]; if (parent.last) |last| doc.nodes.items[last].next_sibling = index else doc.nodes.items[parent.node].first_child = index; parent.last = index; } if (!self_closing) try stack.append(arena, .{ .node = index, .last = null }); } } return doc; } }; /// `svg:path` and `path` are the same element to us. fn localName(qualified: []const u8) []const u8 { return if (std.mem.indexOfScalar(u8, qualified, ':')) |colon| qualified[colon + 1 ..] else qualified; } fn entities(arena: std.mem.Allocator, raw: []const u8) ![]const u8 { if (std.mem.indexOfScalar(u8, raw, '&') == null) return raw; var out: std.ArrayList(u8) = .empty; var i: usize = 0; while (i < raw.len) { if (raw[i] == '&') if (std.mem.indexOfScalarPos(u8, raw, i, ';')) |semi| { const name = raw[i + 1 .. semi]; const char: ?u21 = if (std.mem.eql(u8, name, "amp")) '&' else if (std.mem.eql(u8, name, "lt")) '<' else if (std.mem.eql(u8, name, "gt")) '>' else if (std.mem.eql(u8, name, "quot")) '"' else if (std.mem.eql(u8, name, "apos")) '\'' else if (name.len > 1 and name[0] == '#') (if (name[1] == 'x') std.fmt.parseInt(u21, name[2..], 16) catch null else std.fmt.parseInt(u21, name[1..], 10) catch null) else null; if (char) |ch| { var buf: [4]u8 = undefined; const len = std.unicode.utf8Encode(ch, &buf) catch 0; try out.appendSlice(arena, buf[0..len]); i = semi + 1; continue; } }; try out.append(arena, raw[i]); i += 1; } return out.items; } // --------------------------------------------------------------------------- // Tree walk: inherited style and transforms, shapes into the builder. const Parser = struct { doc: *Document, b: Drawing.Builder, arena: std.mem.Allocator, /// The root viewport, which `100%` lengths refer to. view: geom.Rect, /// Gradient ids already converted, by index in the builder. gradients: std.StringHashMapUnmanaged(u32) = .empty, /// Guards against `use` cycles. depth: u32 = 0, const Inherited = struct { style: Drawing.Style = .{}, color: Drawing.Color = .{ 0, 0, 0, 1 }, /// The innermost viewport clip, in the drawing's user space. clip: ?[4]Vec = null, }; fn children(p: *Parser, index: u32, transform: Affine, inherited: Inherited) Error!void { var child = p.doc.nodes.items[index].first_child; while (child) |c| : (child = p.doc.nodes.items[c].next_sibling) try p.element(c, transform, inherited); } 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" }; for (skip) |s| if (std.mem.eql(u8, name, s)) return; if (p.depth > 64) return; var inherited = parent; try p.applyStyle(n, &inherited); if (std.mem.eql(u8, p.doc.attr(n, "display") orelse "", "none")) return; var transform = parent_transform; if (p.doc.attr(n, "transform")) |t| transform = transform.mul(parseTransform(t)); if (std.mem.eql(u8, name, "g") or std.mem.eql(u8, name, "svg") or std.mem.eql(u8, name, "a") or std.mem.eql(u8, name, "switch")) { if (std.mem.eql(u8, name, "svg")) transform = transform.mul(.translate(p.number(n, "x"), p.number(n, "y"))); return p.children(index, transform, inherited); } if (std.mem.eql(u8, name, "use")) { const href = p.doc.attr(n, "href") orelse p.doc.attr(n, "xlink:href") orelse return; if (href.len < 2 or href[0] != '#') return; const target = p.doc.ids.get(href[1..]) orelse return; transform = transform.mul(.translate(p.number(n, "x"), p.number(n, "y"))); p.depth += 1; defer p.depth -= 1; const t = p.doc.nodes.items[target]; if (std.mem.eql(u8, t.name, "symbol")) { var sym = inherited; try p.applyStyle(t, &sym); // A symbol is a new viewport: the use's size, or the whole // canvas; its viewBox maps into it, and it clips unless its // overflow is visible. const w = if (p.doc.attr(n, "width")) |v| lengthPx(v, p.view.w) else p.view.w; const h = if (p.doc.attr(n, "height")) |v| lengthPx(v, p.view.h) else p.view.h; const overflow = p.doc.attr(t, "overflow") orelse "hidden"; if (!std.mem.eql(u8, overflow, "visible") and !std.mem.eql(u8, overflow, "auto")) { sym.clip = .{ transform.apply(.{ 0, 0 }), transform.apply(.{ w, 0 }), transform.apply(.{ w, h }), transform.apply(.{ 0, h }) }; } var inner = transform; if (p.doc.attr(t, "viewBox")) |vb| { var nums = Numbers{ .text = vb }; const v: geom.Rect = .{ .x = nums.next() orelse 0, .y = nums.next() orelse 0, .w = nums.next() orelse 0, .h = nums.next() orelse 0 }; if (v.w > 0 and v.h > 0) { const s = @min(w / v.w, h / v.h); inner = inner.mul(.translate((w - v.w * s) / 2, (h - v.h * s) / 2)).mul(.scale(s, s)).mul(.translate(-v.x, -v.y)); } } return p.children(target, inner, sym); } return p.element(target, transform, inherited); } const b = &p.b; if (std.mem.eql(u8, name, "path")) { try pathData(b, p.arena, p.doc.attr(n, "d") orelse return); } else if (std.mem.eql(u8, name, "rect")) { const w = p.number(n, "width"); const h = p.number(n, "height"); if (w <= 0 or h <= 0) return; var rx = p.doc.attr(n, "rx"); var ry = p.doc.attr(n, "ry"); if (rx == null) rx = ry; if (ry == null) ry = rx; const r: geom.Rect = .{ .x = p.number(n, "x"), .y = p.number(n, "y"), .w = w, .h = h }; const rxv = @min(if (rx) |v| parseLength(v) else 0, w / 2); const ryv = @min(if (ry) |v| parseLength(v) else 0, h / 2); if (rxv > 0 and ryv > 0) { try b.roundedRect(r, rxv, ryv); try b.closeSubpath(true); } else try b.rect(r, 0); } else if (std.mem.eql(u8, name, "circle")) { const r = p.number(n, "r"); if (r <= 0) return; try b.ellipse(.{ p.number(n, "cx"), p.number(n, "cy") }, r, r); } else if (std.mem.eql(u8, name, "ellipse")) { const rx = p.number(n, "rx"); const ry = p.number(n, "ry"); if (rx <= 0 or ry <= 0) return; try b.ellipse(.{ p.number(n, "cx"), p.number(n, "cy") }, rx, ry); } else if (std.mem.eql(u8, name, "line")) { try b.lineTo(.{ p.number(n, "x1"), p.number(n, "y1") }, .{ p.number(n, "x2"), p.number(n, "y2") }); try b.closeSubpath(false); } else if (std.mem.eql(u8, name, "polyline") or std.mem.eql(u8, name, "polygon")) { var points: std.ArrayList(Vec) = .empty; var nums = Numbers{ .text = p.doc.attr(n, "points") orelse return }; while (nums.next()) |x| try points.append(p.arena, .{ x, nums.next() orelse break }); try b.polyline(points.items, std.mem.eql(u8, name, "polygon")); } else return; const before = b.shapes.items.len; try b.endShape(transform, inherited.style); if (b.shapes.items.len > before) b.shapes.items[before].clip = inherited.clip; } fn number(p: *Parser, n: Node, name: []const u8) f32 { return parseLength(p.doc.attr(n, name) orelse return 0); } /// Presentation attributes, then `style="..."` declarations on top. fn applyStyle(p: *Parser, n: Node, inherited: *Inherited) Error!void { // `opacity` multiplies down the tree (see `property`). for (n.attrs) |a| try p.property(a.name, a.value, inherited); if (p.doc.attr(n, "style")) |css| { var decls = std.mem.tokenizeScalar(u8, css, ';'); while (decls.next()) |decl| { const colon = std.mem.indexOfScalar(u8, decl, ':') orelse continue; try p.property(std.mem.trim(u8, decl[0..colon], " \t\r\n"), std.mem.trim(u8, decl[colon + 1 ..], " \t\r\n"), inherited); } } } fn property(p: *Parser, name: []const u8, raw: []const u8, inherited: *Inherited) Error!void { const value = std.mem.trim(u8, raw, " \t\r\n"); const s = &inherited.style; const eql = std.mem.eql; if (eql(u8, value, "inherit")) return; if (eql(u8, name, "color")) { if (parseColor(value, inherited.color)) |c| inherited.color = c; } else if (eql(u8, name, "fill")) { s.fill = try p.paint(value, inherited.color) orelse s.fill; } else if (eql(u8, name, "stroke")) { s.stroke = try p.paint(value, inherited.color) orelse s.stroke; } else if (eql(u8, name, "fill-rule")) { s.fill_rule = if (eql(u8, value, "evenodd")) .evenodd else .nonzero; } else if (eql(u8, name, "fill-opacity")) { s.fill_opacity = parseOpacity(value); } else if (eql(u8, name, "stroke-opacity")) { s.stroke_opacity = parseOpacity(value); } else if (eql(u8, name, "opacity")) { s.opacity *= parseOpacity(value); } else if (eql(u8, name, "stroke-width")) { s.stroke_width = parseLength(value); } else if (eql(u8, name, "stroke-linecap")) { s.cap = std.meta.stringToEnum(Drawing.Cap, value) orelse s.cap; } else if (eql(u8, name, "stroke-linejoin")) { s.join = if (eql(u8, value, "miter-clip") or eql(u8, value, "arcs")) .miter else std.meta.stringToEnum(Drawing.Join, value) orelse s.join; } else if (eql(u8, name, "stroke-miterlimit")) { s.miter_limit = @max(1, parseLength(value)); } else if (eql(u8, name, "stroke-dasharray")) { s.dash_count = 0; if (!eql(u8, value, "none")) { var nums = Numbers{ .text = value }; var total: f32 = 0; while (nums.next()) |d| { if (s.dash_count == s.dashes.len or d < 0) break; s.dashes[s.dash_count] = d; s.dash_count += 1; total += d; } if (total <= 0) s.dash_count = 0; // An odd list repeats to make an even one. if (s.dash_count % 2 == 1 and s.dash_count * 2 <= s.dashes.len) { @memcpy(s.dashes[s.dash_count..][0..s.dash_count], s.dashes[0..s.dash_count]); s.dash_count *= 2; } } } else if (eql(u8, name, "stroke-dashoffset")) { s.dash_offset = parseLength(value); } } fn paint(p: *Parser, value: []const u8, current: Drawing.Color) Error!?Drawing.Paint { if (std.mem.eql(u8, value, "none")) return .none; if (std.mem.startsWith(u8, value, "url(")) { const close = std.mem.indexOfScalar(u8, value, ')') orelse return null; const ref = std.mem.trim(u8, value[4..close], " '\""); if (ref.len > 1 and ref[0] == '#') if (try p.gradient(ref[1..])) |g| return .{ .gradient = g }; // A missing paint server falls back to what follows it, or none. const fallback = std.mem.trim(u8, value[close + 1 ..], " "); return if (fallback.len > 0) try p.paint(fallback, current) else .none; } return if (parseColor(value, current)) |c| .{ .color = c } else null; } fn gradient(p: *Parser, id: []const u8) Error!?u32 { if (p.gradients.get(id)) |g| return g; const index = p.doc.ids.get(id) orelse return null; const n = p.doc.nodes.items[index]; const radial = std.mem.eql(u8, n.name, "radialGradient"); if (!radial and !std.mem.eql(u8, n.name, "linearGradient")) return null; var g: Drawing.Gradient = .{ .kind = if (radial) .radial else .linear }; if (radial) { g.p0 = .{ 0.5, 0.5 }; g.p1 = .{ 0.5, 0.5 }; } // Attributes and stops come from the first element in the href chain // that has them. var chain: [8]Node = undefined; var len: usize = 0; var at: ?u32 = index; while (at) |i| : (len += 1) { if (len == chain.len) break; chain[len] = p.doc.nodes.items[i]; const href = p.doc.attr(chain[len], "href") orelse p.doc.attr(chain[len], "xlink:href") orelse ""; at = if (href.len > 1 and href[0] == '#') p.doc.ids.get(href[1..]) else null; } const find = struct { fn find(doc: *Document, nodes: []const Node, name: []const u8) ?[]const u8 { for (nodes) |node| if (doc.attr(node, name)) |v| return v; return null; } }.find; const nodes = chain[0..len]; if (find(p.doc, nodes, "gradientUnits")) |u| g.bounding_box = !std.mem.eql(u8, u, "userSpaceOnUse"); if (find(p.doc, nodes, "gradientTransform")) |t| g.transform = parseTransform(t); if (find(p.doc, nodes, "spreadMethod")) |s| g.spread = if (std.mem.eql(u8, s, "reflect")) .reflect else if (std.mem.eql(u8, s, "repeat")) .repeat else .pad; const coord = struct { fn coord(doc: *Document, ns: []const Node, name: []const u8, default: f32, bbox: bool) f32 { const v = find(doc, ns, name) orelse return default; const t = std.mem.trim(u8, v, " "); if (bbox and t.len > 0 and t[t.len - 1] == '%') return (std.fmt.parseFloat(f32, t[0 .. t.len - 1]) catch 0) / 100; return parseLength(t); } }.coord; if (radial) { const cx = coord(p.doc, nodes, "cx", 0.5, g.bounding_box); const cy = coord(p.doc, nodes, "cy", 0.5, g.bounding_box); g.p0 = .{ cx, cy }; g.p1 = .{ coord(p.doc, nodes, "fx", cx, g.bounding_box), coord(p.doc, nodes, "fy", cy, g.bounding_box) }; g.radius = coord(p.doc, nodes, "r", 0.5, g.bounding_box); } else { g.p0 = .{ coord(p.doc, nodes, "x1", 0, g.bounding_box), coord(p.doc, nodes, "y1", 0, g.bounding_box) }; g.p1 = .{ coord(p.doc, nodes, "x2", 1, g.bounding_box), coord(p.doc, nodes, "y2", 0, g.bounding_box) }; } var stops: std.ArrayList(Drawing.Gradient.Stop) = .empty; for (nodes) |node| { var child = node.first_child; while (child) |c| : (child = p.doc.nodes.items[c].next_sibling) { const stop = p.doc.nodes.items[c]; if (!std.mem.eql(u8, stop.name, "stop")) continue; var color: Drawing.Color = .{ 0, 0, 0, 1 }; var opacity: f32 = 1; var offset: f32 = 0; const apply = struct { fn apply(name: []const u8, value: []const u8, col: *Drawing.Color, op: *f32, off: *f32) void { const v = std.mem.trim(u8, value, " "); if (std.mem.eql(u8, name, "stop-color")) { if (parseColor(v, .{ 0, 0, 0, 1 })) |parsed| col.* = parsed; } else if (std.mem.eql(u8, name, "stop-opacity")) { op.* = parseOpacity(v); } else if (std.mem.eql(u8, name, "offset")) { off.* = parseOpacity(v); } } }.apply; for (stop.attrs) |a| apply(a.name, a.value, &color, &opacity, &offset); if (p.doc.attr(stop, "style")) |css| { var decls = std.mem.tokenizeScalar(u8, css, ';'); while (decls.next()) |decl| { const colon = std.mem.indexOfScalar(u8, decl, ':') orelse continue; apply(std.mem.trim(u8, decl[0..colon], " "), decl[colon + 1 ..], &color, &opacity, &offset); } } color[3] *= opacity; // Offsets never go backwards. if (stops.items.len > 0) offset = @max(offset, stops.items[stops.items.len - 1].offset); try stops.append(p.arena, .{ .offset = std.math.clamp(offset, 0, 1), .color = color }); } if (stops.items.len > 0) break; } if (stops.items.len == 0) return null; g.stops = stops.items; const at_index: u32 = @intCast(p.b.gradients.items.len); try p.b.gradients.append(p.arena, g); try p.gradients.put(p.arena, id, at_index); return at_index; } }; // --------------------------------------------------------------------------- // Values /// Numbers separated by whitespace and/or commas, SVG style: "1-2" is two /// numbers, ".5.5" too. pub const Numbers = struct { text: []const u8, i: usize = 0, pub fn next(n: *Numbers) ?f32 { n.skip(); if (n.i >= n.text.len) return null; const start = n.i; var j = n.i; if (j < n.text.len and (n.text[j] == '+' or n.text[j] == '-')) j += 1; var dot = false; while (j < n.text.len) : (j += 1) { const ch = n.text[j]; if (std.ascii.isDigit(ch)) continue; if (ch == '.' and !dot) { dot = true; continue; } if ((ch == 'e' or ch == 'E') and j + 1 < n.text.len and (std.ascii.isDigit(n.text[j + 1]) or ((n.text[j + 1] == '-' or n.text[j + 1] == '+') and j + 2 < n.text.len and std.ascii.isDigit(n.text[j + 2])))) { j += 2; while (j < n.text.len and std.ascii.isDigit(n.text[j])) j += 1; break; } break; } if (j == start) return null; n.i = j; return std.fmt.parseFloat(f32, n.text[start..j]) catch null; } /// A single `0`/`1` arc flag, which may be glued to what follows. pub fn flag(n: *Numbers) ?bool { n.skip(); if (n.i >= n.text.len) return null; const ch = n.text[n.i]; if (ch != '0' and ch != '1') return null; n.i += 1; return ch == '1'; } fn skip(n: *Numbers) void { while (n.i < n.text.len and (std.ascii.isWhitespace(n.text[n.i]) or n.text[n.i] == ',')) n.i += 1; } }; /// A length in user units: unitless and px as-is, other absolute units /// converted at 96 dpi. Percentages and font units fall back to the number. pub fn parseLength(raw: []const u8) f32 { const v = std.mem.trim(u8, raw, " \t\r\n"); var nums = Numbers{ .text = v }; const n = nums.next() orelse return 0; const unit = std.mem.trim(u8, v[nums.i..], " "); const scale: f32 = if (std.mem.eql(u8, unit, "pt")) 4.0 / 3.0 else if (std.mem.eql(u8, unit, "pc")) 16 else if (std.mem.eql(u8, unit, "in")) 96 else if (std.mem.eql(u8, unit, "cm")) 96.0 / 2.54 else if (std.mem.eql(u8, unit, "mm")) 96.0 / 25.4 else if (std.mem.eql(u8, unit, "em")) 16 else 1; return n * scale; } /// Like `parseLength`, but a percentage of `reference`. fn lengthPx(raw: []const u8, reference: f32) f32 { const v = std.mem.trim(u8, raw, " "); if (v.len > 0 and v[v.len - 1] == '%') return (std.fmt.parseFloat(f32, v[0 .. v.len - 1]) catch 100) / 100 * reference; return parseLength(v); } fn parseOpacity(raw: []const u8) f32 { const v = std.mem.trim(u8, raw, " "); if (v.len > 0 and v[v.len - 1] == '%') return std.math.clamp((std.fmt.parseFloat(f32, v[0 .. v.len - 1]) catch 100) / 100, 0, 1); return std.math.clamp(std.fmt.parseFloat(f32, v) catch 1, 0, 1); } pub fn parseTransform(text: []const u8) Affine { var m: Affine = .identity; var i: usize = 0; while (std.mem.indexOfScalarPos(u8, text, i, '(')) |open| { const name = std.mem.trim(u8, text[i..open], " \t\r\n,"); const close = std.mem.indexOfScalarPos(u8, text, open, ')') orelse break; var nums = Numbers{ .text = text[open + 1 .. close] }; var v: [6]f32 = @splat(0); var count: usize = 0; while (nums.next()) |x| : (count += 1) { if (count == v.len) break; v[count] = x; } const deg = std.math.pi / 180.0; const t: Affine = if (std.mem.eql(u8, name, "matrix") and count == 6) .{ .a = v[0], .b = v[1], .c = v[2], .d = v[3], .e = v[4], .f = v[5] } else if (std.mem.eql(u8, name, "translate")) .translate(v[0], if (count > 1) v[1] else 0) else if (std.mem.eql(u8, name, "scale")) .scale(v[0], if (count > 1) v[1] else v[0]) else if (std.mem.eql(u8, name, "rotate")) Affine.translate(v[1], v[2]).mul(.rotate(v[0] * deg)).mul(.translate(-v[1], -v[2])) else if (std.mem.eql(u8, name, "skewX")) .skew(v[0] * deg, 0) else if (std.mem.eql(u8, name, "skewY")) .skew(0, v[0] * deg) else .identity; m = m.mul(t); i = close + 1; } return m; } /// `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()`/`rgba()` (numbers or /// percentages), `currentColor`, `transparent` and the common named colors. pub fn parseColor(raw: []const u8, current: Drawing.Color) ?Drawing.Color { const v = std.mem.trim(u8, raw, " \t\r\n"); if (v.len == 0) return null; if (v[0] == '#') { const hex = v[1..]; const digit = struct { fn d(ch: u8) ?f32 { return @floatFromInt(std.fmt.charToDigit(ch, 16) catch return null); } }.d; switch (hex.len) { 3, 4 => { var c: [4]f32 = .{ 0, 0, 0, 1 }; for (hex, 0..) |ch, i| c[i] = (digit(ch) orelse return null) * 17 / 255; return c; }, 6, 8 => { var c: [4]f32 = .{ 0, 0, 0, 1 }; for (0..hex.len / 2) |i| c[i] = ((digit(hex[2 * i]) orelse return null) * 16 + (digit(hex[2 * i + 1]) orelse return null)) / 255; return c; }, else => return null, } } if (std.ascii.startsWithIgnoreCase(v, "rgb")) { const open = std.mem.indexOfScalar(u8, v, '(') orelse return null; const close = std.mem.indexOfScalar(u8, v, ')') orelse return null; var parts = std.mem.tokenizeAny(u8, v[open + 1 .. close], ", /"); var c: [4]f32 = .{ 0, 0, 0, 1 }; var i: usize = 0; while (parts.next()) |part| : (i += 1) { if (i == 4) break; const pct = part[part.len - 1] == '%'; const n = std.fmt.parseFloat(f32, if (pct) part[0 .. part.len - 1] else part) catch return null; c[i] = std.math.clamp(if (i == 3) (if (pct) n / 100 else n) else if (pct) n / 100 else n / 255, 0, 1); } return c; } if (std.ascii.eqlIgnoreCase(v, "currentColor")) return current; if (std.ascii.eqlIgnoreCase(v, "transparent")) return .{ 0, 0, 0, 0 }; for (named) |entry| if (std.ascii.eqlIgnoreCase(v, entry[0])) { const rgb: u24 = entry[1]; return .{ @as(f32, @floatFromInt(rgb >> 16)) / 255, @as(f32, @floatFromInt((rgb >> 8) & 0xff)) / 255, @as(f32, @floatFromInt(rgb & 0xff)) / 255, 1 }; }; return null; } const named = [_]struct { []const u8, u24 }{ .{ "black", 0x000000 }, .{ "white", 0xffffff }, .{ "red", 0xff0000 }, .{ "lime", 0x00ff00 }, .{ "green", 0x008000 }, .{ "blue", 0x0000ff }, .{ "yellow", 0xffff00 }, .{ "cyan", 0x00ffff }, .{ "aqua", 0x00ffff }, .{ "magenta", 0xff00ff }, .{ "fuchsia", 0xff00ff }, .{ "gray", 0x808080 }, .{ "grey", 0x808080 }, .{ "silver", 0xc0c0c0 }, .{ "maroon", 0x800000 }, .{ "olive", 0x808000 }, .{ "navy", 0x000080 }, .{ "purple", 0x800080 }, .{ "teal", 0x008080 }, .{ "orange", 0xffa500 }, .{ "pink", 0xffc0cb }, .{ "brown", 0xa52a2a }, .{ "gold", 0xffd700 }, .{ "indigo", 0x4b0082 }, .{ "violet", 0xee82ee }, .{ "coral", 0xff7f50 }, .{ "salmon", 0xfa8072 }, .{ "tomato", 0xff6347 }, .{ "orchid", 0xda70d6 }, .{ "crimson", 0xdc143c }, .{ "skyblue", 0x87ceeb }, .{ "steelblue", 0x4682b4 }, .{ "darkgray", 0xa9a9a9 }, .{ "lightgray", 0xd3d3d3 }, .{ "darkgreen", 0x006400 }, .{ "darkblue", 0x00008b }, .{ "darkred", 0x8b0000 }, .{ "lightblue", 0xadd8e6 }, .{ "turquoise", 0x40e0d0 }, .{ "khaki", 0xf0e68c }, }; /// Path data into cubics: every command, absolute and relative, with /// implicit repeats and the smooth-curve reflections. pub fn pathData(b: *Drawing.Builder, gpa: std.mem.Allocator, d: []const u8) !void { var nums = Numbers{ .text = d }; var command: u8 = 0; var current: Vec = .{ 0, 0 }; var start: Vec = .{ 0, 0 }; // Last control point, for S and T reflections. var last_cubic: ?Vec = null; var last_quad: ?Vec = null; var arcs: std.ArrayList(geom.Cubic) = .empty; while (true) { nums.skip(); if (nums.i >= d.len) break; const ch = d[nums.i]; if (std.ascii.isAlphabetic(ch) and ch != 'e' and ch != 'E') { command = ch; nums.i += 1; if (ch == 'z' or ch == 'Z') { if (@reduce(.Or, current != start)) try b.lineTo(current, start); try b.closeSubpath(true); current = start; last_cubic = null; last_quad = null; continue; } } else if (command == 0) return; const rel = std.ascii.isLower(command); const base: Vec = if (rel) current else .{ 0, 0 }; const cubic_before = last_cubic; const quad_before = last_quad; last_cubic = null; last_quad = null; switch (std.ascii.toUpper(command)) { 'M' => { const p = base + Vec{ nums.next() orelse return, nums.next() orelse return }; try b.closeSubpath(false); current = p; start = p; // Further pairs are line-tos. command = if (rel) 'l' else 'L'; }, 'L' => { const p = base + Vec{ nums.next() orelse return, nums.next() orelse return }; try b.lineTo(current, p); current = p; }, 'H' => { const x = nums.next() orelse return; const p: Vec = .{ if (rel) current[0] + x else x, current[1] }; try b.lineTo(current, p); current = p; }, 'V' => { const y = nums.next() orelse return; const p: Vec = .{ current[0], if (rel) current[1] + y else y }; try b.lineTo(current, p); current = p; }, 'C' => { const c1 = base + Vec{ nums.next() orelse return, nums.next() orelse return }; const c2 = base + Vec{ nums.next() orelse return, nums.next() orelse return }; const p = base + Vec{ nums.next() orelse return, nums.next() orelse return }; try b.cubic(.{ current, c1, c2, p }); last_cubic = c2; current = p; }, 'S' => { const c1 = if (cubic_before) |c| current * geom.splat(2) - c else current; const c2 = base + Vec{ nums.next() orelse return, nums.next() orelse return }; const p = base + Vec{ nums.next() orelse return, nums.next() orelse return }; try b.cubic(.{ current, c1, c2, p }); last_cubic = c2; current = p; }, 'Q' => { const c = base + Vec{ nums.next() orelse return, nums.next() orelse return }; const p = base + Vec{ nums.next() orelse return, nums.next() orelse return }; try b.cubic(geom.quad(current, c, p)); last_quad = c; current = p; }, 'T' => { const c = if (quad_before) |q| current * geom.splat(2) - q else current; const p = base + Vec{ nums.next() orelse return, nums.next() orelse return }; try b.cubic(geom.quad(current, c, p)); last_quad = c; current = p; }, 'A' => { const rx = nums.next() orelse return; const ry = nums.next() orelse return; const rotation = nums.next() orelse return; const large = nums.flag() orelse return; const sweep = nums.flag() orelse return; const p = base + Vec{ nums.next() orelse return, nums.next() orelse return }; arcs.clearRetainingCapacity(); try geom.arc(&arcs, gpa, current, .{ rx, ry }, rotation, large, sweep, p); for (arcs.items) |c| try b.cubic(c); current = p; }, else => return, } } try b.closeSubpath(false); } test "typst-style use of symbols, transforms and inherited fill" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const d = try parse(arena.allocator(), \\ \\ \\ \\ ); try std.testing.expectEqual(@as(f32, 20), d.width); try std.testing.expectEqual(@as(usize, 1), d.shapes.len); const shape = d.shapes[0]; try std.testing.expectEqual(Drawing.FillRule.evenodd, shape.style.fill_rule); try std.testing.expectEqual(Drawing.Color{ 1, 0, 0, 1 }, shape.style.fill.color); try std.testing.expectEqual(@as(usize, 4), d.cubicsOf(d.subpathsOf(shape)[0]).len); const corner = shape.transform.apply(d.cubics[0][0]); try std.testing.expectEqual(geom.vec(6, 7), corner); } test "path data: implicit repeats, relative commands, smooth curves and arcs" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); var b: Drawing.Builder = .init(arena.allocator()); try pathData(&b, arena.allocator(), "M10-20l5 5 5-5h-1e1s1,2,3,4q1 1 2 0t2 0a5 5 0 1 0 10 0z"); try std.testing.expectEqual(@as(usize, 1), b.subpaths.items.len); try std.testing.expect(b.subpaths.items[0].closed); const cubics = b.cubics.items; try std.testing.expectEqual(geom.vec(15, -15), cubics[0][3]); try std.testing.expectEqual(geom.vec(20, -20), cubics[1][3]); try std.testing.expectEqual(geom.vec(10, -20), cubics[2][3]); // The first S has no previous curve: its first control is the current point. try std.testing.expectEqual(geom.vec(10, -20), cubics[3][1]); try std.testing.expectEqual(geom.vec(13, -16), cubics[3][3]); var nums = Numbers{ .text = "1.5.5-2e-1" }; try std.testing.expectEqual(@as(f32, 1.5), nums.next().?); try std.testing.expectEqual(@as(f32, 0.5), nums.next().?); try std.testing.expectEqual(@as(f32, -0.2), nums.next().?); } test "colors and lengths" { try std.testing.expectEqual(Drawing.Color{ 1, 1, 1, 1 }, parseColor("#fff", .{ 0, 0, 0, 1 }).?); try std.testing.expectEqual(Drawing.Color{ 0, 0.5, 1, 1 }, parseColor("rgb(0, 50%, 255)", .{ 0, 0, 0, 1 }).?); try std.testing.expectEqual(@as(f32, 20), parseLength("15pt")); try std.testing.expectEqual(@as(f32, 0.5), parseOpacity("50%")); }