feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
package svg
// namedColors are the colors CSS names, as 0xRRGGBB.
var namedColors = map[string]uint32{
"aliceblue": 0xf0f8ff, "antiquewhite": 0xfaebd7, "aqua": 0x00ffff, "aquamarine": 0x7fffd4,
"azure": 0xf0ffff, "beige": 0xf5f5dc, "bisque": 0xffe4c4, "black": 0x000000,
"blanchedalmond": 0xffebcd, "blue": 0x0000ff, "blueviolet": 0x8a2be2, "brown": 0xa52a2a,
"burlywood": 0xdeb887, "cadetblue": 0x5f9ea0, "chartreuse": 0x7fff00, "chocolate": 0xd2691e,
"coral": 0xff7f50, "cornflowerblue": 0x6495ed, "cornsilk": 0xfff8dc, "crimson": 0xdc143c,
"cyan": 0x00ffff, "darkblue": 0x00008b, "darkcyan": 0x008b8b, "darkgoldenrod": 0xb8860b,
"darkgray": 0xa9a9a9, "darkgreen": 0x006400, "darkgrey": 0xa9a9a9, "darkkhaki": 0xbdb76b,
"darkmagenta": 0x8b008b, "darkolivegreen": 0x556b2f, "darkorange": 0xff8c00, "darkorchid": 0x9932cc,
"darkred": 0x8b0000, "darksalmon": 0xe9967a, "darkseagreen": 0x8fbc8f, "darkslateblue": 0x483d8b,
"darkslategray": 0x2f4f4f, "darkslategrey": 0x2f4f4f, "darkturquoise": 0x00ced1, "darkviolet": 0x9400d3,
"deeppink": 0xff1493, "deepskyblue": 0x00bfff, "dimgray": 0x696969, "dimgrey": 0x696969,
"dodgerblue": 0x1e90ff, "firebrick": 0xb22222, "floralwhite": 0xfffaf0, "forestgreen": 0x228b22,
"fuchsia": 0xff00ff, "gainsboro": 0xdcdcdc, "ghostwhite": 0xf8f8ff, "gold": 0xffd700,
"goldenrod": 0xdaa520, "gray": 0x808080, "grey": 0x808080, "green": 0x008000,
"greenyellow": 0xadff2f, "honeydew": 0xf0fff0, "hotpink": 0xff69b4, "indianred": 0xcd5c5c,
"indigo": 0x4b0082, "ivory": 0xfffff0, "khaki": 0xf0e68c, "lavender": 0xe6e6fa,
"lavenderblush": 0xfff0f5, "lawngreen": 0x7cfc00, "lemonchiffon": 0xfffacd, "lightblue": 0xadd8e6,
"lightcoral": 0xf08080, "lightcyan": 0xe0ffff, "lightgoldenrodyellow": 0xfafad2, "lightgray": 0xd3d3d3,
"lightgreen": 0x90ee90, "lightgrey": 0xd3d3d3, "lightpink": 0xffb6c1, "lightsalmon": 0xffa07a,
"lightseagreen": 0x20b2aa, "lightskyblue": 0x87cefa, "lightslategray": 0x778899, "lightslategrey": 0x778899,
"lightsteelblue": 0xb0c4de, "lightyellow": 0xffffe0, "lime": 0x00ff00, "limegreen": 0x32cd32,
"linen": 0xfaf0e6, "magenta": 0xff00ff, "maroon": 0x800000, "mediumaquamarine": 0x66cdaa,
"mediumblue": 0x0000cd, "mediumorchid": 0xba55d3, "mediumpurple": 0x9370db, "mediumseagreen": 0x3cb371,
"mediumslateblue": 0x7b68ee, "mediumspringgreen": 0x00fa9a, "mediumturquoise": 0x48d1cc, "mediumvioletred": 0xc71585,
"midnightblue": 0x191970, "mintcream": 0xf5fffa, "mistyrose": 0xffe4e1, "moccasin": 0xffe4b5,
"navajowhite": 0xffdead, "navy": 0x000080, "oldlace": 0xfdf5e6, "olive": 0x808000,
"olivedrab": 0x6b8e23, "orange": 0xffa500, "orangered": 0xff4500, "orchid": 0xda70d6,
"palegoldenrod": 0xeee8aa, "palegreen": 0x98fb98, "paleturquoise": 0xafeeee, "palevioletred": 0xdb7093,
"papayawhip": 0xffefd5, "peachpuff": 0xffdab9, "peru": 0xcd853f, "pink": 0xffc0cb,
"plum": 0xdda0dd, "powderblue": 0xb0e0e6, "purple": 0x800080, "rebeccapurple": 0x663399,
"red": 0xff0000, "rosybrown": 0xbc8f8f, "royalblue": 0x4169e1, "saddlebrown": 0x8b4513,
"salmon": 0xfa8072, "sandybrown": 0xf4a460, "seagreen": 0x2e8b57, "seashell": 0xfff5ee,
"sienna": 0xa0522d, "silver": 0xc0c0c0, "skyblue": 0x87ceeb, "slateblue": 0x6a5acd,
"slategray": 0x708090, "slategrey": 0x708090, "snow": 0xfffafa, "springgreen": 0x00ff7f,
"steelblue": 0x4682b4, "tan": 0xd2b48c, "teal": 0x008080, "thistle": 0xd8bfd8,
"tomato": 0xff6347, "turquoise": 0x40e0d0, "violet": 0xee82ee, "wheat": 0xf5deb3,
"white": 0xffffff, "whitesmoke": 0xf5f5f5, "yellow": 0xffff00, "yellowgreen": 0x9acd32,
}
+725
View File
@@ -0,0 +1,725 @@
package svg
import (
"math"
"slices"
"strings"
)
// node is a drawing compiled from an element: a shape, or a group of
// nodes. m maps its user space to its parent's.
type node struct {
m matrix
opacity float64
clip *clipDef
mask *maskDef
shape *shape
text *textNode
kids []*node
// bbox is the box around its geometry in its user space, for what
// is in objectBoundingBox units.
bbox box
hasBox bool
// single is true when the node paints one thing at most, so that its
// opacity can apply to it instead of to a layer; flat is true when
// its parent's opacity can apply to it instead.
single, flat bool
}
// Kinds of paint.
const (
paintNone uint8 = iota
paintColor
paintCurrent // the color the document is drawn with
paintGradient
)
type paint struct {
kind uint8
color rgba
grad *gradient
}
type shape struct {
path path
fill, stroke paint
fillOpacity float64
strokeOpacity float64
evenOdd bool
width, miter float64
cap, join uint8
dashes []float64
dashOffset float64
strokeFirst bool
}
// Spread methods.
const (
spreadPad uint8 = iota
spreadReflect
spreadRepeat
)
type gradient struct {
radial bool
bbox bool // in objectBoundingBox units
m matrix // gradientTransform
spread uint8
// The line of a linear gradient, the circles of a radial one.
x1, y1, x2, y2 float64
cx, cy, r, fx, fy, fr float64
stops []stop
}
type stop struct {
offset float64
color rgba
current bool // the color the document is drawn with
opacity float64
}
// clipDef is a clipPath: the union of its shapes clips.
type clipDef struct {
bbox bool // clipPathUnits is objectBoundingBox
m matrix // its transform
kids []*node
clip *clipDef // its own clip-path
}
// maskDef is a mask: the luminance, or alpha, of its content masks, within
// its region.
type maskDef struct {
units, content bool // maskUnits and maskContentUnits are objectBoundingBox
region box
alpha bool
kids []*node
}
// compiler compiles a document's elements into nodes.
type compiler struct {
root *elem
ids map[string]*elem
styles map[*elem]*style
grads map[*elem]*gradient
clips map[*elem]*clipDef
masks map[*elem]*maskDef
// using holds the elements being drawn by use elements, which may not
// use themselves.
using []*elem
// budget is how many more nodes the document may compile to.
budget int
// vw and vh are the size of the viewport, for percentages.
vw, vh float64
base style
// current is set once a paint is currentColor.
current bool
// ctx is the shape whose markers are being compiled, which
// context-fill and context-stroke paint with.
ctx *shape
rep *report
// ext compiles text and markers, which are left out without it.
ext *extras
}
func newCompiler(root *elem, rep *report, ext *extras) *compiler {
c := &compiler{
root: root, ids: map[string]*elem{}, styles: map[*elem]*style{},
grads: map[*elem]*gradient{}, clips: map[*elem]*clipDef{}, masks: map[*elem]*maskDef{},
budget: 1 << 17, base: initialStyle(), rep: rep, ext: ext,
}
walk(root, func(e *elem) {
if id := e.attrs["id"]; id != "" {
if _, ok := c.ids[id]; !ok {
c.ids[id] = e
}
}
})
return c
}
func (c *compiler) diag() float64 { return math.Sqrt((c.vw*c.vw + c.vh*c.vh) / 2) }
// length parses the attribute name of e as a length, with def when it is
// missing or in error, percentages of base.
func (c *compiler) length(e *elem, name string, base, def float64) float64 {
if v, ok := e.attrs[name]; ok {
if l, ok := parseLength(v, base); ok {
return l
}
}
return def
}
func (c *compiler) style(e *elem, parent *style) style { return computeStyle(e, parent, c.vw, c.vh) }
// domStyle returns the style of e where the document has it: for the
// content of gradients, clip paths and masks, which inherit from where
// they are, not from what they paint.
func (c *compiler) domStyle(e *elem) *style {
if s, ok := c.styles[e]; ok {
return s
}
parent := &c.base
if e.parent != nil {
parent = c.domStyle(e.parent)
}
s := c.style(e, parent)
c.styles[e] = &s
return &s
}
// doc compiles the document.
func (c *compiler) doc() *Doc {
root := c.root
vb, hasVB := parseViewBox(root.attrs["viewBox"])
w, wok := absLength(root.attrs["width"])
h, hok := absLength(root.attrs["height"])
switch {
case wok && hok:
case hasVB && wok:
h = w * vb.h / vb.w
case hasVB && hok:
w = h * vb.w / vb.h
case hasVB:
w, h = vb.w, vb.h
default:
if !wok {
w = 300
}
if !hok {
h = 150
}
}
if !hasVB {
vb = box{0, 0, w, h}
}
c.vw, c.vh = vb.w, vb.h
d := &Doc{view: vb, par: parseAspect(root.attrs["preserveAspectRatio"]), w: math.Max(w, 0), h: math.Max(h, 0)}
st := c.style(root, &c.base)
if !st.display {
return d
}
n := &node{m: identity}
c.group(n, root, &st)
c.finish(n, &st)
d.root, d.current = n, c.current
return d
}
// absLength parses an absolute length, ignoring percentages.
func absLength(v string) (float64, bool) {
if strings.HasSuffix(strings.TrimSpace(v), "%") {
return 0, false
}
return parseLength(v, 0)
}
// group compiles the children of e into n.
func (c *compiler) group(n *node, e *elem, st *style) {
for _, k := range e.kids {
if kn := c.elem(k, st); kn != nil {
n.kids = append(n.kids, kn)
}
}
}
// finish gives a node its opacity, clipping and masking, and works out its
// box and whether it is single and flat.
func (c *compiler) finish(n *node, st *style) {
n.opacity = st.opacity
n.clip = c.clipRef(st.clipPath)
n.mask = c.maskRef(st.mask)
if s := n.shape; s != nil {
n.bbox, n.hasBox = s.path.bounds()
n.single = s.fill.kind == paintNone || s.stroke.kind == paintNone
} else if n.text != nil {
n.bbox, n.hasBox = n.text.estimate(), true
} else {
for _, k := range n.kids {
if !k.hasBox {
continue
}
b := k.bbox.transform(k.m)
if n.hasBox {
b = n.bbox.union(b)
}
n.bbox, n.hasBox = b, true
}
n.single = len(n.kids) == 0 || len(n.kids) == 1 && n.kids[0].flat
}
n.flat = n.clip != nil || n.mask != nil || n.single
}
// elem compiles a graphics element, or returns nil for others.
func (c *compiler) elem(e *elem, parent *style) *node {
switch e.name {
case "g", "a", "switch", "svg", "use", "text", "path", "rect", "circle", "ellipse", "line", "polyline", "polygon":
default:
return nil
}
if c.budget <= 0 {
return nil
}
c.budget--
st := c.style(e, parent)
if !st.display {
return nil
}
n := &node{m: identity}
switch e.name {
case "g", "a":
c.group(n, e, &st)
case "switch":
// The first child whose conditions hold, of which only
// requiredExtensions fails: MyGo supports no extension.
for _, k := range e.kids {
if k.attrs["requiredExtensions"] != "" || k.name == "title" || k.name == "desc" || k.name == "metadata" {
continue
}
if kn := c.elem(k, &st); kn != nil {
n.kids = append(n.kids, kn)
}
break
}
case "svg":
x, y := c.length(e, "x", c.vw, 0), c.length(e, "y", c.vh, 0)
w, h := c.length(e, "width", c.vw, c.vw), c.length(e, "height", c.vh, c.vh)
if w <= 0 || h <= 0 {
return nil
}
n.kids = c.viewport(e, &st, x, y, w, h)
case "use":
if !c.use(n, e, &st) {
return nil
}
case "text":
if c.ext == nil {
return nil
}
// Its runs may be visible where it is not.
if n.text = c.ext.text(c, e, &st); n.text == nil {
return nil
}
default:
if !st.visible {
return nil
}
pa := c.shapePath(e)
if len(pa.ops) == 0 {
return nil
}
n.shape = &shape{
path: pa, fill: c.paint(st.fill, &st), stroke: c.paint(st.stroke, &st),
fillOpacity: st.fillOpacity, strokeOpacity: st.strokeOpacity, evenOdd: st.fillEvenOdd,
width: st.strokeWidth, miter: st.miterLimit, cap: st.cap, join: st.join,
dashes: st.dashes, dashOffset: st.dashOffset, strokeFirst: st.strokeFirst,
}
if c.ext == nil {
break
}
if ms := c.ext.markers(c, e, &pa, &st, n.shape); len(ms) > 0 {
// The shape, then its markers over it.
body := &node{m: identity, shape: n.shape}
c.finish(body, &c.base)
n.shape, n.kids = nil, append([]*node{body}, ms...)
if t, ok := e.attrs["transform"]; ok {
n.m = parseTransform(t)
}
c.finish(n, &st)
// What is in its objectBoundingBox units spans the shape
// alone.
n.bbox, n.hasBox = body.bbox, body.hasBox
return n
}
}
if n.shape == nil && n.text == nil && len(n.kids) == 0 {
return nil
}
if t, ok := e.attrs["transform"]; ok {
n.m = parseTransform(t).mul(n.m)
}
c.finish(n, &st)
return n
}
// viewport compiles the children of an svg or symbol element e drawn in a
// viewport w×h at (x, y), which clips them.
func (c *compiler) viewport(e *elem, st *style, x, y, w, h float64) []*node {
vw, vh := c.vw, c.vh
defer func() { c.vw, c.vh = vw, vh }()
inner := &node{m: identity}
if vb, ok := parseViewBox(e.attrs["viewBox"]); ok {
inner.m = viewBoxTransform(vb, parseAspect(e.attrs["preserveAspectRatio"]), w, h)
c.vw, c.vh = vb.w, vb.h
} else {
c.vw, c.vh = w, h
}
c.group(inner, e, st)
if len(inner.kids) == 0 {
return nil
}
c.finish(inner, &c.base)
var r path
r.rect(0, 0, w, h, 0, 0)
clipped := &node{m: translate(x, y), kids: []*node{inner}}
cs := c.base
c.finish(clipped, &cs)
clipped.clip = &clipDef{m: identity, kids: []*node{{m: identity, shape: &shape{path: r}}}}
clipped.flat = true
return []*node{clipped}
}
// use compiles the element a use element e draws into n.
func (c *compiler) use(n *node, e *elem, st *style) bool {
ref := c.ids[hrefID(e)]
if ref == nil || slices.Contains(c.using, ref) {
return false
}
for p := e; p != nil; p = p.parent {
if p == ref {
return false // it would draw itself
}
}
c.using = append(c.using, ref)
defer func() { c.using = c.using[:len(c.using)-1] }()
x, y := c.length(e, "x", c.vw, 0), c.length(e, "y", c.vh, 0)
if ref.name == "symbol" {
sst := c.style(ref, st)
if !sst.display {
return false
}
w, h := c.length(e, "width", c.vw, c.vw), c.length(e, "height", c.vh, c.vh)
if w <= 0 || h <= 0 {
return false
}
n.kids = c.viewport(ref, &sst, x, y, w, h)
return len(n.kids) > 0
}
kid := c.elem(ref, st)
if kid == nil {
return false
}
n.m = translate(x, y)
n.kids = []*node{kid}
return true
}
func hrefID(e *elem) string {
v := strings.TrimSpace(e.attrs["href"])
if !strings.HasPrefix(v, "#") {
return ""
}
return v[1:]
}
func isShape(name string) bool {
switch name {
case "path", "rect", "circle", "ellipse", "line", "polyline", "polygon":
return true
}
return false
}
// shapePath returns the path of a shape element.
func (c *compiler) shapePath(e *elem) path {
var pa path
vw, vh, diag := c.vw, c.vh, c.diag()
switch e.name {
case "path":
pa = parsePath(e.attrs["d"])
case "rect":
x, y := c.length(e, "x", vw, 0), c.length(e, "y", vh, 0)
w, h := c.length(e, "width", vw, 0), c.length(e, "height", vh, 0)
if w <= 0 || h <= 0 {
break
}
rx, ry := c.radii(e, vw, vh)
pa.rect(x, y, w, h, math.Min(rx, w/2), math.Min(ry, h/2))
case "circle":
if r := c.length(e, "r", diag, 0); r > 0 {
pa.ellipse(c.length(e, "cx", vw, 0), c.length(e, "cy", vh, 0), r, r)
}
case "ellipse":
if rx, ry := c.radii(e, vw, vh); rx > 0 && ry > 0 {
pa.ellipse(c.length(e, "cx", vw, 0), c.length(e, "cy", vh, 0), rx, ry)
}
case "line":
pa.moveTo(point{c.length(e, "x1", vw, 0), c.length(e, "y1", vh, 0)})
pa.lineTo(point{c.length(e, "x2", vw, 0), c.length(e, "y2", vh, 0)})
case "polyline", "polygon":
n := numbers(e.attrs["points"])
for i := 0; i+1 < len(n); i += 2 {
if i == 0 {
pa.moveTo(point{n[i], n[i+1]})
} else {
pa.lineTo(point{n[i], n[i+1]})
}
}
if e.name == "polygon" {
pa.close()
}
}
return pa
}
// radii returns the rx and ry of a rect or ellipse: one that is missing,
// or in error, is the other.
func (c *compiler) radii(e *elem, vw, vh float64) (float64, float64) {
rx, okX := parseLength(e.attrs["rx"], vw)
ry, okY := parseLength(e.attrs["ry"], vh)
okX, okY = okX && rx >= 0, okY && ry >= 0
switch {
case okX && !okY:
ry = rx
case okY && !okX:
rx = ry
case !okX && !okY:
rx, ry = 0, 0
}
return rx, ry
}
// paint resolves a fill or stroke of an element of style st.
func (c *compiler) paint(ps paintSpec, st *style) paint {
switch ps.kind {
case specColor:
return paint{kind: paintColor, color: ps.color}
case specCurrent:
if st.colorSet {
return paint{kind: paintColor, color: st.color}
}
c.current = true
return paint{kind: paintCurrent}
case specContextFill, specContextStroke:
if c.ctx == nil {
return paint{}
}
if ps.kind == specContextFill {
return c.ctx.fill
}
return c.ctx.stroke
case specURL:
if el := c.ids[ps.id]; el != nil && (el.name == "linearGradient" || el.name == "radialGradient") {
g := c.gradient(el)
if g == nil || len(g.stops) == 0 {
return paint{}
}
return paint{kind: paintGradient, grad: g}
}
if el := c.ids[ps.id]; el != nil {
c.rep.add("<" + el.name + ">") // a pattern, or a paint server MyGo does not know
}
// What the reference falls back to, or nothing.
return c.paint(paintSpec{kind: ps.fallback, color: ps.color}, st)
}
return paint{}
}
// gradient compiles a gradient element, with what it inherits from the
// gradients it refers to.
func (c *compiler) gradient(e *elem) *gradient {
if g, ok := c.grads[e]; ok {
return g
}
c.grads[e] = nil
chain := []*elem{e}
for cur := e; len(chain) < 32; {
ref := c.ids[hrefID(cur)]
if ref == nil || ref.name != "linearGradient" && ref.name != "radialGradient" || slices.Contains(chain, ref) {
break
}
chain = append(chain, ref)
cur = ref
}
g := &gradient{radial: e.name == "radialGradient", bbox: true, m: identity}
// attr finds an attribute along the chain; the coordinates come from
// gradients of the same kind only.
attr := func(name string, own bool) (string, bool) {
for _, el := range chain {
if own && el.name != e.name {
continue
}
if v, ok := el.attrs[name]; ok {
return v, true
}
}
return "", false
}
if v, ok := attr("gradientUnits", false); ok {
g.bbox = strings.TrimSpace(v) != "userSpaceOnUse"
}
if v, ok := attr("gradientTransform", false); ok {
g.m = parseTransform(v)
}
if v, ok := attr("spreadMethod", false); ok {
switch strings.TrimSpace(v) {
case "reflect":
g.spread = spreadReflect
case "repeat":
g.spread = spreadRepeat
}
}
coord := func(name, def string, base float64) float64 {
v, ok := attr(name, true)
if !ok {
v = def
}
if g.bbox {
base = 1
}
l, ok := parseLength(v, base)
if !ok {
l, _ = parseLength(def, base)
}
return l
}
diag := c.diag()
if g.radial {
g.cx, g.cy, g.r = coord("cx", "50%", c.vw), coord("cy", "50%", c.vh), coord("r", "50%", diag)
g.fx, g.fy = g.cx, g.cy
if _, ok := attr("fx", true); ok {
g.fx = coord("fx", "50%", c.vw)
}
if _, ok := attr("fy", true); ok {
g.fy = coord("fy", "50%", c.vh)
}
g.fr = coord("fr", "0%", diag)
// SVG 1.1 moves a focal point outside the circle onto it.
if d := math.Hypot(g.fx-g.cx, g.fy-g.cy); d > g.r*0.999 && d > 0 {
k := g.r * 0.999 / d
g.fx, g.fy = g.cx+(g.fx-g.cx)*k, g.cy+(g.fy-g.cy)*k
}
} else {
g.x1, g.y1 = coord("x1", "0%", c.vw), coord("y1", "0%", c.vh)
g.x2, g.y2 = coord("x2", "100%", c.vw), coord("y2", "0%", c.vh)
}
// The stops of the first gradient along the chain that has some.
for _, el := range chain {
if g.stops = c.stops(el); len(g.stops) > 0 {
break
}
}
c.grads[e] = g
return g
}
func (c *compiler) stops(e *elem) []stop {
var out []stop
last := 0.0
for _, k := range e.kids {
if k.name != "stop" {
continue
}
st := c.domStyle(k)
off := 0.0
if v, ok := k.attrs["offset"]; ok {
off = parseOpacity(strings.TrimSpace(v), 0)
}
off = math.Max(off, last)
last = off
s := stop{offset: off, color: st.stopColor.color, opacity: st.stopOpacity}
if st.stopColor.kind == specCurrent {
if st.colorSet {
s.color = st.color
} else {
s.current, c.current = true, true
}
}
out = append(out, s)
}
return out
}
// clipRef compiles the clipPath an element refers to, if it is one.
func (c *compiler) clipRef(id string) *clipDef {
el := c.ids[id]
if id == "" || el == nil || el.name != "clipPath" {
return nil
}
if cd, ok := c.clips[el]; ok {
return cd // nil while it is being compiled: it clips itself
}
c.clips[el] = nil
cd := &clipDef{m: parseTransform(el.attrs["transform"]), bbox: strings.TrimSpace(el.attrs["clipPathUnits"]) == "objectBoundingBox"}
st := c.domStyle(el)
for _, k := range el.kids {
if n := c.clipKid(k, st, 0); n != nil {
cd.kids = append(cd.kids, n)
}
}
cd.clip = c.clipRef(st.clipPath)
c.clips[el] = cd
return cd
}
// clipKid compiles a child of a clipPath: a shape, or a use of one. Only
// their geometry clips, filled with the clip-rule.
func (c *compiler) clipKid(k *elem, parent *style, depth int) *node {
if c.budget <= 0 || depth > 1 {
return nil
}
c.budget--
st := c.style(k, parent)
if !st.display || !st.visible {
return nil
}
n := &node{m: parseTransform(k.attrs["transform"])}
switch {
case k.name == "use":
ref := c.ids[hrefID(k)]
if ref == nil || !isShape(ref.name) {
return nil
}
kid := c.clipKid(ref, &st, depth+1)
if kid == nil {
return nil
}
n.m = n.m.mul(translate(c.length(k, "x", c.vw, 0), c.length(k, "y", c.vh, 0)))
n.kids = []*node{kid}
case isShape(k.name):
pa := c.shapePath(k)
if len(pa.ops) == 0 {
return nil
}
n.shape = &shape{path: pa, evenOdd: st.clipEvenOdd}
case k.name == "text":
c.rep.add("<text> in <clipPath>")
return nil
default:
return nil
}
return n
}
// maskRef compiles the mask an element refers to, if it is one.
func (c *compiler) maskRef(id string) *maskDef {
el := c.ids[id]
if id == "" || el == nil || el.name != "mask" {
return nil
}
if md, ok := c.masks[el]; ok {
return md
}
c.masks[el] = nil
md := &maskDef{
units: strings.TrimSpace(el.attrs["maskUnits"]) != "userSpaceOnUse",
content: strings.TrimSpace(el.attrs["maskContentUnits"]) == "objectBoundingBox",
}
bw, bh := c.vw, c.vh
if md.units {
bw, bh = 1, 1
}
md.region = box{
c.length(el, "x", bw, -0.1*bw), c.length(el, "y", bh, -0.1*bh),
c.length(el, "width", bw, 1.2*bw), c.length(el, "height", bh, 1.2*bh),
}
st := c.domStyle(el)
md.alpha = st.maskAlpha
for _, k := range el.kids {
if n := c.elem(k, st); n != nil {
md.kids = append(md.kids, n)
}
}
c.masks[el] = md
return md
}
+614
View File
@@ -0,0 +1,614 @@
package svg
import (
"slices"
"strings"
)
// maxRules bounds the rules of a document's style sheets.
const maxRules = 4096
// report collects what a document has that is not drawn, as Unsupported
// lists it.
type report struct{ items []string }
func (r *report) add(item string) {
if r != nil && !slices.Contains(r.items, item) && len(r.items) < 256 {
r.items = append(r.items, item)
}
}
// Media a rule applies in: the light color scheme, the dark one, or both.
const (
mediaLight uint8 = 1 << iota
mediaDark
mediaAll = mediaLight | mediaDark
)
// sheet is the rules of a document's style sheets.
type sheet struct {
rules []rule
// scheme is true when a rule depends on prefers-color-scheme.
scheme bool
}
// parseSheets parses the style sheets of a document.
func parseSheets(root *elem, rep *report) *sheet {
sh := &sheet{}
walk(root, func(e *elem) {
if t := e.attrs["type"]; e.name == "style" && (t == "" || t == "text/css") {
sh.parse(e.text, mediaAll, rep)
}
})
sh.rules = sh.rules[:min(len(sh.rules), maxRules)]
return sh
}
// cascade gives every element the declarations of its properties, and
// its custom properties, in the dark color scheme or the light one.
func cascade(root *elem, sh *sheet, dark bool, rep *report) {
want := mediaLight
if dark {
want = mediaDark
}
// Rules are filed under the id, first class or type of the element
// they select, so that an element is matched against the rules it
// may match only.
byID, byClass, byTag := map[string][]int{}, map[string][]int{}, map[string][]int{}
var anyElem []int
for i := range sh.rules {
r := &sh.rules[i]
if r.media&want == 0 {
continue
}
switch s := r.sel.subject(); {
case s.id != "":
byID[s.id] = append(byID[s.id], i)
case len(s.classes) > 0:
byClass[s.classes[0]] = append(byClass[s.classes[0]], i)
case s.tag != "":
byTag[s.tag] = append(byTag[s.tag], i)
default:
anyElem = append(anyElem, i)
}
}
var matched []int
var decls []decl
walk(root, func(e *elem) {
e.props = nil
e.vars = nil
if e.parent != nil {
e.vars = e.parent.vars
}
if e.name == "#text" {
return
}
// Attributes, the marker shorthand before the properties it sets.
decls = decls[:0]
if v, ok := e.attrs["marker"]; ok {
decls = append(decls, decl{"marker", strings.TrimSpace(v)})
}
for name, v := range e.attrs {
if properties[name] && name != "marker" {
decls = append(decls, decl{name, strings.TrimSpace(v)})
} else if unsupportedProps[name] {
reportProp(name, v, rep)
}
}
matched = matched[:0]
match := func(candidates []int) {
for _, i := range candidates {
if sh.rules[i].sel.match(e) {
matched = append(matched, i)
}
}
}
match(anyElem)
match(byTag[e.name])
if id := e.attrs["id"]; id != "" {
match(byID[id])
}
for _, c := range strings.Fields(e.attrs["class"]) {
match(byClass[c])
}
// By specificity, then in order.
slices.SortFunc(matched, func(a, b int) int {
if d := sh.rules[a].sel.spec - sh.rules[b].sel.spec; d != 0 {
return d
}
return a - b
})
for _, i := range slices.Compact(matched) {
decls = append(decls, sh.rules[i].decls...)
}
if s, ok := e.attrs["style"]; ok {
decls = append(decls, parseDecls(s, rep)...)
}
e.vars = customProps(e.vars, decls)
for _, d := range decls {
if strings.HasPrefix(d.name, "--") {
continue
}
if strings.Contains(d.value, "var(") {
v, ok := substitute(d.value, e.vars, 0)
if !ok {
// Invalid at computed-value time: as if unset.
v = "unset"
}
d.value = strings.TrimSpace(v)
}
e.props = append(e.props, d)
}
})
}
// customProps returns the custom properties of an element that inherits
// inherited and declares those of decls.
func customProps(inherited map[string]string, decls []decl) map[string]string {
var own map[string]string
for _, d := range decls {
if strings.HasPrefix(d.name, "--") {
if own == nil {
own = map[string]string{}
}
own[d.name] = d.value
}
}
if own == nil {
return inherited
}
raw := make(map[string]string, len(inherited)+len(own))
for k, v := range inherited {
raw[k] = v
}
for k, v := range own {
raw[k] = v
}
// The element's own values may refer to each other: each is
// substituted in full, and one that cannot be is left out, as CSS's
// guaranteed-invalid value.
vars := make(map[string]string, len(raw))
for k, v := range raw {
if _, mine := own[k]; !mine {
vars[k] = v
continue
}
if s, ok := substitute(v, raw, 0); ok {
vars[k] = s
}
}
return vars
}
// Limits on substituting custom properties: how deep var() functions
// nest, and how long a value they make may grow.
const (
maxVarDepth = 32
maxVarLen = 1 << 14
)
// substitute replaces the var() functions of v with the custom
// properties of vars, or their fallbacks: ok is false when one names a
// property that is not there and has no fallback.
func substitute(v string, vars map[string]string, depth int) (string, bool) {
if depth > maxVarDepth {
return "", false
}
var b strings.Builder
for {
i := strings.Index(v, "var(")
if i < 0 {
b.WriteString(v)
break
}
b.WriteString(v[:i])
end := closeParen(v, i+3)
if end < 0 {
return "", false
}
args := v[i+4 : end]
name, fallback, hasFallback := strings.Cut(args, ",")
name = strings.TrimSpace(name)
var sub string
ok := false
if val, found := vars[name]; found {
sub, ok = substitute(val, vars, depth+1)
}
if !ok && hasFallback {
sub, ok = substitute(strings.TrimSpace(fallback), vars, depth+1)
}
if !ok {
return "", false
}
b.WriteString(sub)
if b.Len() > maxVarLen {
return "", false
}
v = v[end+1:]
}
return b.String(), true
}
// closeParen returns the index of the parenthesis closing the one at
// s[open], or -1.
func closeParen(s string, open int) int {
depth := 0
for i := open; i < len(s); i++ {
switch s[i] {
case '(':
depth++
case ')':
if depth--; depth == 0 {
return i
}
}
}
return -1
}
// rule is a rule of a style sheet with a single selector, which applies
// in media.
type rule struct {
sel selector
decls []decl
media uint8
}
// compound is a compound selector: a type, an id, classes and :root, any
// of which may be missing.
type compound struct {
tag string
id string
classes []string
root bool
}
// selector is compound selectors joined by descendant and child
// combinators. Style sheets with other combinators, pseudo-classes but
// :root or attribute selectors are not matched.
type selector struct {
parts []compound // the subject last
// child[i] is true when parts[i+1] is a child of parts[i], rather
// than a descendant.
child []bool
spec int // specificity
}
func (s *selector) subject() *compound { return &s.parts[len(s.parts)-1] }
func (c *compound) match(e *elem) bool {
if c.tag != "" && c.tag != e.name || c.id != "" && e.attrs["id"] != c.id || c.root && e.parent != nil {
return false
}
if len(c.classes) > 0 {
have := strings.Fields(e.attrs["class"])
for _, cl := range c.classes {
if !slices.Contains(have, cl) {
return false
}
}
}
return true
}
func (s *selector) match(e *elem) bool {
n := len(s.parts) - 1
return s.parts[n].match(e) && s.matchFrom(n, e)
}
// matchFrom reports whether the parts before i match the ancestors of e,
// which parts[i] matches.
func (s *selector) matchFrom(i int, e *elem) bool {
if i == 0 {
return true
}
for p := e.parent; p != nil; p = p.parent {
if s.parts[i-1].match(p) && s.matchFrom(i-1, p) {
return true
}
if s.child[i-1] {
break
}
}
return false
}
// parse adds the rules of a style sheet, in media.
func (sh *sheet) parse(s string, media uint8, rep *report) {
for {
s = strings.TrimSpace(s)
switch {
case s == "":
return
case strings.HasPrefix(s, "/*"):
end := strings.Index(s[2:], "*/")
if end < 0 {
return
}
s = s[end+4:]
continue
case strings.HasPrefix(s, "<!--"):
s = s[4:]
continue
case strings.HasPrefix(s, "-->"):
s = s[3:]
continue
case s[0] == '@':
// An at-rule ends at a semicolon or with its block.
i := strings.IndexAny(s, ";{")
if i < 0 {
return
}
name := strings.ToLower(s[1:nameEnd(s, 1)])
if s[i] == ';' {
if name == "import" {
rep.add("@import")
}
s = s[i+1:]
continue
}
end := blockEnd(s, i)
switch name {
case "media":
if m := sh.media(stripComments(s[len("@media"):i]), rep); m&media != 0 {
sh.parse(strings.TrimSuffix(s[i+1:end], "}"), m&media, rep)
}
case "font-face", "keyframes", "supports", "layer", "container", "property":
rep.add("@" + name)
}
s = s[end:]
continue
}
open := strings.IndexByte(s, '{')
if open < 0 {
return
}
end := blockEnd(s, open)
body := strings.TrimSuffix(s[open+1:end], "}")
decls := parseDecls(stripComments(body), rep)
for _, part := range strings.Split(stripComments(s[:open]), ",") {
part = strings.TrimSpace(part)
if sel, ok := parseSelector(part); ok {
sh.rules = append(sh.rules, rule{sel, decls, media})
} else if part != "" && !dynamic(part) {
rep.add("selector " + part)
}
}
s = s[end:]
}
}
// media evaluates a media query list: the media of mediaAll in which it
// is true. Media types but all and screen, and features but
// prefers-color-scheme, are false.
func (sh *sheet) media(q string, rep *report) uint8 {
var out uint8
for _, query := range strings.Split(q, ",") {
m := mediaAll
f := strings.Fields(strings.ToLower(strings.ReplaceAll(strings.ReplaceAll(query, "(", " ( "), ")", " ) ")))
not := len(f) > 0 && f[0] == "not"
if len(f) > 0 && (f[0] == "not" || f[0] == "only") {
f = f[1:]
}
for i := 0; i < len(f); i++ {
switch t := f[i]; t {
case "and":
case "all", "screen":
case "(":
end := slices.Index(f[i:], ")")
if end < 0 {
return 0
}
feature := strings.Join(f[i+1:i+end], "")
i += end
switch feature {
case "prefers-color-scheme:dark":
m &= mediaDark
sh.scheme = true
case "prefers-color-scheme:light":
m &= mediaLight
sh.scheme = true
default:
rep.add("@media (" + strings.Join(f[i-end+1:i], " ") + ")")
m = 0
}
default:
m = 0 // print, and media types MyGo does not know
}
}
if not {
m = mediaAll &^ m
}
out |= m
}
return out
}
// dynamic reports whether a selector selects by a state that a picture
// does not have, as :hover, which leaving out draws right.
func dynamic(sel string) bool {
for _, p := range []string{":hover", ":active", ":focus", ":visited", ":target"} {
if strings.Contains(sel, p) {
return true
}
}
return false
}
// blockEnd returns the index after the block opening at s[open].
func blockEnd(s string, open int) int {
depth := 0
for i := open; i < len(s); i++ {
switch s[i] {
case '{':
depth++
case '}':
if depth--; depth == 0 {
return i + 1
}
}
}
return len(s)
}
func stripComments(s string) string {
for {
i := strings.Index(s, "/*")
if i < 0 {
return s
}
j := strings.Index(s[i+2:], "*/")
if j < 0 {
return s[:i]
}
s = s[:i] + " " + s[i+2+j+2:]
}
}
func isNameChar(c byte) bool {
return c == '-' || c == '_' || c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= 0x80
}
func nameEnd(s string, i int) int {
for i < len(s) && isNameChar(s[i]) {
i++
}
return i
}
// parseSelector parses compound selectors joined by white space and >.
func parseSelector(s string) (selector, bool) {
var sel selector
s = strings.ReplaceAll(s, ">", " > ")
child := false
for _, f := range strings.Fields(s) {
if f == ">" {
if len(sel.parts) == 0 || child {
return selector{}, false
}
child = true
continue
}
c, spec, ok := parseCompound(f)
if !ok {
return selector{}, false
}
if len(sel.parts) > 0 {
sel.child = append(sel.child, child)
}
child = false
sel.parts = append(sel.parts, c)
sel.spec += spec
}
if len(sel.parts) == 0 || child {
return selector{}, false
}
return sel, true
}
// parseCompound parses a compound selector, and returns its specificity.
func parseCompound(s string) (compound, int, bool) {
var c compound
spec := 0
i := 0
if s[0] == '*' {
i = 1
} else if isNameChar(s[0]) {
i = nameEnd(s, 0)
c.tag = s[:i]
spec++
}
for i < len(s) {
ch := s[i]
j := nameEnd(s, i+1)
if j == i+1 {
return compound{}, 0, false
}
switch ch {
case '.':
c.classes = append(c.classes, s[i+1:j])
spec += 100
case '#':
c.id = s[i+1 : j]
spec += 10000
case ':':
if strings.ToLower(s[i+1:j]) != "root" {
return compound{}, 0, false
}
c.root = true
spec += 100
default:
return compound{}, 0, false
}
i = j
}
return c, spec, true
}
// parseDecls parses declarations, such as those of a style attribute: of
// the properties MyGo draws, and custom ones.
func parseDecls(s string, rep *report) []decl {
var out []decl
for _, part := range splitDecls(s) {
name, value, ok := strings.Cut(part, ":")
if !ok {
continue
}
name = strings.TrimSpace(name)
value = strings.TrimSpace(value)
if i := strings.Index(strings.ToLower(value), "!important"); i >= 0 {
value = strings.TrimSpace(value[:i])
}
if strings.HasPrefix(name, "--") {
out = append(out, decl{name, value})
continue
}
name = strings.ToLower(name)
switch {
case properties[name] && value != "":
out = append(out, decl{name, value})
case unsupportedProps[name] || name == "transform":
reportProp(name, value, rep)
}
}
return out
}
// splitDecls splits declarations at the semicolons outside parentheses,
// which data URLs have in them.
func splitDecls(s string) []string {
var out []string
depth, start := 0, 0
for i := range len(s) {
switch s[i] {
case '(':
depth++
case ')':
depth = max(depth-1, 0)
case ';':
if depth == 0 {
out = append(out, s[start:i])
start = i + 1
}
}
}
return append(out, s[start:])
}
// unsupportedProps are the properties that change what a document looks
// like that MyGo does not draw.
var unsupportedProps = map[string]bool{
"filter": true, "mix-blend-mode": true, "vector-effect": true,
"text-decoration": true, "word-spacing": true, "writing-mode": true, "baseline-shift": true,
"font-variant": true, "font-stretch": true, "textLength": true, "lengthAdjust": true,
}
// reportProp reports a property MyGo does not draw, unless its value is
// one that changes nothing.
func reportProp(name, value string, rep *report) {
switch strings.ToLower(strings.TrimSpace(value)) {
case "", "none", "normal", "auto", "0", "baseline", "horizontal-tb", "lr", "lr-tb", "initial", "inherit", "unset":
return
}
rep.add(name)
}
+173
View File
@@ -0,0 +1,173 @@
package svg
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"io"
"strings"
)
// Limits on what a document may hold.
const (
maxElems = 1 << 18
maxDepth = 256
)
// elem is an element of the document.
type elem struct {
name string
attrs map[string]string
kids []*elem
parent *elem
// text is the text of a style element, or of a run of characters of
// a text element, which is an elem named "#text".
text string
// props are the declarations of its properties, in the order they
// apply: attributes, style sheets, then the style attribute.
props []decl
// vars are the custom properties it has, its own and those it
// inherits, with the var() functions in them substituted.
vars map[string]string
}
type decl struct{ name, value string }
// parseXML parses the document's elements.
func parseXML(data []byte) (*elem, error) {
d := xml.NewDecoder(bytes.NewReader(data))
d.Strict = false
d.CharsetReader = charsetReader
var root *elem
var stack []*elem
count, skip := 0, 0
// inText counts the elements open in a text element, which keep the
// characters in them.
inText := 0
for {
tok, err := d.Token()
if err == io.EOF {
break
}
if err != nil {
return nil, fmt.Errorf("svg: %w", err)
}
switch t := tok.(type) {
case xml.StartElement:
if skip > 0 || len(stack) >= maxDepth {
skip++
continue
}
if count++; count > maxElems {
return nil, errors.New("svg: too many elements")
}
e := &elem{name: t.Name.Local, attrs: make(map[string]string, len(t.Attr))}
for _, a := range t.Attr {
// Namespaced attributes belong to editors, but for
// xlink:href, which href takes precedence over, and
// xml:space.
if a.Name.Space == "xml" || a.Name.Space == "http://www.w3.org/XML/1998/namespace" {
if a.Name.Local == "space" {
e.attrs["xml:space"] = a.Value
}
continue
}
if a.Name.Space != "" && a.Name.Local != "href" {
continue
}
if _, ok := e.attrs[a.Name.Local]; ok && a.Name.Space != "" {
continue
}
e.attrs[a.Name.Local] = a.Value
}
if n := len(stack); n > 0 {
e.parent = stack[n-1]
e.parent.kids = append(e.parent.kids, e)
} else {
root = e
}
stack = append(stack, e)
if inText > 0 || e.name == "text" {
inText++
}
case xml.EndElement:
if skip > 0 {
skip--
continue
}
if len(stack) > 0 {
stack = stack[:len(stack)-1]
}
if inText > 0 {
inText--
}
if len(stack) == 0 {
return finishDOM(root)
}
case xml.CharData:
n := len(stack)
switch {
case skip > 0 || n == 0:
case stack[n-1].name == "style":
stack[n-1].text += string(t)
case inText > 0:
if count++; count > maxElems {
return nil, errors.New("svg: too many elements")
}
p := stack[n-1]
p.kids = append(p.kids, &elem{name: "#text", text: string(t), parent: p})
}
}
}
return finishDOM(root)
}
func finishDOM(root *elem) (*elem, error) {
if root == nil || root.name != "svg" {
return nil, errors.New("svg: no svg element")
}
return root, nil
}
// charsetReader reads the single-byte encodings old editors declare; other
// encodings are read as UTF-8.
func charsetReader(label string, r io.Reader) (io.Reader, error) {
switch strings.ToLower(label) {
case "iso-8859-1", "latin1", "latin-1", "windows-1252", "cp1252":
data, err := io.ReadAll(r)
if err != nil {
return nil, err
}
var b strings.Builder
for _, c := range data {
b.WriteRune(rune(c))
}
return strings.NewReader(b.String()), nil
}
return r, nil
}
func walk(e *elem, fn func(*elem)) {
fn(e)
for _, k := range e.kids {
walk(k, fn)
}
}
// unsupportedElems are the elements whose drawing MyGo leaves out, of
// those that draw where they are. Patterns and filters draw where
// something refers to them: the compiler reports them there.
var unsupportedElems = map[string]bool{
"image": true, "foreignObject": true, "textPath": true, "video": true, "canvas": true, "iframe": true,
"animate": true, "animateMotion": true, "animateTransform": true, "animateColor": true, "set": true,
}
// reportElems reports the elements of a document MyGo does not draw.
func reportElems(root *elem, rep *report) {
walk(root, func(e *elem) {
if unsupportedElems[e.name] {
rep.add("<" + e.name + ">")
}
})
}
+797
View File
@@ -0,0 +1,797 @@
package svg
import (
"fmt"
"math"
"strconv"
)
type point struct{ x, y float64 }
// box is a rectangle in user units.
type box struct{ x, y, w, h float64 }
func (b box) union(o box) box {
x0, y0 := math.Min(b.x, o.x), math.Min(b.y, o.y)
x1, y1 := math.Max(b.x+b.w, o.x+o.w), math.Max(b.y+b.h, o.y+o.h)
return box{x0, y0, x1 - x0, y1 - y0}
}
// transform returns the box around b transformed by m.
func (b box) transform(m matrix) box {
out := box{}
for i, p := range [4]point{{b.x, b.y}, {b.x + b.w, b.y}, {b.x, b.y + b.h}, {b.x + b.w, b.y + b.h}} {
q := m.apply(p)
if i == 0 {
out = box{q.x, q.y, 0, 0}
} else {
out = out.union(box{q.x, q.y, 0, 0})
}
}
return out
}
// matrix is an affine transform: it maps (x, y) to (m[0]x + m[2]y + m[4],
// m[1]x + m[3]y + m[5]), as SVG's matrix(a, b, c, d, e, f) does.
type matrix [6]float64
var identity = matrix{1, 0, 0, 1, 0, 0}
// mul returns the transform that applies n, then m.
func (m matrix) mul(n matrix) matrix {
return matrix{
m[0]*n[0] + m[2]*n[1],
m[1]*n[0] + m[3]*n[1],
m[0]*n[2] + m[2]*n[3],
m[1]*n[2] + m[3]*n[3],
m[0]*n[4] + m[2]*n[5] + m[4],
m[1]*n[4] + m[3]*n[5] + m[5],
}
}
func (m matrix) apply(p point) point {
return point{m[0]*p.x + m[2]*p.y + m[4], m[1]*p.x + m[3]*p.y + m[5]}
}
// invert returns the inverse of m, or false when m flattens the plane.
func (m matrix) invert() (matrix, bool) {
d := m[0]*m[3] - m[1]*m[2]
if d == 0 || math.IsNaN(d) || math.IsInf(d, 0) {
return identity, false
}
return matrix{
m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
(m[2]*m[5] - m[3]*m[4]) / d,
(m[1]*m[4] - m[0]*m[5]) / d,
}, true
}
// stretch returns the most m lengthens a line: its largest singular value.
func (m matrix) stretch() float64 {
a, b, c, d := m[0], m[1], m[2], m[3]
e := a*a + b*b - c*c - d*d
f := a*c + b*d
return math.Sqrt((a*a + b*b + c*c + d*d + math.Sqrt(e*e+4*f*f)) / 2)
}
func translate(x, y float64) matrix { return matrix{1, 0, 0, 1, x, y} }
func scaling(x, y float64) matrix { return matrix{x, 0, 0, y, 0, 0} }
func rotation(deg float64) matrix {
s, c := math.Sincos(deg * math.Pi / 180)
return matrix{c, s, -s, c, 0, 0}
}
// boxMatrix maps the unit square to b, for objectBoundingBox units.
func boxMatrix(b box) matrix { return matrix{b.w, 0, 0, b.h, b.x, b.y} }
// parseTransform parses a transform list, such as "translate(10 20)
// rotate(45)". A list in error transforms nothing, as in browsers.
func parseTransform(s string) matrix {
m := identity
p := scanner{s: s}
for {
p.skipSep()
if p.done() {
return m
}
name := p.ident()
p.skipSpace()
if !p.eat('(') {
return identity
}
var a [6]float64
n := 0
for {
p.skipSep()
if p.eat(')') {
break
}
v, ok := p.number()
if !ok || n == len(a) {
return identity
}
a[n] = v
n++
}
var t matrix
switch {
case name == "matrix" && n == 6:
t = matrix(a)
case name == "translate" && (n == 1 || n == 2):
t = translate(a[0], a[1])
case name == "scale" && n == 1:
t = scaling(a[0], a[0])
case name == "scale" && n == 2:
t = scaling(a[0], a[1])
case name == "rotate" && n == 1:
t = rotation(a[0])
case name == "rotate" && n == 3:
t = translate(a[1], a[2]).mul(rotation(a[0])).mul(translate(-a[1], -a[2]))
case name == "skewX" && n == 1:
t = matrix{1, 0, math.Tan(a[0] * math.Pi / 180), 1, 0, 0}
case name == "skewY" && n == 1:
t = matrix{1, math.Tan(a[0] * math.Pi / 180), 0, 1, 0, 0}
default:
return identity
}
m = m.mul(t)
}
}
// scanner reads the numbers, names and separators of attribute values.
type scanner struct {
s string
i int
}
func (p *scanner) done() bool { return p.i >= len(p.s) }
func (p *scanner) peek() byte {
if p.i < len(p.s) {
return p.s[p.i]
}
return 0
}
func (p *scanner) eat(c byte) bool {
if p.i < len(p.s) && p.s[p.i] == c {
p.i++
return true
}
return false
}
func isSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' }
func (p *scanner) skipSpace() {
for p.i < len(p.s) && isSpace(p.s[p.i]) {
p.i++
}
}
// skipSep skips white space with at most one comma in it.
func (p *scanner) skipSep() {
p.skipSpace()
if p.eat(',') {
p.skipSpace()
}
}
// ident reads a name of letters, digits, hyphens and underscores.
func (p *scanner) ident() string {
start := p.i
for p.i < len(p.s) {
c := p.s[p.i]
if c == '-' || c == '_' || c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= 0x80 {
p.i++
continue
}
break
}
return p.s[start:p.i]
}
// number reads a finite number: an optional sign, digits with an optional
// fraction, and an optional exponent.
func (p *scanner) number() (float64, bool) {
s, start := p.s, p.i
i := start
if i < len(s) && (s[i] == '+' || s[i] == '-') {
i++
}
digits := 0
for i < len(s) && s[i] >= '0' && s[i] <= '9' {
i++
digits++
}
if i < len(s) && s[i] == '.' {
i++
for i < len(s) && s[i] >= '0' && s[i] <= '9' {
i++
digits++
}
}
if digits == 0 {
return 0, false
}
if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
// An exponent, unless the e starts a unit such as em.
j := i + 1
if j < len(s) && (s[j] == '+' || s[j] == '-') {
j++
}
if j < len(s) && s[j] >= '0' && s[j] <= '9' {
for j < len(s) && s[j] >= '0' && s[j] <= '9' {
j++
}
i = j
}
}
v, err := strconv.ParseFloat(s[start:i], 64)
if err != nil || math.IsInf(v, 0) {
return 0, false
}
p.i = i
return v, true
}
// numbers parses a list of numbers separated by white space or commas,
// up to the first that is not one.
func numbers(s string) []float64 {
var out []float64
p := scanner{s: s}
for {
p.skipSep()
v, ok := p.number()
if !ok {
return out
}
out = append(out, v)
}
}
// path is a path in user units. Its curves are cubic Bézier curves:
// quadratic curves and arcs are converted.
type path struct {
ops []pathOp
pts []point
// start is the first point of the subpath, cur the pen; open is false
// before the first move and after a close.
start, cur point
open bool
// arcs are the indices in ops of the curves that go on with an arc
// the curve before began, in order: no vertices for markers.
arcs []int
}
type pathOp uint8
const (
opMove pathOp = iota // a point
opLine // a point
opCubic // two control points and the end
opClose // no point
)
func (pa *path) moveTo(p point) {
pa.ops = append(pa.ops, opMove)
pa.pts = append(pa.pts, p)
pa.start, pa.cur, pa.open = p, p, true
}
// begin starts a subpath where the pen is, when drawing follows a close:
// the subpath after a close starts where the closed one did.
func (pa *path) begin() {
if !pa.open {
pa.moveTo(pa.cur)
}
}
func (pa *path) lineTo(p point) {
pa.begin()
pa.ops = append(pa.ops, opLine)
pa.pts = append(pa.pts, p)
pa.cur = p
}
func (pa *path) cubicTo(c1, c2, p point) {
pa.begin()
pa.ops = append(pa.ops, opCubic)
pa.pts = append(pa.pts, c1, c2, p)
pa.cur = p
}
// quadTo draws a quadratic curve, as the cubic curve it is.
func (pa *path) quadTo(c, p point) {
a := pa.cur
pa.cubicTo(point{a.x + 2.0/3*(c.x-a.x), a.y + 2.0/3*(c.y-a.y)}, point{p.x + 2.0/3*(c.x-p.x), p.y + 2.0/3*(c.y-p.y)}, p)
}
func (pa *path) close() {
if pa.open {
pa.ops = append(pa.ops, opClose)
pa.cur, pa.open = pa.start, false
}
}
// arcTo draws an elliptical arc to p as cubic curves, converting SVG's
// endpoint parameters as appendix F.6 of SVG 1.1 says.
func (pa *path) arcTo(rx, ry, rotation float64, large, sweep bool, p point) {
a := pa.cur
if a == p {
return
}
rx, ry = math.Abs(rx), math.Abs(ry)
if rx == 0 || ry == 0 {
pa.lineTo(p)
return
}
sin, cos := math.Sincos(rotation * math.Pi / 180)
// Half the chord, in the ellipse's axes.
hx, hy := (a.x-p.x)/2, (a.y-p.y)/2
x1 := cos*hx + sin*hy
y1 := -sin*hx + cos*hy
// Radii too small to reach p grow.
if l := x1*x1/(rx*rx) + y1*y1/(ry*ry); l > 1 {
l = math.Sqrt(l)
rx, ry = rx*l, ry*l
}
num := rx*rx*ry*ry - rx*rx*y1*y1 - ry*ry*x1*x1
den := rx*rx*y1*y1 + ry*ry*x1*x1
k := 0.0
if den > 0 {
k = math.Sqrt(math.Max(num/den, 0))
}
if large == sweep {
k = -k
}
cx1, cy1 := k*rx*y1/ry, -k*ry*x1/rx
cx := cos*cx1 - sin*cy1 + (a.x+p.x)/2
cy := sin*cx1 + cos*cy1 + (a.y+p.y)/2
ux, uy := (x1-cx1)/rx, (y1-cy1)/ry
vx, vy := (-x1-cx1)/rx, (-y1-cy1)/ry
theta := math.Atan2(uy, ux)
delta := math.Atan2(ux*vy-uy*vx, ux*vx+uy*vy)
if !sweep && delta > 0 {
delta -= 2 * math.Pi
} else if sweep && delta < 0 {
delta += 2 * math.Pi
}
// Quarter turns at most per curve.
n := max(int(math.Ceil(math.Abs(delta)/(math.Pi/2)-1e-7)), 1)
step := delta / float64(n)
t := 4.0 / 3 * math.Tan(step/4)
on := func(ex, ey float64) point {
x, y := ex*rx, ey*ry
return point{cos*x - sin*y + cx, sin*x + cos*y + cy}
}
for i := range n {
s1, c1 := math.Sincos(theta)
s2, c2 := math.Sincos(theta + step)
end := on(c2, s2)
if i == n-1 {
end = p
}
pa.cubicTo(on(c1-t*s1, s1+t*c1), on(c2+t*s2, s2-t*c2), end)
if i > 0 {
pa.arcs = append(pa.arcs, len(pa.ops)-1)
}
theta += step
}
}
// kappa places the control points of a quarter circle's cubic curve.
const kappa = 0.5522847498307936
func (pa *path) ellipse(cx, cy, rx, ry float64) {
kx, ky := rx*kappa, ry*kappa
pa.moveTo(point{cx + rx, cy})
pa.cubicTo(point{cx + rx, cy + ky}, point{cx + kx, cy + ry}, point{cx, cy + ry})
pa.cubicTo(point{cx - kx, cy + ry}, point{cx - rx, cy + ky}, point{cx - rx, cy})
pa.cubicTo(point{cx - rx, cy - ky}, point{cx - kx, cy - ry}, point{cx, cy - ry})
pa.cubicTo(point{cx + kx, cy - ry}, point{cx + rx, cy - ky}, point{cx + rx, cy})
pa.close()
}
// rect adds a rectangle with corners rounded rx by ry.
func (pa *path) rect(x, y, w, h, rx, ry float64) {
if rx <= 0 || ry <= 0 {
pa.moveTo(point{x, y})
pa.lineTo(point{x + w, y})
pa.lineTo(point{x + w, y + h})
pa.lineTo(point{x, y + h})
pa.close()
return
}
kx, ky := rx*kappa, ry*kappa
r, b := x+w, y+h
pa.moveTo(point{x + rx, y})
pa.lineTo(point{r - rx, y})
pa.cubicTo(point{r - rx + kx, y}, point{r, y + ry - ky}, point{r, y + ry})
pa.lineTo(point{r, b - ry})
pa.cubicTo(point{r, b - ry + ky}, point{r - rx + kx, b}, point{r - rx, b})
pa.lineTo(point{x + rx, b})
pa.cubicTo(point{x + rx - kx, b}, point{x, b - ry + ky}, point{x, b - ry})
pa.lineTo(point{x, y + ry})
pa.cubicTo(point{x, y + ry - ky}, point{x + rx - kx, y}, point{x + rx, y})
pa.close()
}
func isCommand(c byte) bool {
switch c {
case 'M', 'm', 'L', 'l', 'H', 'h', 'V', 'v', 'C', 'c', 'S', 's', 'Q', 'q', 'T', 't', 'A', 'a', 'Z', 'z':
return true
}
return false
}
// parsePath parses path data up to its first error, as SVG asks.
func parsePath(d string) path {
pa, _ := parsePathAt(d)
return pa
}
// PathOp is what a segment of path data ParsePath parsed does.
type PathOp = pathOp
// The segments of path data: a move to a point, a line to one, a cubic
// Bézier curve through two control points to its end, and a close.
const (
PathMove = opMove
PathLine = opLine
PathCubic = opCubic
PathClose = opClose
)
// ParsePath parses SVG path data, as a path element's d attribute holds
// it, into its segments, in user units: ops, each taking its points from
// pts in turn, a move and a line one, a cubic curve three, a close none;
// quadratic curves and arcs become cubic ones. At an error it stops, as
// SVG draws a path up to its first error, and returns the error, with the
// segments before it.
func ParsePath(d string) (ops []PathOp, pts [][2]float64, err error) {
pa, at := parsePathAt(d)
pts = make([][2]float64, len(pa.pts))
for i, p := range pa.pts {
pts[i] = [2]float64{p.x, p.y}
}
if at >= 0 {
if at < len(d) {
err = fmt.Errorf("svg: path data: unexpected %q at offset %d", d[at], at)
} else {
err = fmt.Errorf("svg: path data: unexpected end at offset %d", at)
}
}
return pa.ops, pts, err
}
// parsePathAt parses path data up to its first error, and returns where
// in d the error is, or -1 for none.
func parsePathAt(d string) (path, int) {
var pa path
p := scanner{s: d}
var cmd, last byte // the command, and the last one in upper case
var ctrl point // the last control point, for S and T
coord := func() (float64, bool) { p.skipSep(); return p.number() }
pt := func(base point) (point, bool) {
x, ok := coord()
if !ok {
return point{}, false
}
y, ok := coord()
return point{base.x + x, base.y + y}, ok
}
flag := func() (bool, bool) {
p.skipSep()
switch p.peek() {
case '0':
p.i++
return false, true
case '1':
p.i++
return true, true
}
return false, false
}
for {
p.skipSpace()
if p.done() {
return pa, -1
}
at := p.i
if c := p.peek(); isCommand(c) {
cmd = c
p.i++
} else if cmd == 0 || cmd == 'Z' || cmd == 'z' {
return pa, at // numbers without a command
}
if len(pa.ops) == 0 && cmd != 'M' && cmd != 'm' {
return pa, at // a path starts with a move
}
var base point
if cmd >= 'a' {
base = pa.cur
}
up := cmd &^ 0x20
ok := true
switch up {
case 'M':
var a point
if a, ok = pt(base); ok {
pa.moveTo(a)
// More coordinates are lines.
cmd = 'L' | cmd&0x20
}
case 'L':
var a point
if a, ok = pt(base); ok {
pa.lineTo(a)
}
case 'H':
var x float64
if x, ok = coord(); ok {
pa.lineTo(point{base.x + x, pa.cur.y})
}
case 'V':
var y float64
if y, ok = coord(); ok {
pa.lineTo(point{pa.cur.x, base.y + y})
}
case 'C', 'S':
c1 := pa.cur
if up == 'C' {
c1, ok = pt(base)
} else if last == 'C' || last == 'S' {
c1 = point{2*pa.cur.x - ctrl.x, 2*pa.cur.y - ctrl.y}
}
var c2, e point
if ok {
c2, ok = pt(base)
}
if ok {
e, ok = pt(base)
}
if ok {
pa.cubicTo(c1, c2, e)
ctrl = c2
}
case 'Q', 'T':
c := pa.cur
if up == 'Q' {
c, ok = pt(base)
} else if last == 'Q' || last == 'T' {
c = point{2*pa.cur.x - ctrl.x, 2*pa.cur.y - ctrl.y}
}
var e point
if ok {
e, ok = pt(base)
}
if ok {
pa.quadTo(c, e)
ctrl = c
}
case 'A':
var rx, ry, rot float64
var large, sweep bool
var e point
rx, ok = coord()
if ok {
ry, ok = coord()
}
if ok {
rot, ok = coord()
}
if ok {
large, ok = flag()
}
if ok {
sweep, ok = flag()
}
if ok {
e, ok = pt(base)
}
if ok {
pa.arcTo(rx, ry, rot, large, sweep, e)
}
case 'Z':
pa.close()
}
if !ok {
return pa, p.i
}
last = up
}
}
// bounds returns the box around the path's geometry, in user units.
func (pa *path) bounds() (box, bool) {
var b box
found := false
add := func(p point) {
if !found {
b, found = box{p.x, p.y, 0, 0}, true
return
}
b = b.union(box{p.x, p.y, 0, 0})
}
var cur point
i := 0
for _, op := range pa.ops {
switch op {
case opMove:
cur = pa.pts[i]
i++
case opLine:
add(cur)
cur = pa.pts[i]
add(cur)
i++
case opCubic:
c1, c2, e := pa.pts[i], pa.pts[i+1], pa.pts[i+2]
add(cur)
add(e)
for _, t := range extrema(cur.x, c1.x, c2.x, e.x) {
add(bezier(cur, c1, c2, e, t))
}
for _, t := range extrema(cur.y, c1.y, c2.y, e.y) {
add(bezier(cur, c1, c2, e, t))
}
cur = e
i += 3
}
}
return b, found
}
// extrema returns where in (0, 1) a cubic curve's coordinate turns.
func extrema(a, b, c, d float64) []float64 {
qa := -a + 3*b - 3*c + d
qb := 2 * (a - 2*b + c)
qc := b - a
var roots [2]float64
n := 0
if math.Abs(qa) < 1e-12 {
if qb != 0 {
roots[0] = -qc / qb
n = 1
}
} else if disc := qb*qb - 4*qa*qc; disc >= 0 {
s := math.Sqrt(disc)
roots[0], roots[1] = (-qb+s)/(2*qa), (-qb-s)/(2*qa)
n = 2
}
out := roots[:0]
for _, t := range roots[:n] {
if t > 0 && t < 1 {
out = append(out, t)
}
}
return out
}
func bezier(a, b, c, d point, t float64) point {
u := 1 - t
k0, k1, k2, k3 := u*u*u, 3*u*u*t, 3*u*t*t, t*t*t
return point{k0*a.x + k1*b.x + k2*c.x + k3*d.x, k0*a.y + k1*b.y + k2*c.y + k3*d.y}
}
// steps returns how many lines follow a cubic curve, in pixels, to a
// tenth of a pixel: the error of n lines is at most 3/4 of the curve's
// largest second difference over n².
func steps(a, b, c, d point) int {
ddx := math.Max(math.Abs(a.x-2*b.x+c.x), math.Abs(b.x-2*c.x+d.x))
ddy := math.Max(math.Abs(a.y-2*b.y+c.y), math.Abs(b.y-2*c.y+d.y))
dd := math.Hypot(ddx, ddy)
if !(dd >= 0) {
return 1
}
return max(1, min(int(math.Ceil(math.Sqrt(7.5*dd))), 1000))
}
// polys holds polylines: polyline i is pts[starts[i]:starts[i+1]], the
// last up to the end of pts.
type polys struct {
pts []point
starts []int
closed []bool
// begin is where the polyline being built begins, if building.
begin int
building bool
}
func (ps *polys) reset() {
ps.pts, ps.starts, ps.closed, ps.building = ps.pts[:0], ps.starts[:0], ps.closed[:0], false
}
func (ps *polys) len() int { return len(ps.starts) }
func (ps *polys) poly(i int) []point {
end := len(ps.pts)
if i+1 < len(ps.starts) {
end = ps.starts[i+1]
}
return ps.pts[ps.starts[i]:end]
}
// start begins a polyline at p, ending the one being built.
func (ps *polys) start(p point) {
ps.end(false)
ps.begin, ps.building = len(ps.pts), true
ps.pts = append(ps.pts, p)
}
func (ps *polys) add(p point) { ps.pts = append(ps.pts, p) }
// end ends the polyline being built. One of a single point, a move with
// nothing drawn, is dropped.
func (ps *polys) end(closed bool) {
if !ps.building {
return
}
ps.building = false
if len(ps.pts)-ps.begin < 2 {
ps.pts = ps.pts[:ps.begin]
return
}
ps.starts = append(ps.starts, ps.begin)
ps.closed = append(ps.closed, closed)
}
func (ps *polys) transform(m matrix) {
for i, p := range ps.pts {
ps.pts[i] = m.apply(p)
}
}
// maxPoints bounds the points of a flattened path: beyond it, curves are
// drawn as lines, and strokes are left out.
const maxPoints = 1 << 20
// flatten adds the path's subpaths to out as polylines, with points
// enough that they stray less than a tenth of a pixel from its curves
// once transformed by m, the transform to pixels: in pixels with device,
// in user units otherwise.
func (pa *path) flatten(m matrix, device bool, out *polys) {
at := func(p point) point {
if device {
return m.apply(p)
}
return p
}
var cur point
i := 0
for _, op := range pa.ops {
switch op {
case opMove:
cur = pa.pts[i]
i++
out.start(at(cur))
case opLine:
cur = pa.pts[i]
i++
out.add(at(cur))
case opCubic:
c1, c2, e := pa.pts[i], pa.pts[i+1], pa.pts[i+2]
i += 3
n := 1
if len(out.pts) < maxPoints {
n = steps(m.apply(cur), m.apply(c1), m.apply(c2), m.apply(e))
}
for k := 1; k < n; k++ {
out.add(at(bezier(cur, c1, c2, e, float64(k)/float64(n))))
}
out.add(at(e))
cur = e
case opClose:
if out.building && len(out.pts)-out.begin == 1 {
// A subpath of no length, which round and square caps
// stroke.
out.add(out.pts[out.begin])
}
out.end(true)
}
}
out.end(false)
}
+258
View File
@@ -0,0 +1,258 @@
package svg
import (
"math"
"slices"
"strings"
)
// vertex is a vertex of a path, where markers are drawn: the directions
// of the segments into and out of it, where there are some.
type vertex struct {
p point
in, out point
hasIn, hasOut bool
}
// angle returns the direction of a path at a vertex, in degrees: the
// bisector of the directions in and out of it.
func (v *vertex) angle() float64 {
switch {
case v.hasIn && v.hasOut:
a, b := math.Atan2(v.in.y, v.in.x), math.Atan2(v.out.y, v.out.x)
d := math.Remainder(b-a, 2*math.Pi)
return (a + d/2) * 180 / math.Pi
case v.hasIn:
return math.Atan2(v.in.y, v.in.x) * 180 / math.Pi
case v.hasOut:
return math.Atan2(v.out.y, v.out.x) * 180 / math.Pi
}
return 0
}
// direction returns the first of ds that is not of zero length.
func direction(ds ...point) point {
for _, d := range ds {
if d.x != 0 || d.y != 0 {
return d
}
}
return point{}
}
// vertices returns the vertices of a path, as markers see them: the
// points that segments start and end at, but where an arc was split into
// curves.
func (pa *path) vertices() []vertex {
var vs []vertex
var cur, start point
first := 0 // the vertex starting the subpath
segment := func(in, out, e point) {
if n := len(vs); n > 0 {
vs[n-1].out, vs[n-1].hasOut = in, true
}
vs = append(vs, vertex{p: e, in: out, hasIn: true})
cur = e
}
i := 0
for k, op := range pa.ops {
switch op {
case opMove:
cur, start = pa.pts[i], pa.pts[i]
i++
vs = append(vs, vertex{p: cur})
first = len(vs) - 1
case opLine:
e := pa.pts[i]
i++
d := point{e.x - cur.x, e.y - cur.y}
segment(d, d, e)
case opCubic:
c1, c2, e := pa.pts[i], pa.pts[i+1], pa.pts[i+2]
i += 3
in := direction(point{c1.x - cur.x, c1.y - cur.y}, point{c2.x - cur.x, c2.y - cur.y}, point{e.x - cur.x, e.y - cur.y})
out := direction(point{e.x - c2.x, e.y - c2.y}, point{e.x - c1.x, e.y - c1.y}, point{e.x - cur.x, e.y - cur.y})
if _, found := slices.BinarySearch(pa.arcs, k); found && len(vs) > 0 {
// The rest of an arc: the vertex moves to its end.
v := &vs[len(vs)-1]
v.p, v.in = e, out
cur = e
continue
}
segment(in, out, e)
case opClose:
d := point{start.x - cur.x, start.y - cur.y}
if d.x == 0 && d.y == 0 && len(vs) > 0 {
d = vs[len(vs)-1].in
}
segment(d, d, start)
// A closed subpath turns at its start: the markers there
// bisect the closing segment and the first.
if first < len(vs)-1 {
vs[first].in, vs[first].hasIn = d, true
last := &vs[len(vs)-1]
last.out, last.hasOut = vs[first].out, vs[first].hasOut
}
}
}
return vs
}
// markers compiles the markers an element e of style st draws along its
// path pa, of shape sh: those of marker-start at its first vertex,
// marker-mid at the others but the last, and marker-end at the last.
func (c *compiler) markers(e *elem, pa *path, st *style, sh *shape) []*node {
if st.markerStart == "" && st.markerMid == "" && st.markerEnd == "" {
return nil
}
switch e.name {
case "path", "line", "polyline", "polygon":
default:
return nil
}
vs := pa.vertices()
if len(vs) == 0 {
return nil
}
compiled := map[string]*markerDef{}
def := func(id string) *markerDef {
if id == "" {
return nil
}
if m, ok := compiled[id]; ok {
return m
}
m := c.marker(id, sh)
compiled[id] = m
return m
}
var out []*node
for i := range vs {
id := st.markerMid
switch {
case i == 0:
id = st.markerStart
case i == len(vs)-1:
id = st.markerEnd
}
if m := def(id); m != nil {
if n := m.at(&vs[i], i == 0, st.strokeWidth); n != nil {
out = append(out, n)
}
}
}
return out
}
// markerDef is a marker element compiled for an element it is drawn on.
type markerDef struct {
// ref is its reference point in its viewport, which goes on the
// vertex; w and h are the size of the viewport.
ref point
w, h float64
userUnits bool // markerUnits is userSpaceOnUse
auto bool // orient is auto or auto-start-reverse
reverse bool // orient is auto-start-reverse
angle float64
clip bool
content *node
clipRegion *clipDef
}
// marker compiles the marker element of id for an element of shape sh,
// whose fill and stroke context-fill and context-stroke are.
func (c *compiler) marker(id string, sh *shape) *markerDef {
el := c.ids[id]
if el == nil || el.name != "marker" || slices.Contains(c.using, el) || c.budget <= 0 {
return nil
}
c.using = append(c.using, el)
defer func() { c.using = c.using[:len(c.using)-1] }()
ctx := c.ctx
c.ctx = sh
defer func() { c.ctx = ctx }()
vw, vh := c.vw, c.vh
defer func() { c.vw, c.vh = vw, vh }()
m := &markerDef{
w: c.length(el, "markerWidth", c.vw, 3), h: c.length(el, "markerHeight", c.vh, 3),
userUnits: strings.TrimSpace(el.attrs["markerUnits"]) == "userSpaceOnUse",
}
if m.w <= 0 || m.h <= 0 {
return nil
}
switch o := strings.TrimSpace(el.attrs["orient"]); o {
case "auto":
m.auto = true
case "auto-start-reverse":
m.auto, m.reverse = true, true
default:
m.angle = parseAngle(o)
}
inner := &node{m: identity}
if vb, ok := parseViewBox(el.attrs["viewBox"]); ok {
inner.m = viewBoxTransform(vb, parseAspect(el.attrs["preserveAspectRatio"]), m.w, m.h)
c.vw, c.vh = vb.w, vb.h
} else {
c.vw, c.vh = m.w, m.h
}
m.ref = inner.m.apply(point{c.length(el, "refX", c.vw, 0), c.length(el, "refY", c.vh, 0)})
st := c.domStyle(el)
m.clip = !st.overflow
c.group(inner, el, st)
if len(inner.kids) == 0 {
return nil
}
c.finish(inner, &c.base)
m.content = inner
if m.clip {
var r path
r.rect(0, 0, m.w, m.h, 0, 0)
m.clipRegion = &clipDef{m: identity, kids: []*node{{m: identity, shape: &shape{path: r}}}}
}
return m
}
// at returns the marker drawn at a vertex, the first of its path when
// start is true, of a stroke as wide as width.
func (m *markerDef) at(v *vertex, start bool, width float64) *node {
angle := m.angle
if m.auto {
angle = v.angle()
if start && m.reverse {
angle += 180
}
}
scale := 1.0
if !m.userUnits {
scale = width
}
if scale <= 0 {
return nil
}
n := &node{
m: translate(v.p.x, v.p.y).mul(rotation(angle)).mul(scaling(scale, scale)).mul(translate(-m.ref.x, -m.ref.y)),
kids: []*node{m.content}, opacity: 1, clip: m.clipRegion,
}
n.bbox, n.hasBox = m.content.bbox.transform(m.content.m), m.content.hasBox
n.single = m.content.flat
n.flat = n.clip != nil || n.single
return n
}
// parseAngle parses an angle in degrees, or with a unit.
func parseAngle(v string) float64 {
scale := 1.0
switch {
case strings.HasSuffix(v, "deg"):
v = v[:len(v)-3]
case strings.HasSuffix(v, "grad"):
v, scale = v[:len(v)-4], 0.9
case strings.HasSuffix(v, "rad"):
v, scale = v[:len(v)-3], 180/math.Pi
case strings.HasSuffix(v, "turn"):
v, scale = v[:len(v)-4], 360
}
a, _ := parseNumber(v)
return a * scale
}
+539
View File
@@ -0,0 +1,539 @@
package svg
import (
"image"
"math"
"github.com/egoist/mygo/internal/vec"
)
// renderer draws nodes into layers of premultiplied RGBA pixels, w×h.
type renderer struct {
w, h int
current rgba
z vec.Rasterizer
// cov is the coverage of what is being drawn, a rectangle of the
// canvas.
cov []byte
flat, dashed, outline polys
stroker stroker
free []*layer
// fonts draws the text of the document being drawn, and boxes are
// where it lays out a text element's runs.
fonts Fonts
boxes []textBox
// ext is that of the document being drawn.
ext *extras
}
// layer is a canvas: rows of 4×w bytes, with what was drawn into it
// within dirty.
type layer struct {
pix []byte
dirty image.Rectangle
}
func (r *renderer) layer() *layer {
if n := len(r.free); n > 0 {
l := r.free[n-1]
r.free = r.free[:n-1]
return l
}
return &layer{pix: make([]byte, r.w*r.h*4)}
}
// release clears a layer for reuse.
func (r *renderer) release(l *layer) {
d := l.dirty
for y := d.Min.Y; y < d.Max.Y; y++ {
clear(l.pix[(y*r.w+d.Min.X)*4 : (y*r.w+d.Max.X)*4])
}
l.dirty = image.Rectangle{}
r.free = append(r.free, l)
}
// node draws n, whose parent's user space maps to pixels by ctm, into dst
// with an opacity.
func (r *renderer) node(n *node, ctm matrix, dst *layer, alpha float64) {
a := alpha * n.opacity
if a <= 0 {
return
}
m := ctm.mul(n.m)
if n.clip == nil && n.mask == nil && (n.opacity >= 1 || n.single) {
r.content(n, m, dst, a)
return
}
// Group opacity, clipping and masking apply to the content as a whole.
l := r.layer()
r.content(n, m, l, 1)
if n.clip != nil {
r.clip(l, n.clip, m, n.bbox, n.hasBox)
}
if n.mask != nil {
r.mask(l, n.mask, m, n.bbox, n.hasBox)
}
r.composite(dst, l, a)
r.release(l)
}
func (r *renderer) content(n *node, m matrix, dst *layer, alpha float64) {
if n.text != nil {
// Only Parse, which sets ext, compiles text.
r.ext.drawText(r, n.text, m, dst, alpha)
return
}
s := n.shape
if s == nil {
for _, k := range n.kids {
r.node(k, m, dst, alpha)
}
return
}
if s.strokeFirst {
r.stroke(s, m, dst, alpha, n.bbox)
r.fill(s, m, dst, alpha, n.bbox)
} else {
r.fill(s, m, dst, alpha, n.bbox)
r.stroke(s, m, dst, alpha, n.bbox)
}
}
func (r *renderer) fill(s *shape, m matrix, dst *layer, alpha float64, bbox box) {
if s.fill.kind == paintNone {
return
}
r.flat.reset()
s.path.flatten(m, true, &r.flat)
if rect, ok := r.cover(&r.flat, s.evenOdd); ok {
r.paint(dst, rect, s.fill, alpha*s.fillOpacity, m, bbox)
}
}
func (r *renderer) stroke(s *shape, m matrix, dst *layer, alpha float64, bbox box) {
if s.stroke.kind == paintNone || s.width <= 0 {
return
}
scale := m.stretch()
if !(scale > 0) {
return
}
r.flat.reset()
s.path.flatten(m, false, &r.flat)
lines := &r.flat
if len(s.dashes) > 0 {
r.dashed.reset()
dash(&r.flat, s.dashes, s.dashOffset, &r.dashed, 1<<16)
lines = &r.dashed
}
r.outline.reset()
st := &r.stroker
st.hw, st.join, st.cap, st.miter, st.tol, st.out = s.width/2, s.join, s.cap, s.miter, 0.1/scale, &r.outline
st.stroke(lines)
r.outline.transform(m)
if rect, ok := r.cover(&r.outline, false); ok {
r.paint(dst, rect, s.stroke, alpha*s.strokeOpacity, m, bbox)
}
}
// cover rasterizes polygons in pixels into r.cov, returning the rectangle
// of the canvas it covers.
func (r *renderer) cover(ps *polys, evenOdd bool) (image.Rectangle, bool) {
if ps.len() == 0 {
return image.Rectangle{}, false
}
// Shapes far beyond the canvas, or not finite, draw nothing.
const far = 1 << 24
x0, y0 := math.Inf(1), math.Inf(1)
x1, y1 := math.Inf(-1), math.Inf(-1)
for _, p := range ps.pts {
if !(p.x > -far && p.x < far && p.y > -far && p.y < far) {
return image.Rectangle{}, false
}
if p.x < x0 {
x0 = p.x
}
if p.x > x1 {
x1 = p.x
}
if p.y < y0 {
y0 = p.y
}
if p.y > y1 {
y1 = p.y
}
}
rect := image.Rect(int(math.Floor(x0)), int(math.Floor(y0)), int(math.Ceil(x1))+1, int(math.Ceil(y1))+1).
Intersect(image.Rect(0, 0, r.w, r.h))
if rect.Empty() {
return image.Rectangle{}, false
}
w, h := rect.Dx(), rect.Dy()
r.z.Reset(w, h)
ox, oy := float64(rect.Min.X), float64(rect.Min.Y)
for i := range ps.len() {
pts := ps.poly(i)
r.z.MoveTo(float32(pts[0].x-ox), float32(pts[0].y-oy))
for _, p := range pts[1:] {
r.z.LineTo(float32(p.x-ox), float32(p.y-oy))
}
r.z.ClosePath()
}
if cap(r.cov) < w*h {
r.cov = make([]byte, w*h)
}
r.cov = r.cov[:w*h]
if evenOdd {
r.z.MaskEvenOdd(r.cov, w)
} else {
r.z.Mask(r.cov, w)
}
return rect, true
}
// div255 divides by 255, rounding, for x up to 255×255.
func div255(x uint32) uint32 { return (x + 128 + (x+128)>>8) >> 8 }
// over composites a premultiplied color over the pixel d.
func over(d []byte, r, g, b, a uint32) {
ia := 255 - a
d[0] = uint8(r + div255(uint32(d[0])*ia))
d[1] = uint8(g + div255(uint32(d[1])*ia))
d[2] = uint8(b + div255(uint32(d[2])*ia))
d[3] = uint8(a + div255(uint32(d[3])*ia))
}
// premul returns c with an opacity, premultiplied, from 0 to 255.
func premul(c rgba, alpha float64) [4]uint32 {
a := math.Max(0, math.Min(1, c.a*alpha))
q := func(v float64) uint32 { return uint32(math.Max(0, math.Min(1, v))*a*255 + 0.5) }
return [4]uint32{q(c.r), q(c.g), q(c.b), uint32(a*255 + 0.5)}
}
// paint paints the coverage in r.cov, of rect, with a paint and an
// opacity. m maps the user space of the shape it covers to pixels.
func (r *renderer) paint(dst *layer, rect image.Rectangle, p paint, alpha float64, m matrix, bbox box) {
w := rect.Dx()
switch p.kind {
case paintColor, paintCurrent:
col := p.color
if p.kind == paintCurrent {
col = r.current
}
c := premul(col, alpha)
if c[3] == 0 {
return
}
for y := rect.Min.Y; y < rect.Max.Y; y++ {
cov := r.cov[(y-rect.Min.Y)*w : (y-rect.Min.Y+1)*w]
row := dst.pix[(y*r.w+rect.Min.X)*4:]
for x, v := range cov {
if v == 0 {
continue
}
if v == 255 && c[3] == 255 {
d := row[x*4 : x*4+4]
d[0], d[1], d[2], d[3] = uint8(c[0]), uint8(c[1]), uint8(c[2]), 255
continue
}
k := uint32(v)
over(row[x*4:x*4+4], div255(c[0]*k), div255(c[1]*k), div255(c[2]*k), div255(c[3]*k))
}
}
case paintGradient:
g := p.grad
gm := m
if g.bbox {
if bbox.w == 0 || bbox.h == 0 {
return // the gradient has no box to span
}
gm = gm.mul(boxMatrix(bbox))
}
inv, ok := gm.mul(g.m).invert()
if !ok {
return
}
var lut [256][4]uint32
g.lut(r.current, alpha, &lut)
for y := rect.Min.Y; y < rect.Max.Y; y++ {
cov := r.cov[(y-rect.Min.Y)*w : (y-rect.Min.Y+1)*w]
row := dst.pix[(y*r.w+rect.Min.X)*4:]
for x, v := range cov {
if v == 0 {
continue
}
t, ok := g.at(inv.apply(point{float64(rect.Min.X+x) + 0.5, float64(y) + 0.5}))
if !ok {
continue
}
c := &lut[int(t*255+0.5)]
k := uint32(v)
over(row[x*4:x*4+4], div255(c[0]*k), div255(c[1]*k), div255(c[2]*k), div255(c[3]*k))
}
}
default:
return
}
dst.dirty = dst.dirty.Union(rect)
}
// at returns where a point in the gradient's space falls along it, spread
// into [0, 1]; ok is false where a radial gradient does not reach.
func (g *gradient) at(p point) (float64, bool) {
var t float64
if !g.radial {
dx, dy := g.x2-g.x1, g.y2-g.y1
d := dx*dx + dy*dy
if d == 0 {
return 1, true // the last stop's color
}
t = ((p.x-g.x1)*dx + (p.y-g.y1)*dy) / d
} else {
if g.r <= 0 {
return 1, true
}
// The largest t for which p is on the circle around
// f + t(c - f) of radius fr + t(r - fr).
cdx, cdy := g.cx-g.fx, g.cy-g.fy
pdx, pdy := p.x-g.fx, p.y-g.fy
dr := g.r - g.fr
a := cdx*cdx + cdy*cdy - dr*dr
b := pdx*cdx + pdy*cdy + g.fr*dr
c := pdx*pdx + pdy*pdy - g.fr*g.fr
if math.Abs(a) < 1e-12 {
if b == 0 {
return 0, false
}
t = c / (2 * b)
} else {
disc := b*b - a*c
if disc < 0 {
return 0, false
}
s := math.Sqrt(disc)
t0, t1 := (b+s)/a, (b-s)/a
t = math.Max(t0, t1)
if g.fr+t*dr < 0 {
t = math.Min(t0, t1)
if g.fr+t*dr < 0 {
return 0, false
}
}
}
}
switch g.spread {
case spreadReflect:
t = math.Mod(math.Abs(t), 2)
if t > 1 {
t = 2 - t
}
case spreadRepeat:
t -= math.Floor(t)
default:
t = math.Max(0, math.Min(1, t))
}
if !(t >= 0 && t <= 1) {
return 0, false
}
return t, true
}
// lut fills out with the gradient's colors at 256 positions, with an
// opacity, premultiplied.
func (g *gradient) lut(current rgba, alpha float64, out *[256][4]uint32) {
stops := g.stops
color := func(s *stop) rgba {
c := s.color
if s.current {
c = current
}
c.a *= s.opacity
return c
}
j := 0
for i := range out {
t := float64(i) / 255
for j+1 < len(stops) && stops[j+1].offset <= t {
j++
}
var c rgba
switch {
case t <= stops[0].offset:
c = color(&stops[0])
case j == len(stops)-1:
c = color(&stops[j])
default:
a, b := color(&stops[j]), color(&stops[j+1])
f := (t - stops[j].offset) / (stops[j+1].offset - stops[j].offset)
c = rgba{a.r + (b.r-a.r)*f, a.g + (b.g-a.g)*f, a.b + (b.b-a.b)*f, a.a + (b.a-a.a)*f}
}
out[i] = premul(c, alpha)
}
}
// composite draws src over dst with an opacity.
func (r *renderer) composite(dst, src *layer, alpha float64) {
d := src.dirty
if d.Empty() {
return
}
k := uint32(math.Max(0, math.Min(1, alpha))*255 + 0.5)
for y := d.Min.Y; y < d.Max.Y; y++ {
i0, i1 := (y*r.w+d.Min.X)*4, (y*r.w+d.Max.X)*4
s, t := src.pix[i0:i1], dst.pix[i0:i1]
for i := 0; i < len(s); i += 4 {
if s[i+3] == 0 {
continue
}
if k == 255 {
over(t[i:i+4], uint32(s[i]), uint32(s[i+1]), uint32(s[i+2]), uint32(s[i+3]))
continue
}
over(t[i:i+4], div255(uint32(s[i])*k), div255(uint32(s[i+1])*k), div255(uint32(s[i+2])*k), div255(uint32(s[i+3])*k))
}
}
dst.dirty = dst.dirty.Union(d)
}
// scale multiplies the pixels of l within its dirty rectangle by the
// values of mask, one byte per pixel of that rectangle.
func (r *renderer) scale(l *layer, mask []byte) {
d := l.dirty
w := d.Dx()
for y := d.Min.Y; y < d.Max.Y; y++ {
row := l.pix[(y*r.w+d.Min.X)*4 : (y*r.w+d.Max.X)*4]
m := mask[(y-d.Min.Y)*w : (y-d.Min.Y+1)*w]
for x, v := range m {
p := row[x*4 : x*4+4]
switch v {
case 255:
case 0:
p[0], p[1], p[2], p[3] = 0, 0, 0, 0
default:
k := uint32(v)
p[0] = uint8(div255(uint32(p[0]) * k))
p[1] = uint8(div255(uint32(p[1]) * k))
p[2] = uint8(div255(uint32(p[2]) * k))
p[3] = uint8(div255(uint32(p[3]) * k))
}
}
}
}
// clip clips what a layer holds to a clip path, applied in the user space
// m of an element with a bounding box.
func (r *renderer) clip(l *layer, cd *clipDef, m matrix, bbox box, hasBox bool) {
if l.dirty.Empty() {
return
}
r.scale(l, r.clipMask(cd, m, bbox, hasBox, l.dirty))
}
// clipMask returns the coverage of a clip path over a rectangle.
func (r *renderer) clipMask(cd *clipDef, m matrix, bbox box, hasBox bool, rect image.Rectangle) []byte {
w := rect.Dx()
mask := make([]byte, w*rect.Dy())
cm := m.mul(cd.m)
if cd.bbox {
if !hasBox || bbox.w == 0 || bbox.h == 0 {
return mask // nothing to clip to
}
cm = cm.mul(boxMatrix(bbox))
}
for _, k := range cd.kids {
r.clipNode(k, cm, rect, mask)
}
if cd.clip != nil {
inner := r.clipMask(cd.clip, m, bbox, hasBox, rect)
for i, v := range inner {
mask[i] = uint8(div255(uint32(mask[i]) * uint32(v)))
}
}
return mask
}
// clipNode adds the coverage of a clip path's node to mask, a rectangle.
func (r *renderer) clipNode(n *node, m matrix, rect image.Rectangle, mask []byte) {
m = m.mul(n.m)
if n.shape == nil {
for _, k := range n.kids {
r.clipNode(k, m, rect, mask)
}
return
}
r.flat.reset()
n.shape.path.flatten(m, true, &r.flat)
cr, ok := r.cover(&r.flat, n.shape.evenOdd)
if !ok {
return
}
in := cr.Intersect(rect)
cw, w := cr.Dx(), rect.Dx()
for y := in.Min.Y; y < in.Max.Y; y++ {
src := r.cov[(y-cr.Min.Y)*cw+in.Min.X-cr.Min.X:]
dst := mask[(y-rect.Min.Y)*w+in.Min.X-rect.Min.X:]
for x := range in.Dx() {
a, b := uint32(dst[x]), uint32(src[x])
dst[x] = uint8(a + b - div255(a*b))
}
}
}
// mask masks what a layer holds with a mask, applied in the user space m
// of an element with a bounding box.
func (r *renderer) mask(l *layer, md *maskDef, m matrix, bbox box, hasBox bool) {
d := l.dirty
if d.Empty() {
return
}
region := md.region
cm := m
if md.units || md.content {
if !hasBox || bbox.w == 0 || bbox.h == 0 {
r.scale(l, make([]byte, d.Dx()*d.Dy()))
return
}
if md.units {
region = box{bbox.x + region.x*bbox.w, bbox.y + region.y*bbox.h, region.w * bbox.w, region.h * bbox.h}
}
if md.content {
cm = m.mul(boxMatrix(bbox))
}
}
ml := r.layer()
for _, k := range md.kids {
r.node(k, cm, ml, 1)
}
values := make([]byte, d.Dx()*d.Dy())
w := d.Dx()
for y := d.Min.Y; y < d.Max.Y; y++ {
row := ml.pix[(y*r.w+d.Min.X)*4 : (y*r.w+d.Max.X)*4]
for x := range w {
p := row[x*4 : x*4+4]
v := uint32(p[3])
if !md.alpha {
// Luminance, of premultiplied colors.
v = (54*uint32(p[0]) + 183*uint32(p[1]) + 19*uint32(p[2]) + 128) >> 8
}
values[(y-d.Min.Y)*w+x] = uint8(min(v, 255))
}
}
r.release(ml)
// The mask's content shows within its region only.
var rp path
rp.rect(region.x, region.y, region.w, region.h, 0, 0)
r.flat.reset()
rp.flatten(m, true, &r.flat)
cr, ok := r.cover(&r.flat, false)
for y := d.Min.Y; y < d.Max.Y; y++ {
for x := d.Min.X; x < d.Max.X; x++ {
i := (y-d.Min.Y)*w + x - d.Min.X
if !ok || !(image.Point{x, y}.In(cr)) {
values[i] = 0
continue
}
values[i] = uint8(div255(uint32(values[i]) * uint32(r.cov[(y-cr.Min.Y)*cr.Dx()+x-cr.Min.X])))
}
}
r.scale(l, values)
}
+284
View File
@@ -0,0 +1,284 @@
package svg
import "math"
// Line caps and joins.
const (
capButt uint8 = iota
capRound
capSquare
)
const (
joinMiter uint8 = iota
joinRound
joinBevel
)
// stroker outlines polylines as polygons that all turn the same way, so
// that the non-zero rule fills their union: a quadrilateral per segment,
// and the shapes of the joins and caps.
type stroker struct {
hw float64 // half the width
join, cap uint8
miter float64 // the miter limit
tol float64 // how far arcs may stray from circles
out *polys
pts []point
}
func (s *stroker) stroke(in *polys) {
for i := range in.len() {
closed := in.closed[i]
pts := s.pts[:0]
for _, p := range in.poly(i) {
if len(pts) == 0 || p != pts[len(pts)-1] {
pts = append(pts, p)
}
}
if closed && len(pts) > 1 && pts[0] == pts[len(pts)-1] {
pts = pts[:len(pts)-1]
}
s.pts = pts
n := len(pts)
if n == 1 {
s.dot(pts[0])
continue
}
segs := n - 1
if closed {
segs = n
}
for k := range segs {
s.segment(pts[k], pts[(k+1)%n])
}
if closed {
for k := range n {
s.joinAt(pts[(k+n-1)%n], pts[k], pts[(k+1)%n])
}
continue
}
for k := 1; k < n-1; k++ {
s.joinAt(pts[k-1], pts[k], pts[k+1])
}
s.capAt(pts[0], pts[1])
s.capAt(pts[n-1], pts[n-2])
}
}
// full reports whether the outline has all the points it may have.
func (s *stroker) full() bool { return len(s.out.pts) >= 2*maxPoints }
// polygon adds a polygon to out, turned the way they all turn.
func (s *stroker) polygon(pts ...point) {
if s.full() {
return
}
o := s.out
o.start(pts[0])
for _, p := range pts[1:] {
o.add(p)
}
s.finish()
}
// finish ends the polygon being built, reversing it if it turns the other
// way.
func (s *stroker) finish() {
o := s.out
begin := o.begin
o.end(true)
if len(o.starts) == 0 || o.starts[len(o.starts)-1] != begin {
return
}
pts := o.pts[begin:]
var area float64
a := pts[len(pts)-1]
for _, b := range pts {
area += a.x*b.y - b.x*a.y
a = b
}
if area < 0 {
for i, j := 0, len(pts)-1; i < j; i, j = i+1, j-1 {
pts[i], pts[j] = pts[j], pts[i]
}
}
}
func unit(a, b point) point {
dx, dy := b.x-a.x, b.y-a.y
l := math.Sqrt(dx*dx + dy*dy)
return point{dx / l, dy / l}
}
func (s *stroker) segment(a, b point) {
d := unit(a, b)
n := point{-d.y * s.hw, d.x * s.hw}
s.polygon(point{a.x + n.x, a.y + n.y}, point{b.x + n.x, b.y + n.y}, point{b.x - n.x, b.y - n.y}, point{a.x - n.x, a.y - n.y})
}
// joinAt joins the segments a→p and p→b on the outer side of the turn.
func (s *stroker) joinAt(a, p, b point) {
d0, d1 := unit(a, p), unit(p, b)
cross := d0.x*d1.y - d0.y*d1.x
dot := d0.x*d1.x + d0.y*d1.y
if math.Abs(cross) < 1e-12 && dot > 0 {
return // straight on
}
side := s.hw
if cross > 0 {
side = -s.hw
}
n0 := point{-d0.y * side, d0.x * side}
n1 := point{-d1.y * side, d1.x * side}
o0 := point{p.x + n0.x, p.y + n0.y}
o1 := point{p.x + n1.x, p.y + n1.y}
switch s.join {
case joinRound:
turn := math.Atan2(math.Abs(cross), dot)
if s.hw*(1-math.Cos(turn/2)) < s.tol {
s.polygon(p, o0, o1)
return
}
s.wedge(p, n0, math.Atan2(n0.x*n1.y-n0.y*n1.x, n0.x*n1.x+n0.y*n1.y))
case joinBevel:
s.polygon(p, o0, o1)
default:
// The miter's length over the stroke's width is 1/cos(turn/2).
cosHalf := math.Sqrt(math.Max((1+dot)/2, 0))
if cosHalf*s.miter < 1 {
s.polygon(p, o0, o1)
return
}
u := unit(point{}, point{n0.x + n1.x, n0.y + n1.y})
l := s.hw / cosHalf
s.polygon(p, o0, point{p.x + u.x*l, p.y + u.y*l}, o1)
}
}
// capAt caps the end p of a polyline whose last segment comes from prev.
func (s *stroker) capAt(p, prev point) {
d := unit(prev, p)
n := point{d.y * s.hw, -d.x * s.hw}
switch s.cap {
case capRound:
// Half a turn from n, through the direction d.
s.wedge(p, n, math.Pi)
case capSquare:
e := point{d.x * s.hw, d.y * s.hw}
s.polygon(point{p.x + n.x, p.y + n.y}, point{p.x + n.x + e.x, p.y + n.y + e.y},
point{p.x - n.x + e.x, p.y - n.y + e.y}, point{p.x - n.x, p.y - n.y})
}
}
// dot draws a subpath of no length: a disc with round caps, a square with
// square caps.
func (s *stroker) dot(p point) {
switch s.cap {
case capRound:
s.wedge(p, point{s.hw, 0}, 2*math.Pi)
case capSquare:
h := s.hw
s.polygon(point{p.x - h, p.y - h}, point{p.x + h, p.y - h}, point{p.x + h, p.y + h}, point{p.x - h, p.y + h})
}
}
// wedge adds the slice of the disc around c of radius hw from the vector
// from, sweeping sweep radians.
func (s *stroker) wedge(c, from point, sweep float64) {
if s.full() {
return
}
step := 2 * math.Acos(math.Max(1-s.tol/s.hw, -1))
n := 1
if step > 0 {
n = max(1, min(int(math.Ceil(math.Abs(sweep)/step)), 256))
}
a0 := math.Atan2(from.y, from.x)
o := s.out
full := math.Abs(sweep) >= 2*math.Pi
if full {
n = max(n, 8)
}
// Points between the ends lie a little outside the circle, so that
// the polygon covers as much as the slice of the disc does.
a := math.Abs(sweep) / float64(n)
r := s.hw * math.Sqrt(a/math.Sin(a))
if full {
o.start(point{c.x + from.x*r/s.hw, c.y + from.y*r/s.hw})
} else {
o.start(c)
o.add(point{c.x + from.x, c.y + from.y})
}
for k := 1; k < n; k++ {
sin, cos := math.Sincos(a0 + sweep*float64(k)/float64(n))
o.add(point{c.x + cos*r, c.y + sin*r})
}
if !full {
sin, cos := math.Sincos(a0 + sweep)
o.add(point{c.x + cos*s.hw, c.y + sin*s.hw})
}
s.finish()
}
// dash cuts the polylines of in into the dashes of a dash array (of even
// length), starting offset into it, as open polylines in out. limit
// bounds the number of dashes.
func dash(in *polys, dashes []float64, offset float64, out *polys, limit int) {
var total float64
for _, d := range dashes {
total += d
}
offset = math.Mod(offset, total)
if offset < 0 {
offset += total
}
for i := range in.len() {
pts := in.poly(i)
// Every subpath starts the pattern anew, offset into it: in dash
// or gap k, with left of it to go.
k, o := 0, offset
for o > dashes[k] {
o -= dashes[k]
k = (k + 1) % len(dashes)
}
left := dashes[k] - o
on := k%2 == 0
if on {
out.start(pts[0])
}
n := len(pts)
segs := n - 1
if in.closed[i] {
segs = n
}
for sg := range segs {
a, b := pts[sg], pts[(sg+1)%n]
l := math.Hypot(b.x-a.x, b.y-a.y)
pos := 0.0
for l-pos > left {
pos += left
t := pos / l
p := point{a.x + (b.x-a.x)*t, a.y + (b.y-a.y)*t}
if on {
out.add(p)
out.end(false)
limit--
if limit <= 0 {
return
}
} else {
out.start(p)
}
on = !on
k = (k + 1) % len(dashes)
left = dashes[k]
}
left -= l - pos
if on {
out.add(b)
}
}
out.end(false)
}
}
+842
View File
@@ -0,0 +1,842 @@
package svg
import (
"math"
"strings"
)
// rgba is a straight color, its components from 0 to 1.
type rgba struct{ r, g, b, a float64 }
var black = rgba{0, 0, 0, 1}
// Kinds of paint specifications.
const (
specNone uint8 = iota
specColor
specCurrent
specURL
// The fill and the stroke of the element a marker is drawn on.
specContextFill
specContextStroke
)
// paintSpec is a fill or stroke as written: none, a color, currentColor,
// or a reference to a gradient with what to paint when it is not one.
type paintSpec struct {
kind uint8
color rgba
id string
fallback uint8 // specNone, specColor or specCurrent, with color
}
// style is the computed style of an element.
type style struct {
// Inherited.
fill, stroke paintSpec
fillOpacity float64
strokeOpacity float64
fillEvenOdd bool
clipEvenOdd bool
strokeWidth float64
miterLimit float64
cap, join uint8
dashes []float64
dashOffset float64
// color is the color property, which currentColor stands for; until a
// document sets it, currentColor is the color it is drawn with.
color rgba
colorSet bool
visible bool
strokeFirst bool
// The font and the layout of text.
fontFamily string
fontSize float64
fontWeight int
italic bool
letterSpacing float64
anchor uint8 // text-anchor
baseline uint8 // dominant-baseline
preserve bool // white-space that keeps spaces
// The markers of paths, lines, polylines and polygons.
markerStart, markerMid, markerEnd string
// Not inherited.
opacity float64
display bool
clipPath string
mask string
maskAlpha bool
stopColor paintSpec
stopOpacity float64
align uint8 // alignment-baseline, which overrides baseline
overflow bool // overflow is visible
}
// Values of text-anchor.
const (
anchorStart uint8 = iota
anchorMiddle
anchorEnd
)
// Baselines of dominant-baseline and alignment-baseline.
const (
baselineAuto uint8 = iota // the alphabetic baseline
baselineMiddle
baselineCentral
baselineHanging
baselineTop
baselineBottom
baselineMath
)
func initialStyle() style {
return style{
fill: paintSpec{kind: specColor, color: black},
fillOpacity: 1, strokeOpacity: 1, strokeWidth: 1, miterLimit: 4,
visible: true, opacity: 1, display: true,
stopColor: paintSpec{kind: specColor, color: black}, stopOpacity: 1,
fontSize: 16, fontWeight: 400,
}
}
// initial is the initial value of every property.
var initial = initialStyle()
// properties are the properties that attributes, style sheets and style
// attributes set.
var properties = map[string]bool{
"fill": true, "fill-opacity": true, "fill-rule": true,
"stroke": true, "stroke-width": true, "stroke-opacity": true, "stroke-linecap": true,
"stroke-linejoin": true, "stroke-miterlimit": true, "stroke-dasharray": true, "stroke-dashoffset": true,
"opacity": true, "color": true, "display": true, "visibility": true, "paint-order": true,
"clip-path": true, "clip-rule": true, "mask": true, "mask-type": true,
"stop-color": true, "stop-opacity": true,
"font": true, "font-family": true, "font-size": true, "font-weight": true, "font-style": true,
"letter-spacing": true, "text-anchor": true, "dominant-baseline": true, "alignment-baseline": true,
"white-space": true, "marker": true, "marker-start": true, "marker-mid": true, "marker-end": true,
"overflow": true,
}
// inherited reports whether a property is inherited.
func inherited(name string) bool {
switch name {
case "opacity", "display", "clip-path", "mask", "mask-type", "stop-color", "stop-opacity", "alignment-baseline", "overflow":
return false
}
return true
}
// computeStyle computes the style of e, a child of an element of style
// parent, with lengths in percent of the viewport vw×vh.
func computeStyle(e *elem, parent *style, vw, vh float64) style {
s := *parent
s.opacity, s.display, s.clipPath, s.mask, s.maskAlpha = 1, true, "", "", false
s.stopColor, s.stopOpacity = paintSpec{kind: specColor, color: black}, 1
s.align, s.overflow = baselineAuto, false
diag := math.Sqrt((vw*vw + vh*vh) / 2)
for _, d := range e.props {
v := d.value
switch v {
case "inherit":
s.inherit(d.name, parent)
continue
case "initial", "unset":
if v == "unset" && inherited(d.name) {
s.inherit(d.name, parent)
} else {
s.inherit(d.name, &initial)
}
continue
}
switch d.name {
case "fill":
if p, ok := parsePaint(v); ok {
s.fill = p
}
case "stroke":
if p, ok := parsePaint(v); ok {
s.stroke = p
}
case "fill-opacity":
s.fillOpacity = parseOpacity(v, s.fillOpacity)
case "stroke-opacity":
s.strokeOpacity = parseOpacity(v, s.strokeOpacity)
case "opacity":
s.opacity = parseOpacity(v, s.opacity)
case "stop-opacity":
s.stopOpacity = parseOpacity(v, s.stopOpacity)
case "fill-rule":
if v == "evenodd" || v == "nonzero" {
s.fillEvenOdd = v == "evenodd"
}
case "clip-rule":
if v == "evenodd" || v == "nonzero" {
s.clipEvenOdd = v == "evenodd"
}
case "stroke-width":
if w, ok := parseLength(v, diag); ok && w >= 0 {
s.strokeWidth = w
}
case "stroke-miterlimit":
if l, ok := parseNumber(v); ok && l >= 1 {
s.miterLimit = l
}
case "stroke-linecap":
switch v {
case "butt":
s.cap = capButt
case "round":
s.cap = capRound
case "square":
s.cap = capSquare
}
case "stroke-linejoin":
switch v {
case "miter", "miter-clip", "arcs":
s.join = joinMiter
case "round":
s.join = joinRound
case "bevel":
s.join = joinBevel
}
case "stroke-dasharray":
s.dashes = parseDashes(v, diag)
case "stroke-dashoffset":
if o, ok := parseLength(v, diag); ok {
s.dashOffset = o
}
case "color":
if strings.EqualFold(v, "currentColor") {
break // the color it inherits
}
if c, ok := parseColor(v); ok {
s.color, s.colorSet = c, true
}
case "display":
s.display = v != "none"
case "visibility":
if v == "visible" || v == "hidden" || v == "collapse" {
s.visible = v == "visible"
}
case "paint-order":
s.strokeFirst = strokeFirst(v)
case "clip-path":
s.clipPath = urlID(v)
case "mask":
s.mask = urlID(v)
case "mask-type":
s.maskAlpha = v == "alpha"
case "stop-color":
if strings.EqualFold(v, "currentColor") {
s.stopColor = paintSpec{kind: specCurrent}
} else if c, ok := parseColor(v); ok {
s.stopColor = paintSpec{kind: specColor, color: c}
}
case "font":
s.font(v, parent)
case "font-family":
s.fontFamily = v
case "font-size":
if n, ok := parseFontSize(v, parent.fontSize); ok {
s.fontSize = n
}
case "font-weight":
if w, ok := parseWeight(v, parent.fontWeight); ok {
s.fontWeight = w
}
case "font-style":
s.italic = v == "italic" || strings.HasPrefix(v, "oblique")
case "letter-spacing":
if v == "normal" {
s.letterSpacing = 0
} else if l, ok := parseEm(v, s.fontSize); ok {
s.letterSpacing = l
}
case "text-anchor":
switch v {
case "start":
s.anchor = anchorStart
case "middle":
s.anchor = anchorMiddle
case "end":
s.anchor = anchorEnd
}
case "dominant-baseline":
if b, ok := parseBaseline(v); ok {
s.baseline = b
}
case "alignment-baseline":
if b, ok := parseBaseline(v); ok {
s.align = b
}
case "white-space":
s.preserve = strings.HasPrefix(v, "pre") || v == "break-spaces"
case "marker":
id := urlID(v)
s.markerStart, s.markerMid, s.markerEnd = id, id, id
case "marker-start":
s.markerStart = urlID(v)
case "marker-mid":
s.markerMid = urlID(v)
case "marker-end":
s.markerEnd = urlID(v)
case "overflow":
s.overflow = v == "visible" || v == "auto"
}
}
return s
}
// font sets the properties the font shorthand does: a style and a weight,
// a size with an optional line height, and the families.
func (s *style) font(v string, parent *style) {
f := strings.Fields(v)
for i, t := range f {
size, _, _ := strings.Cut(t, "/")
if n, ok := parseFontSize(size, parent.fontSize); ok {
s.fontSize = n
rest := f[i+1:]
if len(rest) > 0 && strings.HasPrefix(rest[0], "/") {
rest = rest[1:] // a line height after a space
}
s.fontFamily = strings.Join(rest, " ")
s.italic, s.fontWeight = false, 400
for _, k := range f[:i] {
if k == "italic" || k == "oblique" {
s.italic = true
} else if w, ok := parseWeight(k, parent.fontWeight); ok {
s.fontWeight = w
}
}
return
}
}
}
// parseFontSize parses a font size: a length, a percentage or em of the
// parent's, or a keyword.
func parseFontSize(v string, parent float64) (float64, bool) {
switch v {
case "larger":
return parent * 1.2, true
case "smaller":
return parent / 1.2, true
case "xx-small":
return 9, true
case "x-small":
return 10, true
case "small":
return 13, true
case "medium":
return 16, true
case "large":
return 18, true
case "x-large":
return 24, true
case "xx-large":
return 32, true
}
if n, ok := parseEm(v, parent); ok && n >= 0 {
return n, true
}
return 0, false
}
// parseEm parses a length with em and percentages of em.
func parseEm(v string, em float64) (float64, bool) {
l := strings.ToLower(v)
if n, ok := parseNumber(strings.TrimSuffix(l, "em")); ok && strings.HasSuffix(l, "em") && !strings.HasSuffix(l, "rem") {
return n * em, true
}
return parseLength(v, em)
}
// parseWeight parses a font weight, bolder and lighter than the parent's
// as CSS's table says.
func parseWeight(v string, parent int) (int, bool) {
switch v {
case "normal":
return 400, true
case "bold":
return 700, true
case "bolder":
switch {
case parent < 350:
return 400, true
case parent < 550:
return 700, true
}
return 900, true
case "lighter":
switch {
case parent < 550:
return 100, true
case parent < 750:
return 400, true
}
return 700, true
}
if n, ok := parseNumber(v); ok && n >= 1 && n <= 1000 {
return int(n), true
}
return 0, false
}
func parseBaseline(v string) (uint8, bool) {
switch v {
case "auto", "alphabetic", "baseline":
return baselineAuto, true
case "middle":
return baselineMiddle, true
case "central":
return baselineCentral, true
case "hanging":
return baselineHanging, true
case "text-top", "text-before-edge", "before-edge":
return baselineTop, true
case "text-bottom", "text-after-edge", "after-edge", "ideographic":
return baselineBottom, true
case "mathematical":
return baselineMath, true
}
return 0, false
}
// inherit takes a property from the parent's style, undoing what an
// earlier declaration set.
func (s *style) inherit(name string, p *style) {
switch name {
case "fill":
s.fill = p.fill
case "stroke":
s.stroke = p.stroke
case "fill-opacity":
s.fillOpacity = p.fillOpacity
case "stroke-opacity":
s.strokeOpacity = p.strokeOpacity
case "fill-rule":
s.fillEvenOdd = p.fillEvenOdd
case "clip-rule":
s.clipEvenOdd = p.clipEvenOdd
case "stroke-width":
s.strokeWidth = p.strokeWidth
case "stroke-miterlimit":
s.miterLimit = p.miterLimit
case "stroke-linecap":
s.cap = p.cap
case "stroke-linejoin":
s.join = p.join
case "stroke-dasharray":
s.dashes = p.dashes
case "stroke-dashoffset":
s.dashOffset = p.dashOffset
case "color":
s.color, s.colorSet = p.color, p.colorSet
case "visibility":
s.visible = p.visible
case "paint-order":
s.strokeFirst = p.strokeFirst
case "opacity":
s.opacity = p.opacity
case "display":
s.display = p.display
case "clip-path":
s.clipPath = p.clipPath
case "mask":
s.mask = p.mask
case "mask-type":
s.maskAlpha = p.maskAlpha
case "stop-color":
s.stopColor = p.stopColor
case "stop-opacity":
s.stopOpacity = p.stopOpacity
case "font":
s.fontFamily, s.fontSize, s.fontWeight, s.italic = p.fontFamily, p.fontSize, p.fontWeight, p.italic
case "font-family":
s.fontFamily = p.fontFamily
case "font-size":
s.fontSize = p.fontSize
case "font-weight":
s.fontWeight = p.fontWeight
case "font-style":
s.italic = p.italic
case "letter-spacing":
s.letterSpacing = p.letterSpacing
case "text-anchor":
s.anchor = p.anchor
case "dominant-baseline":
s.baseline = p.baseline
case "alignment-baseline":
s.align = p.align
case "white-space":
s.preserve = p.preserve
case "marker":
s.markerStart, s.markerMid, s.markerEnd = p.markerStart, p.markerMid, p.markerEnd
case "marker-start":
s.markerStart = p.markerStart
case "marker-mid":
s.markerMid = p.markerMid
case "marker-end":
s.markerEnd = p.markerEnd
case "overflow":
s.overflow = p.overflow
}
}
// strokeFirst reports whether a paint-order paints the stroke before the
// fill.
func strokeFirst(v string) bool {
for _, f := range strings.Fields(v) {
switch f {
case "stroke":
return true
case "fill":
return false
}
}
return false
}
// urlID returns the id url(#id) refers to.
func urlID(v string) string {
v = strings.TrimSpace(v)
if !strings.HasPrefix(v, "url(") {
return ""
}
end := strings.IndexByte(v, ')')
if end < 0 {
return ""
}
ref := strings.Trim(strings.TrimSpace(v[4:end]), `"'`)
if !strings.HasPrefix(ref, "#") {
return ""
}
return ref[1:]
}
func parsePaint(v string) (paintSpec, bool) {
switch {
case v == "none":
return paintSpec{kind: specNone}, true
case strings.EqualFold(v, "currentColor"):
return paintSpec{kind: specCurrent}, true
case v == "context-fill":
return paintSpec{kind: specContextFill}, true
case v == "context-stroke":
return paintSpec{kind: specContextStroke}, true
case strings.HasPrefix(v, "url("):
id := urlID(v)
if id == "" {
return paintSpec{}, false
}
p := paintSpec{kind: specURL, id: id}
if rest := strings.TrimSpace(v[strings.IndexByte(v, ')')+1:]); rest != "" {
fb, ok := parsePaint(rest)
if !ok || fb.kind >= specURL {
return paintSpec{}, false
}
p.fallback, p.color = fb.kind, fb.color
}
return p, true
}
c, ok := parseColor(v)
return paintSpec{kind: specColor, color: c}, ok
}
// parseColor parses a CSS color: a name, #rgb, #rgba, #rrggbb, #rrggbbaa,
// rgb(), rgba(), hsl(), hsla() or transparent.
func parseColor(v string) (rgba, bool) {
v = strings.TrimSpace(v)
// An ICC color follows the sRGB one, which is all that is drawn.
if i := strings.Index(v, "icc-color("); i > 0 {
v = strings.TrimSpace(v[:i])
}
if v == "" {
return rgba{}, false
}
if v[0] == '#' {
return parseHex(v[1:])
}
lower := strings.ToLower(v)
if open := strings.IndexByte(lower, '('); open > 0 && strings.HasSuffix(lower, ")") {
name, args := lower[:open], lower[open+1:len(lower)-1]
switch name {
case "rgb", "rgba":
return parseRGB(args)
case "hsl", "hsla":
return parseHSL(args)
}
return rgba{}, false
}
if lower == "transparent" {
return rgba{}, true
}
if c, ok := namedColors[lower]; ok {
return rgba{float64(c>>16) / 255, float64(c>>8&0xff) / 255, float64(c&0xff) / 255, 1}, true
}
return rgba{}, false
}
func parseHex(h string) (rgba, bool) {
var d [8]float64
for i := range len(h) {
c := h[i]
switch {
case i >= len(d):
return rgba{}, false
case c >= '0' && c <= '9':
d[i] = float64(c - '0')
case c >= 'a' && c <= 'f':
d[i] = float64(c - 'a' + 10)
case c >= 'A' && c <= 'F':
d[i] = float64(c - 'A' + 10)
default:
return rgba{}, false
}
}
switch len(h) {
case 3, 4:
c := rgba{d[0] * 17 / 255, d[1] * 17 / 255, d[2] * 17 / 255, 1}
if len(h) == 4 {
c.a = d[3] * 17 / 255
}
return c, true
case 6, 8:
c := rgba{(d[0]*16 + d[1]) / 255, (d[2]*16 + d[3]) / 255, (d[4]*16 + d[5]) / 255, 1}
if len(h) == 8 {
c.a = (d[6]*16 + d[7]) / 255
}
return c, true
}
return rgba{}, false
}
// colorArgs splits the arguments of rgb() or hsl(), separated by commas or
// spaces, with the alpha after a slash in the latter syntax.
func colorArgs(s string) []string {
s = strings.ReplaceAll(s, "/", " / ")
f := strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == ' ' || r == '\t' || r == '\n' || r == '\r' })
if len(f) == 5 && f[3] == "/" {
return []string{f[0], f[1], f[2], f[4]}
}
for _, a := range f {
if a == "/" {
return nil
}
}
return f
}
func parseRGB(s string) (rgba, bool) {
args := colorArgs(s)
if len(args) != 3 && len(args) != 4 {
return rgba{}, false
}
var c [4]float64
c[3] = 1
for i, a := range args {
pct := strings.HasSuffix(a, "%")
n, ok := parseNumber(strings.TrimSuffix(a, "%"))
if !ok {
return rgba{}, false
}
switch {
case i == 3 && pct:
c[i] = n / 100
case i == 3:
c[i] = n
case pct:
c[i] = n / 100
default:
c[i] = n / 255
}
c[i] = math.Max(0, math.Min(1, c[i]))
}
return rgba{c[0], c[1], c[2], c[3]}, true
}
func parseHSL(s string) (rgba, bool) {
args := colorArgs(s)
if len(args) != 3 && len(args) != 4 {
return rgba{}, false
}
h := args[0]
scale := 1.0
switch {
case strings.HasSuffix(h, "deg"):
h = h[:len(h)-3]
case strings.HasSuffix(h, "grad"):
h, scale = h[:len(h)-4], 0.9
case strings.HasSuffix(h, "rad"):
h, scale = h[:len(h)-3], 180/math.Pi
case strings.HasSuffix(h, "turn"):
h, scale = h[:len(h)-4], 360
}
hue, ok := parseNumber(h)
if !ok {
return rgba{}, false
}
var v [3]float64
v[2] = 1
for i, a := range args[1:] {
pct := strings.HasSuffix(a, "%")
n, ok := parseNumber(strings.TrimSuffix(a, "%"))
if !ok || i < 2 && !pct {
return rgba{}, false
}
if pct {
n /= 100
}
v[i] = math.Max(0, math.Min(1, n))
}
hue = math.Mod(hue*scale, 360)
if hue < 0 {
hue += 360
}
sat, light := v[0], v[1]
f := func(n float64) float64 {
k := math.Mod(n+hue/30, 12)
a := sat * math.Min(light, 1-light)
return light - a*math.Max(-1, math.Min(math.Min(k-3, 9-k), 1))
}
return rgba{f(0), f(8), f(4), v[2]}, true
}
func parseNumber(v string) (float64, bool) {
p := scanner{s: strings.TrimSpace(v)}
n, ok := p.number()
return n, ok && p.done()
}
// parseOpacity parses a number or percentage, clamped to [0, 1], or
// returns old.
func parseOpacity(v string, old float64) float64 {
pct := strings.HasSuffix(v, "%")
n, ok := parseNumber(strings.TrimSuffix(v, "%"))
if !ok {
return old
}
if pct {
n /= 100
}
return math.Max(0, math.Min(1, n))
}
// parseLength parses a length: a number with an optional unit, in pixels,
// or a percentage of base.
func parseLength(v string, base float64) (float64, bool) {
p := scanner{s: strings.TrimSpace(v)}
n, ok := p.number()
if !ok {
return 0, false
}
switch strings.ToLower(p.s[p.i:]) {
case "", "px":
return n, true
case "%":
return n * base / 100, true
case "pt":
return n * 4 / 3, true
case "pc":
return n * 16, true
case "in":
return n * 96, true
case "cm":
return n * 96 / 2.54, true
case "mm":
return n * 96 / 25.4, true
case "q":
return n * 96 / 101.6, true
case "em", "rem":
return n * 16, true
case "ex":
return n * 8, true
}
return 0, false
}
// parseDashes parses a dash array: nil for a solid line, as none or an
// array in error asks, and of even length otherwise.
func parseDashes(v string, diag float64) []float64 {
if v == "none" {
return nil
}
var out []float64
var total float64
for _, f := range strings.FieldsFunc(v, func(r rune) bool { return r == ',' || r == ' ' || r == '\t' || r == '\n' || r == '\r' }) {
l, ok := parseLength(f, diag)
if !ok || l < 0 {
return nil
}
out = append(out, l)
total += l
}
if total <= 0 {
return nil
}
if len(out)%2 == 1 {
out = append(out, out...)
}
return out
}
// aspect is a preserveAspectRatio: how a viewBox fits its viewport.
type aspect struct {
none bool
ax, ay float64 // where it aligns: 0 at the start, 0.5 in the middle, 1 at the end
slice bool
}
func parseAspect(v string) aspect {
a := aspect{ax: 0.5, ay: 0.5}
f := strings.Fields(v)
if len(f) > 0 && f[0] == "defer" {
f = f[1:]
}
if len(f) == 0 {
return a
}
if f[0] == "none" {
a.none = true
return a
}
pos := map[string]float64{"Min": 0, "Mid": 0.5, "Max": 1}
al := f[0]
if len(al) != 8 || al[0] != 'x' || al[4] != 'Y' {
return a
}
x, okX := pos[al[1:4]]
y, okY := pos[al[5:8]]
if !okX || !okY {
return a
}
a.ax, a.ay = x, y
a.slice = len(f) > 1 && f[1] == "slice"
return a
}
// viewBoxTransform maps a viewBox to a viewport w×h as a says.
func viewBoxTransform(vb box, a aspect, w, h float64) matrix {
if vb.w <= 0 || vb.h <= 0 {
return identity
}
sx, sy := w/vb.w, h/vb.h
if a.none {
return matrix{sx, 0, 0, sy, -vb.x * sx, -vb.y * sy}
}
s := math.Min(sx, sy)
if a.slice {
s = math.Max(sx, sy)
}
return matrix{s, 0, 0, s, -vb.x*s + (w-vb.w*s)*a.ax, -vb.y*s + (h-vb.h*s)*a.ay}
}
func parseViewBox(v string) (box, bool) {
n := numbers(v)
if len(n) != 4 || n[2] <= 0 || n[3] <= 0 {
return box{}, false
}
return box{n[0], n[1], n[2], n[3]}, true
}
+194
View File
@@ -0,0 +1,194 @@
// Package svg parses SVG documents and draws them into pixels, for the
// icons and pictures of package ui, in Go alone.
//
// It draws paths and the basic shapes, groups, nested svg elements, use
// and symbol elements, transforms, fills and strokes (with joins, caps
// and dashes) of colors, currentColor and linear and radial gradients,
// opacity, clip paths and masks, markers, text with the Fonts of the
// caller, and style sheets of type, class, id and :root selectors
// joined by descendant and child combinators, with custom properties and
// prefers-color-scheme media queries. Embedded images, patterns and
// filters are not drawn: Unsupported lists what a document has that is
// not. ParseBasic leaves out text, markers and style sheets, so that a
// program whose SVGs are its own simple icons does not link them.
package svg
import (
"image"
"image/color"
"slices"
"strings"
"sync"
)
// renderers keeps renderers and their memory between drawings.
var renderers = sync.Pool{New: func() any { return new(renderer) }}
// Doc is a parsed SVG document. Draw may draw it from any goroutine.
type Doc struct {
root *node
// dark is the document in the dark color scheme, when its style
// sheets ask for prefers-color-scheme.
dark *node
view box
par aspect
w, h float64
// current is true when something is painted with currentColor.
current bool
unsupported []string
// ext draws its text, for a document Parse parsed.
ext *extras
}
// extras are what Parse does that ParseBasic does not. A program links
// them only when it calls Parse: each app with native UI parses icons
// with ParseBasic, and most never draw text or markers from an SVG.
type extras struct {
text func(c *compiler, e *elem, st *style) *textNode
drawText func(r *renderer, t *textNode, m matrix, dst *layer, alpha float64)
markers func(c *compiler, e *elem, pa *path, st *style, sh *shape) []*node
}
// Options are how Draw draws a document.
type Options struct {
// Current is the color currentColor stands for where the document
// does not set the color property.
Current color.NRGBA
// Stretch stretches the viewBox to the pixels, whatever the
// document's preserveAspectRatio says.
Stretch bool
// Dark draws the document in the dark color scheme, which media
// queries for prefers-color-scheme: dark match; the light one
// otherwise.
Dark bool
// Fonts lays out and rasterizes text; without it, no text is drawn.
Fonts Fonts
}
// Parse parses an SVG document.
func Parse(data []byte) (*Doc, error) {
root, err := parseXML(data)
if err != nil {
return nil, err
}
ext := &extras{text: (*compiler).text, drawText: (*renderer).text, markers: (*compiler).markers}
rep := &report{}
sh := parseSheets(root, rep)
cascade(root, sh, false, rep)
d := newCompiler(root, rep, ext).doc()
if sh.scheme {
cascade(root, sh, true, rep)
dark := newCompiler(root, rep, ext).doc()
d.dark, d.current = dark.root, d.current || dark.current
if d.dark == nil {
d.dark = &node{m: identity} // nothing to draw
}
}
reportElems(root, rep)
slices.Sort(rep.items)
d.unsupported, d.ext = rep.items, ext
return d, nil
}
// ParseBasic parses an SVG document as Parse does, but for its text,
// markers and style elements, which it leaves out (Unsupported does not
// list them), and the var() functions of its style attributes, which it
// treats as errors. It is for icons that are part of the program: those
// do without, and a program that never calls Parse links none of them.
func ParseBasic(data []byte) (*Doc, error) {
root, err := parseXML(data)
if err != nil {
return nil, err
}
rep := &report{}
walk(root, func(e *elem) {
if e.name == "#text" {
return
}
for name, v := range e.attrs {
if properties[name] {
e.props = append(e.props, decl{name, strings.TrimSpace(v)})
}
}
if s, ok := e.attrs["style"]; ok {
e.props = append(e.props, parseDecls(s, rep)...)
}
})
d := newCompiler(root, rep, nil).doc()
reportElems(root, rep)
slices.Sort(rep.items)
d.unsupported = rep.items
return d, nil
}
// Unsupported lists what the document has that Draw leaves out: elements
// as "<pattern>", properties as "filter", at-rules as "@font-face", and
// selectors as "selector a + b". It is empty when Draw draws all of it.
func (d *Doc) Unsupported() []string { return slices.Clone(d.unsupported) }
// UsesColorScheme reports whether the document draws differently in the
// dark color scheme (Options.Dark).
func (d *Doc) UsesColorScheme() bool { return d.dark != nil }
// Size returns the document's size in pixels: its width and height, or
// those of its viewBox.
func (d *Doc) Size() (w, h float64) { return d.w, d.h }
// UsesCurrentColor reports whether the color Draw takes for currentColor
// changes what it draws.
func (d *Doc) UsesCurrentColor() bool { return d.current }
// Draw draws the document over the pixels of dst, fitting its viewBox in
// them as its preserveAspectRatio says, or as o says.
func (d *Doc) Draw(dst *image.RGBA, o Options) {
b := dst.Bounds()
a := d.par
if o.Stretch {
a = aspect{none: true}
}
d.draw(dst, &o, viewBoxTransform(d.view, a, float64(b.Dx()), float64(b.Dy())))
}
// DrawRotated draws the document as Draw does in a box w×h pixels at the
// center of dst, turned by degrees clockwise around it.
func (d *Doc) DrawRotated(dst *image.RGBA, o Options, w, h, degrees float64) {
b := dst.Bounds()
m := translate(float64(b.Dx())/2, float64(b.Dy())/2).mul(rotation(degrees)).mul(translate(-w/2, -h/2))
d.draw(dst, &o, m.mul(viewBoxTransform(d.view, d.par, w, h)))
}
func (d *Doc) draw(dst *image.RGBA, o *Options, m matrix) {
b := dst.Bounds()
w, h := b.Dx(), b.Dy()
root := d.root
if o.Dark && d.dark != nil {
root = d.dark
}
if w <= 0 || h <= 0 || root == nil {
return
}
r := renderers.Get().(*renderer)
defer renderers.Put(r)
if r.w != w || r.h != h {
r.w, r.h, r.free = w, h, nil
}
current := o.Current
r.current = rgba{float64(current.R) / 255, float64(current.G) / 255, float64(current.B) / 255, float64(current.A) / 255}
r.fonts, r.ext = o.Fonts, d.ext
defer func() { r.fonts, r.ext = nil, nil }()
l := r.layer()
defer r.release(l)
r.node(root, m, l, 1)
dr := l.dirty
for y := dr.Min.Y; y < dr.Max.Y; y++ {
src := l.pix[(y*w+dr.Min.X)*4 : (y*w+dr.Max.X)*4]
out := dst.Pix[dst.PixOffset(b.Min.X+dr.Min.X, b.Min.Y+y):]
for i := 0; i < len(src); i += 4 {
if a := src[i+3]; a == 255 {
copy(out[i:i+4], src[i:i+4])
} else if a > 0 {
over(out[i:i+4], uint32(src[i]), uint32(src[i+1]), uint32(src[i+2]), uint32(a))
}
}
}
}
+862
View File
@@ -0,0 +1,862 @@
package svg
import (
"fmt"
"image"
"image/color"
"math"
"slices"
"strings"
"testing"
)
var red = color.NRGBA{255, 0, 0, 255}
func draw(t *testing.T, src string, w, h int) *image.RGBA {
t.Helper()
d, err := Parse([]byte(src))
if err != nil {
t.Fatalf("Parse: %v", err)
}
img := image.NewRGBA(image.Rect(0, 0, w, h))
d.Draw(img, Options{Current: red})
return img
}
func at(img *image.RGBA, x, y int) color.RGBA { return img.RGBAAt(x, y) }
// alphaSum is the total coverage of an image, in pixels.
func alphaSum(img *image.RGBA) float64 {
var s float64
for i := 3; i < len(img.Pix); i += 4 {
s += float64(img.Pix[i]) / 255
}
return s
}
func TestFill(t *testing.T) {
img := draw(t, `<svg viewBox="0 0 10 10"><rect x="2" y="2" width="6" height="6" fill="#00f"/></svg>`, 20, 20)
if c := at(img, 10, 10); c != (color.RGBA{0, 0, 255, 255}) {
t.Errorf("inside: %v", c)
}
if c := at(img, 4, 4); c.A != 255 {
t.Errorf("the first pixel inside: %v", c)
}
if c := at(img, 3, 3); c.A != 0 {
t.Errorf("outside: %v", c)
}
if got := alphaSum(img); math.Abs(got-144) > 0.5 {
t.Errorf("coverage %v, want 144", got)
}
}
func TestPathSyntax(t *testing.T) {
// The same square, written in the ways path data allows.
want := draw(t, `<svg viewBox="0 0 10 10"><path d="M1 1 L9 1 L9 9 L1 9 Z"/></svg>`, 10, 10)
for _, d := range []string{
"M1,1L9,1L9,9L1,9Z",
"M1 1h8v8h-8z",
"m1 1 8 0 0 8-8 0z",
"M1 1 9 1 9 9 1 9z",
"M+1.0e0,1.L9,1,9,9,1,9Z",
"M1 1H9V9H1Z M20 20", // a lone move draws nothing
} {
got := draw(t, `<svg viewBox="0 0 10 10"><path d="`+d+`"/></svg>`, 10, 10)
if string(got.Pix) != string(want.Pix) {
t.Errorf("%q draws another shape", d)
}
}
// Path data in error draws up to the error.
part := draw(t, `<svg viewBox="0 0 10 10"><path d="M1 1H9V9H1Z M0 0 L5 x"/></svg>`, 10, 10)
if string(part.Pix) != string(want.Pix) {
t.Error("path data in error does not draw what comes before the error")
}
if img := draw(t, `<svg viewBox="0 0 10 10"><path d="L1 1 9 9 1 9Z"/></svg>`, 10, 10); alphaSum(img) != 0 {
t.Error("path data that does not start with a move draws")
}
}
func TestArcs(t *testing.T) {
circle := draw(t, `<svg viewBox="0 0 20 20"><circle cx="10" cy="10" r="8"/></svg>`, 40, 40)
arcs := draw(t, `<svg viewBox="0 0 20 20"><path d="M2 10a8 8 0 1 1 16 0A8 8 0 1 1 2 10z"/></svg>`, 40, 40)
want := math.Pi * 16 * 16
for name, img := range map[string]*image.RGBA{"circle": circle, "arcs": arcs} {
if got := alphaSum(img); math.Abs(got-want) > want*0.01 {
t.Errorf("%s covers %v pixels, want %v", name, got, want)
}
}
// Flags packed without separators, and radii too small to reach.
packed := draw(t, `<svg viewBox="0 0 20 20"><path d="M2 10a1 1 0 1116 0a1,1,0,1,1-16,0z"/></svg>`, 40, 40)
if got := alphaSum(packed); math.Abs(got-want) > want*0.01 {
t.Errorf("packed arcs cover %v pixels, want %v", got, want)
}
}
func TestFillRule(t *testing.T) {
const rings = `M0 0H10V10H0Z M2 2H8V8H2Z`
nz := draw(t, `<svg viewBox="0 0 10 10"><path d="`+rings+`"/></svg>`, 10, 10)
eo := draw(t, `<svg viewBox="0 0 10 10"><path fill-rule="evenodd" d="`+rings+`"/></svg>`, 10, 10)
if at(nz, 5, 5).A != 255 {
t.Error("the non-zero rule does not fill contours that turn the same way")
}
if at(eo, 5, 5).A != 0 || at(eo, 1, 1).A != 255 {
t.Errorf("the even-odd rule: hole %v, ring %v", at(eo, 5, 5), at(eo, 1, 1))
}
}
func TestStrokeCaps(t *testing.T) {
line := func(cap string) *image.RGBA {
return draw(t, `<svg viewBox="0 0 20 10"><path d="M5 5H15" stroke="#000" stroke-width="4" stroke-linecap="`+cap+`"/></svg>`, 20, 10)
}
butt, square, round := line("butt"), line("square"), line("round")
if got := alphaSum(butt); math.Abs(got-40) > 0.5 {
t.Errorf("butt caps cover %v, want 40", got)
}
if got := alphaSum(square); math.Abs(got-56) > 0.5 {
t.Errorf("square caps cover %v, want 56", got)
}
if got, want := alphaSum(round), 40+4*math.Pi; math.Abs(got-want) > 0.5 {
t.Errorf("round caps cover %v, want %v", got, want)
}
if at(butt, 4, 5).A != 0 || at(square, 4, 5).A != 255 {
t.Error("caps do not end where they should")
}
// A subpath of no length is a dot with round caps.
dot := draw(t, `<svg viewBox="0 0 10 10"><path d="M5 5z" stroke="#000" stroke-width="4" stroke-linecap="round"/></svg>`, 10, 10)
if got, want := alphaSum(dot), 4*math.Pi; math.Abs(got-want) > 0.3 {
t.Errorf("a dot covers %v, want %v", got, want)
}
}
func TestStrokeJoins(t *testing.T) {
corner := func(join string) *image.RGBA {
return draw(t, `<svg viewBox="0 0 20 20"><path d="M2 10H10V18" fill="none" stroke="#000" stroke-width="4" stroke-linejoin="`+join+`"/></svg>`, 20, 20)
}
miter, bevel, round := corner("miter"), corner("bevel"), corner("round")
// The outer corner of the turn is at (12, 8): the miter reaches it,
// the bevel cuts it off, the round join rounds it.
if at(miter, 11, 8).A != 255 {
t.Errorf("the miter does not fill the corner: %v", at(miter, 11, 8))
}
if at(bevel, 11, 8).A > 128 {
t.Errorf("the bevel fills the corner: %v", at(bevel, 11, 8))
}
m, b, r := alphaSum(miter), alphaSum(bevel), alphaSum(round)
if !(m > r && r > b) {
t.Errorf("coverage of miter %v, round %v, bevel %v", m, r, b)
}
// A sharp turn beyond the miter limit is beveled.
sharp := func(limit string) float64 {
return alphaSum(draw(t, `<svg viewBox="0 0 40 40"><path d="M2 20L38 22L2 24" fill="none" stroke="#000" stroke-width="2" stroke-miterlimit="`+limit+`"/></svg>`, 40, 40))
}
if sharp("4") >= sharp("100") {
t.Error("the miter limit does not bevel a sharp turn")
}
}
func TestDashes(t *testing.T) {
img := draw(t, `<svg viewBox="0 0 20 4"><path d="M0 2H20" stroke="#000" stroke-width="2" stroke-dasharray="2 3"/></svg>`, 20, 4)
for x, want := range []uint8{255, 255, 0, 0, 0, 255, 255, 0, 0, 0} {
if got := at(img, x, 2).A; got != want {
t.Errorf("pixel %d: %d, want %d", x, got, want)
}
}
shifted := draw(t, `<svg viewBox="0 0 20 4"><path d="M0 2H20" stroke="#000" stroke-width="2" stroke-dasharray="2 3" stroke-dashoffset="1"/></svg>`, 20, 4)
if at(shifted, 0, 2).A != 255 || at(shifted, 1, 2).A != 0 || at(shifted, 4, 2).A != 255 {
t.Error("the dash offset does not shift the dashes")
}
}
func TestTransforms(t *testing.T) {
plain := draw(t, `<svg viewBox="0 0 20 20"><rect x="5" y="0" width="5" height="5"/></svg>`, 20, 20)
for _, rect := range []string{
`<rect width="5" height="5" transform="translate(5)"/>`,
`<rect width="5" height="5" transform="translate(5 0)"/>`,
`<rect width="5" height="5" transform=" matrix(1,0,0,1,5,0) "/>`,
`<rect width="10" height="10" transform="translate(5 0) scale(0.5)"/>`,
`<rect width="5" height="5" transform="rotate(90 5 5)"/>`,
`<g transform="translate(5)"><rect width="10" height="5" transform="scale(.5 1)"/></g>`,
} {
got := draw(t, `<svg viewBox="0 0 20 20">`+rect+`</svg>`, 20, 20)
if alphaSum(got) == 0 || string(got.Pix) != string(plain.Pix) {
t.Errorf("%s moves the rectangle elsewhere", rect)
}
}
// A transform in error transforms nothing.
got := draw(t, `<svg viewBox="0 0 20 20"><rect x="5" width="5" height="5" transform="translate(5 0"/></svg>`, 20, 20)
if string(got.Pix) != string(plain.Pix) {
t.Error("a transform in error moves the rectangle")
}
}
func TestCurrentColor(t *testing.T) {
img := draw(t, `<svg viewBox="0 0 2 1"><rect width="1" height="1" fill="currentColor"/><g color="#0f0"><rect x="1" width="1" height="1" fill="currentColor"/></g></svg>`, 2, 1)
if c := at(img, 0, 0); c != (color.RGBA{255, 0, 0, 255}) {
t.Errorf("currentColor is %v, not the color it is drawn with", c)
}
if c := at(img, 1, 0); c != (color.RGBA{0, 255, 0, 255}) {
t.Errorf("currentColor is %v, not the color property", c)
}
}
func TestColors(t *testing.T) {
for v, want := range map[string]color.RGBA{
"#f00": {255, 0, 0, 255},
"#FF0000": {255, 0, 0, 255},
"rgb(0, 0, 255)": {0, 0, 255, 255},
"rgb(0 0 100%)": {0, 0, 255, 255},
"rgba(0,0,255,0.5)": {0, 0, 128, 128},
"rgb(0 0 255 / 50%)": {0, 0, 128, 128},
"#0000ff80": {0, 0, 128, 128},
"hsl(120, 100%, 50%)": {0, 255, 0, 255},
"hsl(240deg 100% 50%)": {0, 0, 255, 255},
"DarkOrange": {255, 140, 0, 255},
"transparent": {},
"#ff0000 icc-color(x, 1)": {255, 0, 0, 255},
"none": {},
"url(#nothing) #00f": {0, 0, 255, 255},
"url(#nothing)": {},
"not a color": {0, 0, 0, 255}, // ignored: black, the initial fill
"rgb(0,0,0": {0, 0, 0, 255},
"#12345": {0, 0, 0, 255},
"hsl(120, 100, 50)": {0, 0, 0, 255},
"rgba(255, 255, 255, 0.0)": {},
} {
img := draw(t, `<svg viewBox="0 0 1 1"><rect width="1" height="1" fill="`+v+`"/></svg>`, 1, 1)
if got := at(img, 0, 0); got != want {
t.Errorf("fill %q: %v, want %v", v, got, want)
}
}
}
func TestLinearGradient(t *testing.T) {
img := draw(t, `<svg viewBox="0 0 100 10">
<defs><linearGradient id="g"><stop offset="0" stop-color="#f00"/><stop offset="100%" stop-color="#00f"/></linearGradient></defs>
<rect width="100" height="10" fill="url(#g)"/></svg>`, 100, 10)
left, mid, right := at(img, 0, 5), at(img, 50, 5), at(img, 99, 5)
if left.R < 250 || left.B > 5 || right.B < 250 || right.R > 5 {
t.Errorf("ends: %v, %v", left, right)
}
if mid.R < 115 || mid.R > 140 || mid.B < 115 || mid.B > 140 {
t.Errorf("middle: %v", mid)
}
// Stops and coordinates inherited through href, in user space, and
// spread.
img = draw(t, `<svg viewBox="0 0 100 10">
<linearGradient id="a"><stop offset="0" stop-color="#000"/><stop offset="1" stop-color="#fff"/></linearGradient>
<linearGradient id="b" href="#a" gradientUnits="userSpaceOnUse" x1="0" x2="50" spreadMethod="reflect"/>
<rect width="100" height="10" fill="url(#b)"/></svg>`, 100, 10)
if c := at(img, 49, 5); c.R < 245 {
t.Errorf("at the end of the gradient: %v", c)
}
if c := at(img, 99, 5); c.R > 10 {
t.Errorf("reflected: %v", c)
}
}
func TestRadialGradient(t *testing.T) {
img := draw(t, `<svg viewBox="0 0 20 20">
<radialGradient id="g"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#000"/></radialGradient>
<rect width="20" height="20" fill="url(#g)"/></svg>`, 20, 20)
center, edge, corner := at(img, 10, 10), at(img, 10, 0), at(img, 0, 0)
if center.R < 230 || edge.R > 30 || corner != (color.RGBA{0, 0, 0, 255}) {
t.Errorf("center %v, edge %v, corner %v", center, edge, corner)
}
// A focal point off center.
img = draw(t, `<svg viewBox="0 0 20 20">
<radialGradient id="g" fx="0.25"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#000"/></radialGradient>
<rect width="20" height="20" fill="url(#g)"/></svg>`, 20, 20)
if at(img, 5, 10).R < 230 || at(img, 15, 10).R > at(img, 5, 10).R {
t.Errorf("focal point: %v, %v", at(img, 5, 10), at(img, 15, 10))
}
}
func TestGroupOpacity(t *testing.T) {
const rects = `<rect width="6" height="10"/><rect x="4" width="6" height="10"/>`
group := draw(t, `<svg viewBox="0 0 10 10"><g opacity="0.5">`+rects+`</g></svg>`, 10, 10)
each := draw(t, `<svg viewBox="0 0 10 10"><g fill-opacity="0.5">`+rects+`</g></svg>`, 10, 10)
if a, b := at(group, 5, 5).A, at(group, 1, 5).A; a != b || a < 126 || a > 129 {
t.Errorf("group opacity: overlap %d, alone %d", a, b)
}
if at(each, 5, 5).A <= at(each, 1, 5).A {
t.Error("shapes with their own opacity do not add up where they overlap")
}
// Fill and stroke of one shape with opacity.
img := draw(t, `<svg viewBox="0 0 10 10"><rect x="2" y="2" width="6" height="6" stroke="#000" stroke-width="2" opacity="0.5"/></svg>`, 10, 10)
if a, b := at(img, 2, 2).A, at(img, 5, 5).A; a != b {
t.Errorf("an element's opacity: stroke over fill %d, fill %d", a, b)
}
}
func TestClipPath(t *testing.T) {
img := draw(t, `<svg viewBox="0 0 20 20">
<clipPath id="c"><circle cx="10" cy="10" r="8"/></clipPath>
<rect width="20" height="20" clip-path="url(#c)"/></svg>`, 20, 20)
if at(img, 10, 10).A != 255 || at(img, 0, 0).A != 0 {
t.Errorf("clipped: center %v, corner %v", at(img, 10, 10), at(img, 0, 0))
}
if got, want := alphaSum(img), math.Pi*64; math.Abs(got-want) > want*0.02 {
t.Errorf("clipped coverage %v, want %v", got, want)
}
// objectBoundingBox units, with an even-odd clip rule.
img = draw(t, `<svg viewBox="0 0 20 20">
<clipPath id="c" clipPathUnits="objectBoundingBox"><path clip-rule="evenodd" d="M0 0H1V1H0Z M.25 .25H.75V.75H.25Z"/></clipPath>
<g clip-path="url(#c)"><rect x="4" y="4" width="12" height="12"/></g></svg>`, 20, 20)
if at(img, 10, 10).A != 0 || at(img, 5, 5).A != 255 || at(img, 2, 2).A != 0 {
t.Errorf("box clip: hole %v, ring %v, outside %v", at(img, 10, 10), at(img, 5, 5), at(img, 2, 2))
}
}
func TestMask(t *testing.T) {
img := draw(t, `<svg viewBox="0 0 20 10">
<mask id="m" maskUnits="userSpaceOnUse" x="0" y="0" width="20" height="10">
<rect width="10" height="10" fill="#fff"/><rect x="10" width="10" height="10" fill="#000"/>
</mask>
<rect width="20" height="10" fill="#00f" mask="url(#m)"/></svg>`, 20, 10)
if at(img, 5, 5).A != 255 || at(img, 15, 5).A != 0 {
t.Errorf("masked: white %v, black %v", at(img, 5, 5), at(img, 15, 5))
}
}
func TestStyleSheets(t *testing.T) {
img := draw(t, `<svg viewBox="0 0 4 1">
<style><![CDATA[
/* Illustrator writes classes */
.a { fill: #00f }
rect.b, .c { fill: #0f0 !important }
#d { fill: #f0f }
@media print { .a { fill: #fff } }
g > rect { fill: #fff }
]]></style>
<rect class="a" width="1" height="1"/>
<rect class="a b" x="1" width="1" height="1"/>
<rect class="a" id="d" x="2" width="1" height="1"/>
<rect class="a" x="3" width="1" height="1" fill="#f00" style="fill: #ff0"/>
</svg>`, 4, 1)
for x, want := range []color.RGBA{{0, 0, 255, 255}, {0, 255, 0, 255}, {255, 0, 255, 255}, {255, 255, 0, 255}} {
if got := at(img, x, 0); got != want {
t.Errorf("rect %d: %v, want %v", x, got, want)
}
}
}
func TestUse(t *testing.T) {
img := draw(t, `<svg viewBox="0 0 20 10">
<defs><rect id="r" width="5" height="5"/>
<symbol id="s" viewBox="0 0 1 1"><rect width="1" height="1" fill="#00f"/></symbol></defs>
<use href="#r" x="5"/>
<use xlink:href="#s" x="10" y="0" width="5" height="5" xmlns:xlink="http://www.w3.org/1999/xlink"/>
<use href="#loop" id="loop"/>
</svg>`, 20, 10)
if at(img, 1, 1).A != 0 || at(img, 6, 1).A != 255 {
t.Error("use does not draw its element where it says")
}
if c := at(img, 12, 2); c != (color.RGBA{0, 0, 255, 255}) {
t.Errorf("a symbol: %v", c)
}
if at(img, 12, 7).A != 0 {
t.Error("a symbol draws outside its viewport")
}
}
func TestDisplayAndVisibility(t *testing.T) {
img := draw(t, `<svg viewBox="0 0 3 1">
<rect width="1" height="1" display="none"/>
<g visibility="hidden"><rect x="1" width="1" height="1"/><rect x="2" width="1" height="1" visibility="visible"/></g>
</svg>`, 3, 1)
if at(img, 0, 0).A != 0 || at(img, 1, 0).A != 0 || at(img, 2, 0).A != 255 {
t.Errorf("display none %v, hidden %v, visible %v", at(img, 0, 0), at(img, 1, 0), at(img, 2, 0))
}
}
func TestSizeAndAspect(t *testing.T) {
for src, want := range map[string][2]float64{
`<svg width="24" height="24" viewBox="0 0 48 48"/>`: {24, 24},
`<svg viewBox="0 0 48 24"/>`: {48, 24},
`<svg width="10" viewBox="0 0 48 24"/>`: {10, 5},
`<svg width="100%" height="100%" viewBox="0 0 8 4"/>`: {8, 4},
`<svg width="1in" height="12pt"/>`: {96, 16},
`<svg/>`: {300, 150},
} {
d, err := Parse([]byte(src))
if err != nil {
t.Fatal(err)
}
if w, h := d.Size(); w != want[0] || h != want[1] {
t.Errorf("%s: %vx%v, want %vx%v", src, w, h, want[0], want[1])
}
}
// A wide viewBox in a square: centered, unless aligned or stretched.
const wide = `<rect width="10" height="5"/></svg>`
mid := draw(t, `<svg viewBox="0 0 10 5">`+wide, 10, 10)
if at(mid, 5, 1).A != 0 || at(mid, 5, 5).A != 255 || at(mid, 5, 8).A != 0 {
t.Error("the viewBox is not centered")
}
top := draw(t, `<svg viewBox="0 0 10 5" preserveAspectRatio="xMinYMin meet">`+wide, 10, 10)
if at(top, 5, 1).A != 255 || at(top, 5, 8).A != 0 {
t.Error("the viewBox is not aligned to the top")
}
d, _ := Parse([]byte(`<svg viewBox="0 0 10 5">` + wide))
img := image.NewRGBA(image.Rect(0, 0, 10, 10))
d.Draw(img, Options{Current: red, Stretch: true})
if alphaSum(img) != 100 {
t.Error("the viewBox is not stretched")
}
}
func TestOldEditors(t *testing.T) {
// Illustrator's declarations, entities, namespaces and switch.
src := `<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [
<!ENTITY ns_svg "http://www.w3.org/2000/svg">
]>
<svg xmlns="&ns_svg;" xmlns:i="&ns_ai;" viewBox="0 0 10 10">
<switch>
<foreignObject requiredExtensions="&ns_ai;" x="0" y="0" width="1" height="1"/>
<g i:extraneous="self"><rect width="10" height="10" fill="#00f"/></g>
</switch>
<!-- caf` + "\xe9" + ` -->
</svg>`
img := draw(t, src, 10, 10)
if c := at(img, 5, 5); c != (color.RGBA{0, 0, 255, 255}) {
t.Errorf("drawn %v", c)
}
}
func TestErrors(t *testing.T) {
for _, src := range []string{``, `<html/>`, `<svg><rect`, `not xml`} {
if _, err := Parse([]byte(src)); err == nil {
t.Errorf("%q parses", src)
}
}
}
func TestIcons(t *testing.T) {
// A check mark stroked in currentColor, as icon sets draw them.
check := draw(t, checkIcon, 24, 24)
if c := at(check, 9, 16); c != (color.RGBA{255, 0, 0, 255}) {
t.Errorf("the check mark's corner: %v", c)
}
if at(check, 2, 2).A != 0 {
t.Error("the check mark covers its corner")
}
// A house filled in a viewBox above the origin, with a door cut out.
house := draw(t, `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960"><path fill-rule="evenodd" d="M160-120V-600L480-840L800-600V-120ZM400-120V-360H560V-120Z"/></svg>`, 24, 24)
if at(house, 12, 6).A != 255 || at(house, 6, 15).A != 255 || at(house, 12, 18).A != 0 || at(house, 2, 2).A != 0 {
t.Errorf("the house: roof %v, wall %v, door %v", at(house, 12, 6), at(house, 6, 15), at(house, 12, 18))
}
}
// TestParseBasic draws icons as Parse does, and leaves out text, markers
// and style sheets.
func TestParseBasic(t *testing.T) {
basic := func(src string) *image.RGBA {
t.Helper()
d, err := ParseBasic([]byte(src))
if err != nil {
t.Fatalf("ParseBasic: %v", err)
}
img := image.NewRGBA(image.Rect(0, 0, 24, 24))
d.Draw(img, Options{Current: red, Fonts: boxFonts{}})
return img
}
for _, src := range []string{
checkIcon,
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 3"/></svg>`,
`<svg viewBox="0 0 24 24"><g transform="rotate(20 12 12)" opacity=".5" style="fill: currentColor; stroke: blue"><rect x="4" y="4" width="16" height="16" rx="3"/></g></svg>`,
`<svg viewBox="0 0 24 24"><linearGradient id="g"><stop offset="0" stop-color="red"/><stop offset="1" stop-color="blue"/></linearGradient><clipPath id="c"><circle cx="12" cy="12" r="10"/></clipPath><rect width="24" height="24" fill="url(#g)" clip-path="url(#c)"/></svg>`,
} {
want := draw(t, src, 24, 24)
if got := basic(src); !slices.Equal(got.Pix, want.Pix) {
t.Errorf("ParseBasic draws differently from Parse:\n%s", src)
}
}
empty := basic(`<svg viewBox="0 0 24 24"><style>rect{fill:red}</style><rect width="24" height="24" fill="none"/><text y="20" font-size="20">a</text><marker id="m" viewBox="0 0 2 2"><rect width="2" height="2"/></marker><path d="M2 2H22" fill="none" marker-end="url(#m)"/></svg>`)
if alphaSum(empty) != 0 {
t.Errorf("ParseBasic drew text, a marker or a style sheet's rule: %v pixels", alphaSum(empty))
}
}
func FuzzParse(f *testing.F) {
for _, s := range []string{
`<svg viewBox="0 0 10 10"><path d="M1 1a5 5 0 1 0 8 8z" stroke="red" stroke-dasharray="1 2"/></svg>`,
`<svg><g opacity=".5" clip-path="url(#c)"><use href="#u"/></g><clipPath id="c"><use href="#r"/></clipPath><rect id="r" width="5" height="5"/></svg>`,
`<svg><mask id="m"><rect width="1" height="1" mask="url(#m)"/></mask><circle r="5" mask="url(#m)"/></svg>`,
`<svg><linearGradient id="a" href="#b"/><radialGradient id="b" href="#a" fr="2"/><rect width="9" height="9" fill="url(#a)"/></svg>`,
`<svg><style>:root{--a:var(--b,red);--b:var(--a)} g > .c{fill:var(--a,#0f0)} @media not (prefers-color-scheme:dark){*{stroke:blue}}</style><g><rect class="c" width="9" height="9"/></g></svg>`,
`<svg><marker id="m" orient="auto-start-reverse" viewBox="0 0 4 4" refX="2"><path d="M0 0L4 2L0 4z" fill="context-stroke" marker-end="url(#m)"/></marker><path d="M1 1a4 4 0 1 1 8 8Z" stroke="red" marker-start="url(#m)" marker-mid="url(#m)"/></svg>`,
`<svg><text x="1 2" dx="3" y="9" text-anchor="middle" transform="rotate(30)" font="bold 8px serif" stroke="red">a <tspan dy="-2" xml:space="preserve"> b </tspan>c</text></svg>`,
} {
f.Add([]byte(s))
}
f.Fuzz(func(t *testing.T, data []byte) {
d, err := Parse(data)
if err != nil {
return
}
d.Draw(image.NewRGBA(image.Rect(0, 0, 16, 16)), Options{Current: red, Fonts: boxFonts{}})
if d, err = ParseBasic(data); err != nil {
t.Fatalf("ParseBasic fails where Parse does not: %v", err)
}
d.Draw(image.NewRGBA(image.Rect(0, 0, 16, 16)), Options{Current: red, Fonts: boxFonts{}})
})
}
const checkIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>`
// gear returns an icon of a gear: arcs and lines with round joins.
func gear(teeth int) string {
var b strings.Builder
b.WriteString(`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="`)
for i := range teeth * 2 {
r := 10.0
if i%2 == 1 {
r = 7.5
}
a0, a1 := float64(i)*math.Pi/float64(teeth), float64(i+1)*math.Pi/float64(teeth)
cmd := "L"
if i == 0 {
cmd = "M"
}
fmt.Fprintf(&b, "%s%.2f %.2fA%.1f %.1f 0 0 1 %.2f %.2f", cmd, 12+r*math.Cos(a0), 12+r*math.Sin(a0), r, r, 12+r*math.Cos(a1), 12+r*math.Sin(a1))
}
b.WriteString(`Z"/><circle cx="12" cy="12" r="3"/></svg>`)
return b.String()
}
var gearIcon = gear(8)
// BenchmarkParse parses an icon of a gear drawn with arcs.
func BenchmarkParse(b *testing.B) {
for b.Loop() {
if _, err := Parse([]byte(gearIcon)); err != nil {
b.Fatal(err)
}
}
}
// BenchmarkDrawIcon draws icons of a check and of the gear at 16 to 256
// pixels.
func BenchmarkDrawIcon(b *testing.B) {
for _, bc := range []struct {
name string
src string
size int
}{{"check16", checkIcon, 16}, {"gear16", gearIcon, 16}, {"gear32", gearIcon, 32}, {"gear256", gearIcon, 256}} {
b.Run(bc.name, func(b *testing.B) {
d, _ := Parse([]byte(bc.src))
img := image.NewRGBA(image.Rect(0, 0, bc.size, bc.size))
for b.Loop() {
clear(img.Pix)
d.Draw(img, Options{Current: red})
}
})
}
}
func TestUsesCurrentColor(t *testing.T) {
for src, want := range map[string]bool{
checkIcon: true,
`<svg><rect width="1" height="1" fill="#000"/></svg>`: false,
`<svg color="red"><rect width="1" height="1" fill="currentColor"/></svg>`: false,
`<svg><linearGradient id="g"><stop stop-color="currentColor"/></linearGradient><rect width="1" height="1" fill="url(#g)"/></svg>`: true,
} {
d, err := Parse([]byte(src))
if err != nil {
t.Fatal(err)
}
if got := d.UsesCurrentColor(); got != want {
t.Errorf("%s: UsesCurrentColor %v", src, got)
}
}
}
// drawWith draws a document as o says.
func drawWith(t *testing.T, src string, w, h int, o Options) *image.RGBA {
t.Helper()
d, err := Parse([]byte(src))
if err != nil {
t.Fatalf("Parse: %v", err)
}
img := image.NewRGBA(image.Rect(0, 0, w, h))
d.Draw(img, o)
return img
}
// TestCustomProperties draws colors of var(), as the diagrams of READMEs
// set them.
func TestCustomProperties(t *testing.T) {
// The repro of #1691: white, not the black of a fill MyGo did not
// understand.
img := draw(t, `<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><style>svg { --bg: #ffffff; } .bg { fill: var(--bg); }</style><rect class="bg" width="100" height="100"/></svg>`, 100, 100)
if c := at(img, 50, 50); c != (color.RGBA{255, 255, 255, 255}) {
t.Errorf("var(--bg) = #ffffff draws %v", c)
}
img = draw(t, `<svg viewBox="0 0 6 1">
<style>
:root { --a: #00f; --b: var(--a); --loop1: var(--loop2); --loop2: var(--loop1) }
.a { fill: var(--a) } .b { fill: var(--b) }
.fallback { fill: var(--missing, var(--also-missing, #0f0)) }
.loop { fill: var(--loop1, #ff0) }
.bad { fill: var(--missing) }
</style>
<rect class="a" width="1" height="1"/>
<rect class="b" x="1" width="1" height="1"/>
<rect class="fallback" x="2" width="1" height="1"/>
<g style="--c: rgb(255, 0, 255)"><rect x="3" width="1" height="1" style="fill: var(--c)"/></g>
<rect class="loop" x="4" width="1" height="1"/>
<g fill="#0ff"><rect class="bad" x="5" width="1" height="1"/></g>
</svg>`, 6, 1)
for x, want := range []color.RGBA{
{0, 0, 255, 255}, // var()
{0, 0, 255, 255}, // a var() of a var()
{0, 255, 0, 255}, // nested fallbacks
{255, 0, 255, 255}, // inherited from a style attribute
{255, 255, 0, 255}, // a cycle, which falls back
{0, 255, 255, 255}, // undefined: unset, which inherits
} {
if got := at(img, x, 0); got != want {
t.Errorf("rect %d: %v, want %v", x, got, want)
}
}
}
// TestColorScheme draws the colors of prefers-color-scheme media queries
// in the scheme Draw is asked for.
func TestColorScheme(t *testing.T) {
const src = `<svg viewBox="0 0 2 1">
<style>
:root { --fg: #000; --bg: #fff }
@media (prefers-color-scheme: dark) { :root { --fg: #fff; --bg: #000 } .only { fill: #f00 } }
@media screen and (prefers-color-scheme: light) { .only { fill: #00f } }
.bg { fill: var(--bg) } .only { fill: #0f0 }
</style>
<rect class="bg" width="1" height="1"/><rect class="only" x="1" width="1" height="1"/>
</svg>`
light := drawWith(t, src, 2, 1, Options{})
dark := drawWith(t, src, 2, 1, Options{Dark: true})
if c := at(light, 0, 0); c != (color.RGBA{255, 255, 255, 255}) {
t.Errorf("light background %v", c)
}
if c := at(dark, 0, 0); c != (color.RGBA{0, 0, 0, 255}) {
t.Errorf("dark background %v", c)
}
// The rule after the media queries wins either way, as it would in a
// browser.
if at(light, 1, 0) != at(dark, 1, 0) || at(light, 1, 0) != (color.RGBA{0, 255, 0, 255}) {
t.Errorf("a later rule: light %v, dark %v", at(light, 1, 0), at(dark, 1, 0))
}
d, _ := Parse([]byte(src))
if !d.UsesColorScheme() {
t.Error("a document of prefers-color-scheme does not use the color scheme")
}
d, _ = Parse([]byte(checkIcon))
if d.UsesColorScheme() {
t.Error("an icon uses the color scheme")
}
}
// TestSelectors matches descendant and child combinators, and :root.
func TestSelectors(t *testing.T) {
img := draw(t, `<svg viewBox="0 0 4 1">
<style>
.diagram .node rect { fill: #00f }
g > rect.direct { fill: #0f0 }
:root > rect { fill: #f0f }
.x + rect { fill: #fff }
</style>
<g class="diagram"><g class="node"><rect width="1" height="1"/></g></g>
<g><rect class="direct" x="1" width="1" height="1"/></g>
<rect x="2" width="1" height="1"/>
<g class="node"><rect x="3" width="1" height="1"/></g>
</svg>`, 4, 1)
for x, want := range []color.RGBA{{0, 0, 255, 255}, {0, 255, 0, 255}, {255, 0, 255, 255}, {0, 0, 0, 255}} {
if got := at(img, x, 0); got != want {
t.Errorf("rect %d: %v, want %v", x, got, want)
}
}
}
// TestUnsupported lists what a document has that is not drawn, and
// nothing for one that is drawn whole.
func TestUnsupported(t *testing.T) {
d, err := Parse([]byte(`<svg viewBox="0 0 10 10">
<style>@font-face { font-family: X; src: url(x.woff) } .a + .b { fill: red } .c:hover { fill: blue }
@media (min-width: 600px) { rect { fill: red } }</style>
<pattern id="p" width="2" height="2"><rect width="1" height="1"/></pattern>
<filter id="f"><feGaussianBlur stdDeviation="2"/></filter>
<rect width="5" height="5" fill="url(#p)" style="filter: url(#f)"/>
<image href="a.png" width="5" height="5"/>
<text>a<textPath href="#q">b</textPath></text>
</svg>`))
if err != nil {
t.Fatal(err)
}
want := []string{"<image>", "<pattern>", "<textPath>", "@font-face", "@media (min-width: 600px)", "filter", "selector .a + .b"}
if got := d.Unsupported(); !slices.Equal(got, want) {
t.Errorf("Unsupported() = %q, want %q", got, want)
}
for _, src := range []string{checkIcon, gearIcon, diagram} {
d, err := Parse([]byte(src))
if err != nil {
t.Fatal(err)
}
if got := d.Unsupported(); len(got) != 0 {
t.Errorf("Unsupported() = %q for a document drawn whole", got)
}
}
}
// diagram is a diagram as READMEs have them: colors of custom properties
// with a dark scheme, labels and an arrow.
const diagram = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 40">
<style>
:root { --fg: #1f2328 } @media (prefers-color-scheme: dark) { :root { --fg: #e6edf3 } }
text { fill: var(--fg); font: 600 10px sans-serif; text-anchor: middle; dominant-baseline: central }
.edge { stroke: var(--fg); marker-end: url(#arrow) }
</style>
<defs><marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="context-stroke"/></marker></defs>
<text x="20" y="20">A</text><path class="edge" d="M30 20H70"/><text x="80" y="20">B</text>
</svg>`
// boxFonts measures every character half an em wide, 0.8 em high and 0.2
// em deep, and draws it as a box that wide and high.
type boxFonts struct{}
func (boxFonts) Measure(s string, f Font) (float64, float64, float64) {
return float64(len([]rune(s))) * f.Size / 2, 0.8 * f.Size, 0.2 * f.Size
}
func (boxFonts) Rasterize(s string, f Font, x, stroke float64) Bitmap {
w := int(math.Round(x + float64(len([]rune(s)))*f.Size/2))
h := int(math.Round(0.8 * f.Size))
pix := make([]byte, w*h)
for i := range pix {
pix[i] = 255
}
return Bitmap{Left: 0, Top: -h, W: w, H: h, Pix: pix}
}
// inkX returns the columns of row y an image covers, from the first to
// after the last.
func inkX(img *image.RGBA, y int) (x0, x1 int) {
x0, x1 = -1, -1
for x := range img.Bounds().Dx() {
if at(img, x, y).A > 127 {
if x0 < 0 {
x0 = x
}
x1 = x + 1
}
}
return x0, x1
}
// TestText lays out text with the Fonts of Options: anchored, placed and
// moved, and between the shapes around it.
func TestText(t *testing.T) {
o := Options{Fonts: boxFonts{}}
img := drawWith(t, `<svg viewBox="0 0 100 100">
<text x="50" y="20" font-size="10" text-anchor="middle">abcd</text>
<text x="50" y="40" font-size="10" text-anchor="end">ab</text>
<text x="10" y="60" font-size="10">ab<tspan dx="10">c</tspan></text>
<text x="10 30" y="80" font-size="10">a<tspan font-size="20">b</tspan></text>
</svg>`, 100, 100, o)
for _, c := range []struct {
y, x0, x1 int
}{
{16, 40, 60}, // middle: centered on x
{36, 40, 50}, // end: ending at x
{56, 10, 35}, // a run, then one 10 further
} {
if x0, x1 := inkX(img, c.y); x0 != c.x0 || x1 != c.x1 {
t.Errorf("row %d: ink from %d to %d, want %d to %d", c.y, x0, x1, c.x0, c.x1)
}
}
// dx moves the run after it; a list of x places each character.
if at(img, 22, 56).A != 0 || at(img, 32, 56).A != 255 {
t.Errorf("dx: %v at 22, %v at 32", at(img, 22, 56), at(img, 32, 56))
}
if at(img, 20, 70).A != 0 || at(img, 35, 70).A != 255 || at(img, 12, 78).A != 255 {
t.Errorf("x list: %v at 20, %v at 35", at(img, 20, 70), at(img, 35, 70))
}
// Central puts the middle of the em box on y.
img = drawWith(t, `<svg viewBox="0 0 100 100"><text x="0" y="50" font-size="20" dominant-baseline="central">a</text></svg>`, 100, 100, o)
// The box of 0.8 em above the baseline and 0.2 em below it is from 40
// to 60: what is above the baseline, from 40 to 56, is drawn.
if at(img, 5, 41).A != 255 || at(img, 5, 55).A != 255 || at(img, 5, 38).A != 0 || at(img, 5, 57).A != 0 {
t.Errorf("central: %v %v %v %v", at(img, 5, 38), at(img, 5, 41), at(img, 5, 55), at(img, 5, 57))
}
// Text between shapes, in document order, scaled and rotated.
img = drawWith(t, `<svg viewBox="0 0 50 50">
<rect width="50" height="50" fill="#00f"/>
<text x="5" y="20" font-size="10" fill="#0f0">abc</text>
<rect x="0" y="30" width="50" height="20" fill="#f00"/>
<text x="5" y="45" font-size="10" fill="#ff0" opacity=".5">abc</text>
<text transform="rotate(90 40 5)" x="40" y="5" font-size="10" fill="#fff">abc</text>
</svg>`, 100, 100, o)
if c := at(img, 20, 30); c != (color.RGBA{0, 255, 0, 255}) {
t.Errorf("text over a shape: %v", c)
}
if c := at(img, 20, 86); c.R != 255 || c.G < 120 || c.G > 135 {
t.Errorf("translucent text over a shape: %v", c)
}
if c := at(img, 88, 30); c != (color.RGBA{255, 255, 255, 255}) {
t.Errorf("rotated text: %v", c)
}
// Without Fonts, no text is drawn.
if img := draw(t, `<svg viewBox="0 0 10 10"><text y="10" font-size="10">a</text></svg>`, 10, 10); alphaSum(img) != 0 {
t.Error("text drawn without Fonts")
}
}
// TestMarkers draws arrowheads along the direction of a path's end, and
// at its start reversed.
func TestMarkers(t *testing.T) {
const defs = `<defs><marker id="a" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="5" markerHeight="5" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#00f"/></marker></defs>`
// Down the middle, then right: the arrowhead at the end points right,
// its tip at the end; the one at the start points up.
img := draw(t, `<svg viewBox="0 0 100 100">`+defs+`<path d="M20 30V70H80" fill="none" stroke="#000" stroke-width="4" marker-start="url(#a)" marker-end="url(#a)"/></svg>`, 100, 100)
blue := func(x, y int) bool { c := at(img, x, y); return c.B > 200 && c.R < 50 }
// The end: 20 wide (5 × the stroke's 4) and 20 high, from x 60 to 80.
if !blue(62, 70) || !blue(62, 62) || !blue(76, 70) || blue(76, 64) || blue(82, 70) {
t.Errorf("the end's arrowhead does not point right: %v %v %v %v", blue(62, 70), blue(62, 62), blue(76, 70), blue(76, 64))
}
// The start: reversed, pointing up, its tip at (20, 30).
if !blue(20, 32) || !blue(12, 48) || blue(12, 33) || blue(20, 27) {
t.Errorf("the start's arrowhead does not point up: %v %v %v %v", blue(20, 32), blue(12, 48), blue(12, 33), blue(20, 27))
}
// userSpaceOnUse sizes it in user units; a fixed orient turns it
// whatever the path's direction.
img = draw(t, `<svg viewBox="0 0 100 100"><defs><marker id="b" markerUnits="userSpaceOnUse" markerWidth="10" markerHeight="10" refX="5" refY="5" orient="90"><path d="M0 0H10L5 10z" fill="#00f"/></marker></defs>
<line x1="10" y1="50" x2="50" y2="50" stroke="#000" stroke-width="10" marker-end="url(#b)"/></svg>`, 100, 100)
// Turned a quarter: its point at the left.
if !blue(53, 47) || !blue(53, 52) || blue(46, 46) {
t.Errorf("a marker of a fixed orient: %v %v %v", blue(53, 47), blue(53, 52), blue(46, 46))
}
// A marker's overflow is hidden: what is past its viewport is cut.
img = draw(t, `<svg viewBox="0 0 100 100"><defs><marker id="c" markerUnits="userSpaceOnUse" markerWidth="10" markerHeight="10"><rect width="20" height="20" fill="#00f"/></marker></defs>
<line x1="10" y1="10" x2="50" y2="10" stroke="#000" marker-end="url(#c)"/></svg>`, 100, 100)
if !blue(55, 15) || blue(65, 15) {
t.Errorf("a marker's overflow: %v inside, %v outside", blue(55, 15), blue(65, 15))
}
}
// TestMarkerVertices finds the vertices of paths: arcs split into curves
// are one segment, and closed subpaths turn at their start.
func TestMarkerVertices(t *testing.T) {
pa := parsePath("M0 0A10 10 0 1 1 0 20L0 30")
if vs := pa.vertices(); len(vs) != 3 {
t.Errorf("an arc and a line: %d vertices, want 3", len(vs))
}
pa = parsePath("M0 0H10V10Z")
vs := pa.vertices()
if len(vs) != 4 {
t.Fatalf("a closed triangle: %d vertices, want 4", len(vs))
}
// At its start, between the closing segment's direction (up and to
// the left, -135 degrees) and the first's (right, 0).
if a := vs[0].angle(); math.Abs(a+67.5) > 1e-9 {
t.Errorf("the start of a closed subpath turns %v degrees, want -67.5", a)
}
}
+438
View File
@@ -0,0 +1,438 @@
package svg
import (
"image"
"math"
"strings"
)
// Font is the font of a run of text.
type Font struct {
// Family is a list of families, as CSS's font-family writes it.
Family string
// Size is the em size in pixels.
Size float64
// Weight is from 1 to 1000: 400 is normal, 700 bold.
Weight int
Italic bool
// LetterSpacing adds pixels after every character.
LetterSpacing float64
}
// Fonts lays out and rasterizes lines of text, as Draw draws the text of
// documents with them: package ui gives the system's text stack. Draw
// calls it from the goroutine drawing.
type Fonts interface {
// Measure returns how far a line of text s in font f moves the pen,
// and the font's ascent and descent, in pixels.
Measure(s string, f Font) (advance, ascent, descent float64)
// Rasterize returns the coverage of a line of text s in font f, its
// pen on the baseline x pixels right of the left edge of a pixel (0
// ≤ x < 1), or with stroke > 0 that of a stroke stroke pixels wide
// along the outlines of its glyphs.
Rasterize(s string, f Font, x, stroke float64) Bitmap
}
// Bitmap is the coverage of a line of text: W×H bytes, row by row, the
// first Left pixels right of the pixel the pen starts in and Top pixels
// below the baseline (Top is usually negative).
type Bitmap struct {
Left, Top, W, H int
Pix []byte
}
// textNode is a text element: runs of characters, each in one style and
// at one position, which Draw lays out with the Fonts it is given.
type textNode struct {
runs []textRun
}
// textRun is a run of a text element's characters.
type textRun struct {
s string
font Font // its size in user units
// x and y place the run, where absX and absY say they do, and dx and
// dy move it; otherwise it goes on from the run before.
x, y, dx, dy float64
absX, absY bool
// anchor is the text-anchor of the chunk of text the run starts, if
// it is placed.
anchor uint8
baseline uint8
hidden bool
shape shape // its paint; no path
}
// tchar is a character of a text element, in the style of the element it
// is in.
type tchar struct {
r rune
st *style
space bool // a space that white space collapses
}
// text compiles a text element of style st.
func (c *compiler) text(e *elem, st *style) *textNode {
var chars []tchar
type placed struct {
el *elem
start int
}
var lists []placed
var visit func(el *elem, st *style, preserve bool)
visit = func(el *elem, st *style, preserve bool) {
if v, ok := el.attrs["xml:space"]; ok {
preserve = v == "preserve"
}
preserve = preserve || st.preserve
lists = append(lists, placed{el, len(chars)})
for _, k := range el.kids {
switch k.name {
case "#text":
for _, r := range k.text {
switch r {
case '\n', '\r', '\t':
r = ' '
}
if r == ' ' && !preserve && (len(chars) == 0 || chars[len(chars)-1].space) {
continue
}
chars = append(chars, tchar{r, st, r == ' ' && !preserve})
}
case "tspan", "a":
if c.budget <= 0 {
return
}
c.budget--
kst := c.style(k, st)
if kst.display {
p := new(style)
*p = kst
visit(k, p, preserve)
}
case "textPath":
c.rep.add("<textPath>")
}
}
}
visit(e, st, false)
for len(chars) > 0 && chars[len(chars)-1].space {
chars = chars[:len(chars)-1]
}
if len(chars) == 0 {
return nil
}
// The positions the elements give their characters, inner elements
// over outer ones.
n := len(chars)
xs, ys := make([]float64, n), make([]float64, n)
for i := range xs {
xs[i], ys[i] = math.NaN(), math.NaN()
}
dxs, dys := make([]float64, n), make([]float64, n)
for _, p := range lists {
for k, list := range [4][]float64{xs, ys, dxs, dys} {
base := c.vw
if k%2 == 1 {
base = c.vh
}
for i, v := range c.lengths(p.el.attrs[[4]string{"x", "y", "dx", "dy"}[k]], base) {
if p.start+i < n {
list[p.start+i] = v
}
}
}
if p.el.attrs["rotate"] != "" {
c.rep.add("rotate")
}
}
if math.IsNaN(xs[0]) {
xs[0] = 0
}
if math.IsNaN(ys[0]) {
ys[0] = 0
}
t := &textNode{}
var b strings.Builder
for i, ch := range chars {
placedHere := !math.IsNaN(xs[i]) || !math.IsNaN(ys[i]) || dxs[i] != 0 || dys[i] != 0
if i == 0 || placedHere || ch.st != chars[i-1].st {
if len(t.runs) > 0 {
t.runs[len(t.runs)-1].s = b.String()
b.Reset()
}
t.runs = append(t.runs, c.textRun(ch.st, xs[i], ys[i], dxs[i], dys[i]))
}
b.WriteRune(ch.r)
}
t.runs[len(t.runs)-1].s = b.String()
return t
}
// textRun starts a run of characters of style st at a position.
func (c *compiler) textRun(st *style, x, y, dx, dy float64) textRun {
family := st.fontFamily
if family == "" {
family = "serif" // as browsers draw SVG
}
r := textRun{
font: Font{Family: family, Size: st.fontSize, Weight: st.fontWeight, Italic: st.italic, LetterSpacing: st.letterSpacing},
x: x, y: y, dx: dx, dy: dy, absX: !math.IsNaN(x), absY: !math.IsNaN(y),
anchor: st.anchor, baseline: st.baseline, hidden: !st.visible,
shape: shape{
fill: c.paint(st.fill, st), stroke: c.paint(st.stroke, st),
fillOpacity: st.fillOpacity, strokeOpacity: st.strokeOpacity,
width: st.strokeWidth, strokeFirst: st.strokeFirst,
},
}
if st.align != baselineAuto {
r.baseline = st.align
}
return r
}
// lengths parses a list of lengths, percentages of base, up to the first
// in error.
func (c *compiler) lengths(v string, base float64) []float64 {
var out []float64
for _, f := range strings.FieldsFunc(v, func(r rune) bool { return r == ',' || r == ' ' || r == '\t' || r == '\n' || r == '\r' }) {
l, ok := parseLength(f, base)
if !ok {
break
}
out = append(out, l)
}
return out
}
// textBox is where a run of text is laid out: its pen on the baseline,
// its advance, and its ascent and descent, in user units.
type textBox struct {
pen point
advance, ascent, depth float64
}
// layout lays out the runs of t, measured by measure in user units, into
// boxes, and returns the box around them.
func (t *textNode) layout(measure func(r *textRun) (advance, ascent, descent float64), boxes []textBox) box {
var pen point
chunk := 0
anchor := func(end int) {
if end <= chunk {
return
}
k := 0.0
switch t.runs[chunk].anchor {
case anchorMiddle:
k = 0.5
case anchorEnd:
k = 1
}
shift := (pen.x - boxes[chunk].pen.x) * k
for i := chunk; i < end; i++ {
boxes[i].pen.x -= shift
}
}
for i := range t.runs {
r := &t.runs[i]
if (r.absX || r.absY) && i > 0 {
anchor(i)
chunk = i
}
if r.absX {
pen.x = r.x
}
if r.absY {
pen.y = r.y
}
pen.x += r.dx
pen.y += r.dy
adv, asc, desc := measure(r)
size := r.font.Size
var shift float64 // of the baseline, down
switch r.baseline {
case baselineMiddle:
shift = 0.25 * size // half an x-height
case baselineCentral:
shift = (asc - desc) / 2
case baselineHanging:
shift = 0.8 * asc
case baselineTop:
shift = asc
case baselineBottom:
shift = -desc
case baselineMath:
shift = 0.5 * asc
}
boxes[i] = textBox{point{pen.x, pen.y + shift}, adv, asc, desc}
pen.x += adv
}
anchor(len(t.runs))
var b box
for i, x := range boxes {
r := box{x.pen.x, x.pen.y - x.ascent, x.advance, x.ascent + x.depth}
if i == 0 {
b = r
} else {
b = b.union(r)
}
}
return b
}
// estimate returns the box around the text, with characters of usual
// widths, for what is in its objectBoundingBox units before Draw
// measures it.
func (t *textNode) estimate() box {
return t.layout(func(r *textRun) (float64, float64, float64) {
n := float64(len([]rune(r.s)))
return n * (0.55*r.font.Size + r.font.LetterSpacing), 0.8 * r.font.Size, 0.2 * r.font.Size
}, make([]textBox, len(t.runs)))
}
// maxFontPixels is the largest size text is rasterized at: larger text is
// rasterized at it and scaled.
const maxFontPixels = 512
// text draws a text element, mapped to pixels by m, into dst with an
// opacity.
func (r *renderer) text(t *textNode, m matrix, dst *layer, alpha float64) {
fonts := r.fonts
if fonts == nil {
return
}
// The scale text is rasterized at, in pixels per user unit.
k := math.Sqrt(math.Abs(m[0]*m[3] - m[1]*m[2]))
if !(k > 0) || math.IsInf(k, 0) {
return
}
scaled := func(f Font) (Font, float64) {
s := k
if f.Size*s > maxFontPixels {
s = maxFontPixels / f.Size
}
f.Size *= s
f.LetterSpacing *= s
return f, s
}
if cap(r.boxes) < len(t.runs) {
r.boxes = make([]textBox, len(t.runs))
}
boxes := r.boxes[:len(t.runs)]
bbox := t.layout(func(run *textRun) (float64, float64, float64) {
f, s := scaled(run.font)
if f.Size <= 0 {
return 0, 0, 0
}
adv, asc, desc := fonts.Measure(run.s, f)
return adv / s, asc / s, desc / s
}, boxes)
for i := range t.runs {
run := &t.runs[i]
f, s := scaled(run.font)
if run.hidden || f.Size < 0.5 {
continue
}
sh := &run.shape
// Runs off the canvas, with room for glyphs reaching past their
// box, are left out, and so are those too large to rasterize.
x := &boxes[i]
pad := run.font.Size + sh.width
on := box{x.pen.x - pad, x.pen.y - x.ascent - pad, x.advance + 2*pad, x.ascent + x.depth + 2*pad}.transform(m)
if on.x > float64(r.w) || on.y > float64(r.h) || on.x+on.w < 0 || on.y+on.h < 0 || on.w*on.h*s*s/(k*k) > 1<<24 {
continue
}
draw := func(p paint, opacity, stroke float64) {
if p.kind == paintNone {
return
}
// The pen in pixels, and the transform from the pixels of the
// bitmap, at the left edge of the pixel the pen starts in, to
// those of the canvas.
pen := m.apply(boxes[i].pen)
upright := m[1] == 0 && m[2] == 0 && m[0] > 0 && math.Abs(m[0]-m[3]) < 1e-9 && s == k
var bm matrix
var x float64
if upright {
x = pen.x - math.Floor(pen.x)
bm = translate(math.Floor(pen.x), math.Round(pen.y))
} else {
bm = m.mul(translate(boxes[i].pen.x, boxes[i].pen.y)).mul(scaling(1/s, 1/s))
}
b := fonts.Rasterize(run.s, f, x, stroke*s)
if b.W <= 0 || b.H <= 0 || len(b.Pix) < b.W*b.H {
return
}
if rect, ok := r.coverBitmap(&b, bm, upright); ok {
r.paint(dst, rect, p, alpha*opacity, m, bbox)
}
}
stroke := func() {
if sh.width > 0 {
draw(sh.stroke, sh.strokeOpacity, sh.width)
}
}
if sh.strokeFirst {
stroke()
}
draw(sh.fill, sh.fillOpacity, 0)
if !sh.strokeFirst {
stroke()
}
}
}
// coverBitmap puts the coverage of a bitmap of text into r.cov, its
// pixels mapped to the canvas's by m, and returns the rectangle of the
// canvas it covers. An upright m moves the bitmap by whole pixels;
// others are sampled.
func (r *renderer) coverBitmap(b *Bitmap, m matrix, upright bool) (image.Rectangle, bool) {
src := image.Rect(b.Left, b.Top, b.Left+b.W, b.Top+b.H)
var rect image.Rectangle
if upright {
rect = src.Add(image.Pt(int(m[4]), int(m[5])))
} else {
bb := box{float64(src.Min.X), float64(src.Min.Y), float64(b.W), float64(b.H)}.transform(m)
rect = image.Rect(int(math.Floor(bb.x)), int(math.Floor(bb.y)), int(math.Ceil(bb.x+bb.w)), int(math.Ceil(bb.y+bb.h)))
}
rect = rect.Intersect(image.Rect(0, 0, r.w, r.h))
if rect.Empty() {
return rect, false
}
w, h := rect.Dx(), rect.Dy()
if cap(r.cov) < w*h {
r.cov = make([]byte, w*h)
}
r.cov = r.cov[:w*h]
if upright {
ox, oy := int(m[4])+b.Left, int(m[5])+b.Top
for y := range h {
row := b.Pix[(rect.Min.Y+y-oy)*b.W+rect.Min.X-ox:]
copy(r.cov[y*w:(y+1)*w], row[:w])
}
return rect, true
}
inv, ok := m.invert()
if !ok {
return rect, false
}
at := func(x, y int) float64 {
if x < 0 || y < 0 || x >= b.W || y >= b.H {
return 0
}
return float64(b.Pix[y*b.W+x])
}
for y := range h {
for x := range w {
// Bilinearly, between the centers of the bitmap's pixels.
q := inv.apply(point{float64(rect.Min.X+x) + 0.5, float64(rect.Min.Y+y) + 0.5})
u, v := q.x-float64(b.Left)-0.5, q.y-float64(b.Top)-0.5
x0, y0 := math.Floor(u), math.Floor(v)
fx, fy := u-x0, v-y0
i, j := int(x0), int(y0)
c := (at(i, j)*(1-fx)+at(i+1, j)*fx)*(1-fy) + (at(i, j+1)*(1-fx)+at(i+1, j+1)*fx)*fy
r.cov[y*w+x] = uint8(c + 0.5)
}
}
return rect, true
}