Merge dev/svg-maker: svgc v1
This commit is contained in:
82
svg-maker/README.md
Normal file
82
svg-maker/README.md
Normal file
@@ -0,0 +1,82 @@
|
||||
# svg-maker — `svgc`, vector graphics for agents
|
||||
|
||||
Builds SVG images from a line-based text format (`.svgd`) that an
|
||||
agent can author directly, **verify without a GUI** (terminal preview
|
||||
+ measurements) and show to a human through agent-helm
|
||||
(`helmd share out.svg`). Built for "graphical elements": status cards,
|
||||
diagrams, icons, simple illustrations.
|
||||
|
||||
## Usage
|
||||
|
||||
```
|
||||
svgc build <file.svgd> [-o out.svg] [--preview] [--width N]
|
||||
svgc preview <file.svgd> [--width N] truecolor half-block render
|
||||
svgc info <file.svgd> counts, colors, bbox, warnings
|
||||
svgc example annotated example to start from
|
||||
```
|
||||
|
||||
Typical agent flow:
|
||||
|
||||
```bash
|
||||
svgc example > card.svgd # start from the example
|
||||
# ...edit card.svgd...
|
||||
svgc build card.svgd --preview # writes card.svg + shows what it looks like
|
||||
helmd share card.svg --note "status card" # display it in agent-helm
|
||||
```
|
||||
|
||||
`build` prints an info block after writing — element counts, colors,
|
||||
the drawing's bounding box and **warnings for anything outside the
|
||||
canvas** — so mistakes surface as text even without the preview.
|
||||
Errors carry line numbers (`card.svgd: line 7: "four" is not a
|
||||
number — rect needs: rect <x> <y> <w> <h>`).
|
||||
|
||||
## The .svgd format
|
||||
|
||||
One element per line, `#` comments, `key=value` attributes last:
|
||||
|
||||
```
|
||||
canvas 240 120 # required: width height
|
||||
bg #12161f # optional background
|
||||
def accent #4f9cf9 # named color, use as $accent
|
||||
|
||||
rect 10 10 60 40 fill=$accent rx=6
|
||||
circle 120 40 20 fill=#3fca7c stroke=white stroke-width=2
|
||||
ellipse 60 90 30 12 fill=gray
|
||||
line 10 100 190 100 stroke=red width=3
|
||||
polyline 10,20 30,40 50,10 stroke=white
|
||||
polygon 20,80 40,60 60,80 fill=#e0a63f
|
||||
path M10,10 L50,50 Q70,20 90,50 Z stroke=white
|
||||
text 100 60 "Hello agent-helm" size=14 fill=white anchor=middle bold
|
||||
group stroke=gray stroke-width=1 # group attrs are inherited
|
||||
line 0 0 10 10
|
||||
end
|
||||
```
|
||||
|
||||
| Piece | Notes |
|
||||
|---|---|
|
||||
| `canvas w h` | required first; becomes the viewBox and image size |
|
||||
| `bg color` | background rect |
|
||||
| `def name color` | color variable; `$name` in any fill/stroke |
|
||||
| attributes | `fill stroke stroke-width` (alias `width`) `opacity fill-opacity stroke-opacity rx ry anchor size font dash linecap linejoin transform id` + flags `bold italic` |
|
||||
| colors | `#rgb`, `#rrggbb`, CSS names, `none`; unknown attribute keys are errors |
|
||||
| `path` | subset `M L H V C Q Z`, absolute + relative, commas or spaces |
|
||||
| `transform` | raw SVG transform with commas: `transform=rotate(45,50,50)` |
|
||||
|
||||
Friendly defaults: `line`/`polyline`/`path` get a visible stroke if
|
||||
you give none, `polyline` gets `fill=none` — no invisible elements,
|
||||
no accidental filled blobs.
|
||||
|
||||
## Preview fidelity
|
||||
|
||||
The preview rasterizes the same shape model the emitter writes:
|
||||
fills, strokes, opacity and group inheritance are honored. Two
|
||||
approximations: `rx` rounded corners render square, and **text renders
|
||||
as its baseline box** (real glyphs are a font problem — check text in
|
||||
the real render via agent-helm). `info` always reflects true geometry.
|
||||
|
||||
## Build & test
|
||||
|
||||
```bash
|
||||
go test ./...
|
||||
go build -o build/svgc .
|
||||
```
|
||||
12
svg-maker/examples/gauge.svgd
Normal file
12
svg-maker/examples/gauge.svgd
Normal file
@@ -0,0 +1,12 @@
|
||||
# gauge.svgd - example: a small status card
|
||||
canvas 240 120
|
||||
bg #12161f
|
||||
|
||||
def ok #3fca7c
|
||||
def frame #262d3a
|
||||
|
||||
rect 8 8 224 104 fill=none stroke=$frame stroke-width=2 rx=10
|
||||
circle 40 60 22 fill=none stroke=$ok stroke-width=6
|
||||
path M30,60 L38,68 L52,50 stroke=$ok width=5 linecap=round fill=none
|
||||
text 76 54 "backups" size=13 fill=#8a93a5
|
||||
text 76 76 "all green" size=17 fill=white bold
|
||||
3
svg-maker/go.mod
Normal file
3
svg-maker/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module gitea.brasse-pc.eu/brasse/agent-tools/svg-maker
|
||||
|
||||
go 1.24
|
||||
176
svg-maker/main.go
Normal file
176
svg-maker/main.go
Normal file
@@ -0,0 +1,176 @@
|
||||
// svgc builds SVG images from .svgd text descriptions — vector
|
||||
// graphics an agent can author, verify (terminal preview + info) and
|
||||
// share to agent-helm with `helmd share out.svg`.
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"gitea.brasse-pc.eu/brasse/agent-tools/svg-maker/svg"
|
||||
)
|
||||
|
||||
var version = "dev"
|
||||
|
||||
const usage = `svgc - SVG maker for agents
|
||||
|
||||
Usage:
|
||||
svgc build <file.svgd> [-o out.svg] [--preview] [--width N]
|
||||
svgc preview <file.svgd> [--width N] draw it in the terminal
|
||||
svgc info <file.svgd> counts, colors, bbox, warnings
|
||||
svgc example print an annotated example file
|
||||
svgc version
|
||||
|
||||
The .svgd format ('#' comments, one element per line):
|
||||
canvas 200 120 required: width height
|
||||
bg #1a2029 optional background
|
||||
def accent #4f9cf9 named color, use as $accent
|
||||
rect 10 10 60 40 fill=$accent rx=6
|
||||
circle 120 40 20 fill=#3fca7c stroke=white stroke-width=2
|
||||
ellipse 60 90 30 12 fill=gray
|
||||
line 10 100 190 100 stroke=red width=3
|
||||
polyline 10,20 30,40 50,10 stroke=white
|
||||
polygon 20,80 40,60 60,80 fill=#e0a63f
|
||||
path M10,10 L50,50 Q70,20 90,50 Z stroke=white
|
||||
text 100 60 "Hello agent-helm" size=14 fill=white anchor=middle bold
|
||||
group stroke=gray stroke-width=1 group attrs are inherited
|
||||
line 0 0 10 10
|
||||
end
|
||||
|
||||
Attributes: fill stroke stroke-width|width opacity fill-opacity
|
||||
stroke-opacity rx ry anchor size font dash linecap linejoin transform
|
||||
id, plus flags bold italic. Colors: #rgb #rrggbb, CSS names, none.
|
||||
|
||||
Show the result in agent-helm: helmd share out.svg --note "diagram"
|
||||
`
|
||||
|
||||
const exampleFile = `# gauge.svgd - example: a small status card
|
||||
canvas 240 120
|
||||
bg #12161f
|
||||
|
||||
def ok #3fca7c
|
||||
def frame #262d3a
|
||||
|
||||
rect 8 8 224 104 fill=none stroke=$frame stroke-width=2 rx=10
|
||||
circle 40 60 22 fill=none stroke=$ok stroke-width=6
|
||||
path M30,60 L38,68 L52,50 stroke=$ok width=5 linecap=round fill=none
|
||||
text 76 54 "backups" size=13 fill=#8a93a5
|
||||
text 76 76 "all green" size=17 fill=white bold
|
||||
`
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
fmt.Print(usage)
|
||||
os.Exit(2)
|
||||
}
|
||||
switch os.Args[1] {
|
||||
case "build":
|
||||
cmdBuild(os.Args[2:])
|
||||
case "preview":
|
||||
cmdPreview(os.Args[2:])
|
||||
case "info":
|
||||
cmdInfo(os.Args[2:])
|
||||
case "example":
|
||||
fmt.Print(exampleFile)
|
||||
case "version", "--version", "-v":
|
||||
fmt.Println("svgc", version)
|
||||
case "help", "--help", "-h":
|
||||
fmt.Print(usage)
|
||||
default:
|
||||
die("unknown command %q — run 'svgc help'", os.Args[1])
|
||||
}
|
||||
}
|
||||
|
||||
func cmdBuild(args []string) {
|
||||
fs := flag.NewFlagSet("build", flag.ExitOnError)
|
||||
out := fs.String("o", "", "output file (default: input with .svg)")
|
||||
preview := fs.Bool("preview", false, "also draw the result in the terminal")
|
||||
width := fs.Int("width", 72, "preview width in characters")
|
||||
pos := parseInterspersed(fs, args)
|
||||
if len(pos) != 1 {
|
||||
die("build takes exactly one .svgd file")
|
||||
}
|
||||
xml, doc := load(pos[0])
|
||||
dst := *out
|
||||
if dst == "" {
|
||||
dst = strings.TrimSuffix(pos[0], filepath.Ext(pos[0])) + ".svg"
|
||||
}
|
||||
if err := os.WriteFile(dst, []byte(xml), 0o644); err != nil {
|
||||
die("%v", err)
|
||||
}
|
||||
fmt.Printf("wrote %s (%d bytes)\n", dst, len(xml))
|
||||
fmt.Print(svg.Info(doc))
|
||||
if *preview {
|
||||
fmt.Print(svg.RenderGrid(doc, *width).ANSI())
|
||||
}
|
||||
}
|
||||
|
||||
func cmdPreview(args []string) {
|
||||
fs := flag.NewFlagSet("preview", flag.ExitOnError)
|
||||
width := fs.Int("width", 72, "preview width in characters")
|
||||
pos := parseInterspersed(fs, args)
|
||||
if len(pos) != 1 {
|
||||
die("preview takes exactly one .svgd file")
|
||||
}
|
||||
_, doc := load(pos[0])
|
||||
fmt.Print(svg.RenderGrid(doc, *width).ANSI())
|
||||
}
|
||||
|
||||
func cmdInfo(args []string) {
|
||||
if len(args) != 1 {
|
||||
die("info takes exactly one .svgd file")
|
||||
}
|
||||
_, doc := load(args[0])
|
||||
fmt.Print(svg.Info(doc))
|
||||
}
|
||||
|
||||
// load reads and builds a .svgd file (attrs normalized), dying with
|
||||
// the parser's line-numbered error on failure. Returns the SVG XML
|
||||
// and the parsed document.
|
||||
func load(path string) (string, *svg.Doc) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
die("%v", err)
|
||||
}
|
||||
xml, doc, err := svg.Build(string(data))
|
||||
if err != nil {
|
||||
die("%s: %v", path, err)
|
||||
}
|
||||
return xml, doc
|
||||
}
|
||||
|
||||
// parseInterspersed lets flags appear before or after positional args.
|
||||
func parseInterspersed(fs *flag.FlagSet, args []string) []string {
|
||||
var flags, pos []string
|
||||
for i := 0; i < len(args); i++ {
|
||||
a := args[i]
|
||||
if len(a) > 1 && a[0] == '-' {
|
||||
flags = append(flags, a)
|
||||
name := strings.TrimLeft(a, "-")
|
||||
if eq := strings.Index(name, "="); eq >= 0 {
|
||||
continue
|
||||
}
|
||||
if f := fs.Lookup(name); f != nil {
|
||||
if bf, ok := f.Value.(interface{ IsBoolFlag() bool }); ok && bf.IsBoolFlag() {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if i+1 < len(args) {
|
||||
i++
|
||||
flags = append(flags, args[i])
|
||||
}
|
||||
} else {
|
||||
pos = append(pos, a)
|
||||
}
|
||||
}
|
||||
fs.Parse(flags)
|
||||
return pos
|
||||
}
|
||||
|
||||
func die(format string, args ...interface{}) {
|
||||
fmt.Fprintf(os.Stderr, "svgc: "+format+"\n", args...)
|
||||
os.Exit(1)
|
||||
}
|
||||
135
svg-maker/svg/emit.go
Normal file
135
svg-maker/svg/emit.go
Normal file
@@ -0,0 +1,135 @@
|
||||
package svg
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Emit renders the document as an SVG file.
|
||||
func Emit(d *Doc) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 %s %s" width="%s" height="%s">`,
|
||||
num(d.W), num(d.H), num(d.W), num(d.H))
|
||||
b.WriteString("\n")
|
||||
if d.Bg != "" {
|
||||
fmt.Fprintf(&b, ` <rect width="100%%" height="100%%" fill="%s"/>`+"\n", d.Bg)
|
||||
}
|
||||
for _, el := range d.Elems {
|
||||
emitElem(&b, el, 1)
|
||||
}
|
||||
b.WriteString("</svg>\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func emitElem(b *strings.Builder, el *Elem, depth int) {
|
||||
ind := strings.Repeat(" ", depth)
|
||||
attrs := attrString(el.Attrs)
|
||||
switch el.Kind {
|
||||
case "rect":
|
||||
fmt.Fprintf(b, `%s<rect x="%s" y="%s" width="%s" height="%s"%s/>`+"\n",
|
||||
ind, num(el.Nums[0]), num(el.Nums[1]), num(el.Nums[2]), num(el.Nums[3]), attrs)
|
||||
case "circle":
|
||||
fmt.Fprintf(b, `%s<circle cx="%s" cy="%s" r="%s"%s/>`+"\n",
|
||||
ind, num(el.Nums[0]), num(el.Nums[1]), num(el.Nums[2]), attrs)
|
||||
case "ellipse":
|
||||
fmt.Fprintf(b, `%s<ellipse cx="%s" cy="%s" rx="%s" ry="%s"%s/>`+"\n",
|
||||
ind, num(el.Nums[0]), num(el.Nums[1]), num(el.Nums[2]), num(el.Nums[3]), attrs)
|
||||
case "line":
|
||||
fmt.Fprintf(b, `%s<line x1="%s" y1="%s" x2="%s" y2="%s"%s/>`+"\n",
|
||||
ind, num(el.Nums[0]), num(el.Nums[1]), num(el.Nums[2]), num(el.Nums[3]), attrs)
|
||||
case "polyline", "polygon":
|
||||
pts := make([]string, len(el.Points))
|
||||
for i, p := range el.Points {
|
||||
pts[i] = num(p[0]) + "," + num(p[1])
|
||||
}
|
||||
fmt.Fprintf(b, `%s<%s points="%s"%s/>`+"\n", ind, el.Kind, strings.Join(pts, " "), attrs)
|
||||
case "path":
|
||||
fmt.Fprintf(b, `%s<path d="%s"%s/>`+"\n", ind, escape(el.D), attrs)
|
||||
case "text":
|
||||
fmt.Fprintf(b, `%s<text x="%s" y="%s"%s>%s</text>`+"\n",
|
||||
ind, num(el.Nums[0]), num(el.Nums[1]), attrs, escape(el.Text))
|
||||
case "group":
|
||||
fmt.Fprintf(b, "%s<g%s>\n", ind, attrs)
|
||||
for _, kid := range el.Kids {
|
||||
emitElem(b, kid, depth+1)
|
||||
}
|
||||
fmt.Fprintf(b, "%s</g>\n", ind)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults SVG would otherwise pick that surprise agents: lines and
|
||||
// paths get a visible stroke if none set; polyline defaults fill=none
|
||||
// so it doesn't render as a filled blob.
|
||||
func effectiveAttrs(el *Elem) map[string]string {
|
||||
out := map[string]string{}
|
||||
for k, v := range el.Attrs {
|
||||
out[k] = v
|
||||
}
|
||||
switch el.Kind {
|
||||
case "line", "polyline":
|
||||
if out["stroke"] == "" {
|
||||
out["stroke"] = "black"
|
||||
}
|
||||
if el.Kind == "polyline" && out["fill"] == "" {
|
||||
out["fill"] = "none"
|
||||
}
|
||||
case "path":
|
||||
if out["stroke"] == "" && out["fill"] == "" {
|
||||
out["stroke"] = "black"
|
||||
out["fill"] = "none"
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func attrString(attrs map[string]string) string {
|
||||
if len(attrs) == 0 {
|
||||
return ""
|
||||
}
|
||||
keys := make([]string, 0, len(attrs))
|
||||
for k := range attrs {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
var b strings.Builder
|
||||
for _, k := range keys {
|
||||
fmt.Fprintf(&b, ` %s="%s"`, k, escape(attrs[k]))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func num(f float64) string {
|
||||
return strconv.FormatFloat(f, 'f', -1, 64)
|
||||
}
|
||||
|
||||
func escape(s string) string {
|
||||
r := strings.NewReplacer("&", "&", "<", "<", ">", ">", `"`, """)
|
||||
return r.Replace(s)
|
||||
}
|
||||
|
||||
// normalize applies the effective attrs (visibility defaults) onto the
|
||||
// tree before emit/raster so both outputs agree.
|
||||
func (d *Doc) normalize() {
|
||||
var walk func(els []*Elem)
|
||||
walk = func(els []*Elem) {
|
||||
for _, el := range els {
|
||||
el.Attrs = effectiveAttrs(el)
|
||||
if el.Kind == "group" {
|
||||
walk(el.Kids)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(d.Elems)
|
||||
}
|
||||
|
||||
// Build parses src and emits SVG in one step.
|
||||
func Build(src string) (string, *Doc, error) {
|
||||
doc, err := Parse(src)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
doc.normalize()
|
||||
return Emit(doc), doc, nil
|
||||
}
|
||||
143
svg-maker/svg/info.go
Normal file
143
svg-maker/svg/info.go
Normal file
@@ -0,0 +1,143 @@
|
||||
package svg
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Info summarizes a parsed document: element counts, colors, the
|
||||
// drawing's bounding box and warnings (things drawn outside the
|
||||
// canvas), so an agent can verify a build without looking at pixels.
|
||||
func Info(d *Doc) string {
|
||||
counts := map[string]int{}
|
||||
colors := map[string]bool{}
|
||||
minX, minY := math.Inf(1), math.Inf(1)
|
||||
maxX, maxY := math.Inf(-1), math.Inf(-1)
|
||||
var warnings []string
|
||||
|
||||
var walk func(els []*Elem)
|
||||
walk = func(els []*Elem) {
|
||||
for _, el := range els {
|
||||
if el.Kind == "group" {
|
||||
counts["group"]++
|
||||
walk(el.Kids)
|
||||
continue
|
||||
}
|
||||
counts[el.Kind]++
|
||||
for _, key := range []string{"fill", "stroke"} {
|
||||
if c := el.Attrs[key]; c != "" && c != "none" && c != "transparent" {
|
||||
colors[c] = true
|
||||
}
|
||||
}
|
||||
x0, y0, x1, y1, ok := bbox(el)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
minX = math.Min(minX, x0)
|
||||
minY = math.Min(minY, y0)
|
||||
maxX = math.Max(maxX, x1)
|
||||
maxY = math.Max(maxY, y1)
|
||||
if x1 < 0 || y1 < 0 || x0 > d.W || y0 > d.H {
|
||||
warnings = append(warnings, fmt.Sprintf("line %d: %s is entirely outside the canvas", el.Line, el.Kind))
|
||||
} else if x0 < 0 || y0 < 0 || x1 > d.W || y1 > d.H {
|
||||
warnings = append(warnings, fmt.Sprintf("line %d: %s sticks outside the canvas", el.Line, el.Kind))
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(d.Elems)
|
||||
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "canvas: %gx%g", d.W, d.H)
|
||||
if d.Bg != "" {
|
||||
fmt.Fprintf(&b, " bg: %s", d.Bg)
|
||||
}
|
||||
b.WriteString("\n")
|
||||
kinds := make([]string, 0, len(counts))
|
||||
for k := range counts {
|
||||
kinds = append(kinds, k)
|
||||
}
|
||||
sort.Strings(kinds)
|
||||
total := 0
|
||||
parts := make([]string, 0, len(kinds))
|
||||
for _, k := range kinds {
|
||||
parts = append(parts, fmt.Sprintf("%s:%d", k, counts[k]))
|
||||
if k != "group" {
|
||||
total += counts[k]
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&b, "elements: %d (%s)\n", total, strings.Join(parts, " "))
|
||||
if len(colors) > 0 {
|
||||
cl := make([]string, 0, len(colors))
|
||||
for c := range colors {
|
||||
cl = append(cl, c)
|
||||
}
|
||||
sort.Strings(cl)
|
||||
fmt.Fprintf(&b, "colors: %s\n", strings.Join(cl, " "))
|
||||
}
|
||||
if total > 0 && !math.IsInf(minX, 1) {
|
||||
fmt.Fprintf(&b, "drawing bbox: %.4g,%.4g .. %.4g,%.4g\n", minX, minY, maxX, maxY)
|
||||
}
|
||||
for _, w := range warnings {
|
||||
fmt.Fprintf(&b, "warning: %s\n", w)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// bbox computes an element's geometric bounding box (stroke width and
|
||||
// transforms not included — good enough for out-of-canvas warnings).
|
||||
func bbox(el *Elem) (x0, y0, x1, y1 float64, ok bool) {
|
||||
switch el.Kind {
|
||||
case "rect":
|
||||
return el.Nums[0], el.Nums[1], el.Nums[0] + el.Nums[2], el.Nums[1] + el.Nums[3], true
|
||||
case "circle":
|
||||
cx, cy, r := el.Nums[0], el.Nums[1], el.Nums[2]
|
||||
return cx - r, cy - r, cx + r, cy + r, true
|
||||
case "ellipse":
|
||||
cx, cy, rx, ry := el.Nums[0], el.Nums[1], el.Nums[2], el.Nums[3]
|
||||
return cx - rx, cy - ry, cx + rx, cy + ry, true
|
||||
case "line":
|
||||
return math.Min(el.Nums[0], el.Nums[2]), math.Min(el.Nums[1], el.Nums[3]),
|
||||
math.Max(el.Nums[0], el.Nums[2]), math.Max(el.Nums[1], el.Nums[3]), true
|
||||
case "polyline", "polygon":
|
||||
return pointsBBox(el.Points)
|
||||
case "path":
|
||||
subs, err := flattenPath(el.D)
|
||||
if err != nil {
|
||||
return 0, 0, 0, 0, false
|
||||
}
|
||||
var all [][2]float64
|
||||
for _, sp := range subs {
|
||||
all = append(all, sp...)
|
||||
}
|
||||
return pointsBBox(all)
|
||||
case "text":
|
||||
size := attrFloat(el.Attrs, "font-size", 16)
|
||||
w := 0.6 * size * float64(len([]rune(el.Text)))
|
||||
x, y := el.Nums[0], el.Nums[1]
|
||||
switch el.Attrs["text-anchor"] {
|
||||
case "middle":
|
||||
x -= w / 2
|
||||
case "end":
|
||||
x -= w
|
||||
}
|
||||
return x, y - size, x + w, y, true
|
||||
}
|
||||
return 0, 0, 0, 0, false
|
||||
}
|
||||
|
||||
func pointsBBox(pts [][2]float64) (x0, y0, x1, y1 float64, ok bool) {
|
||||
if len(pts) == 0 {
|
||||
return 0, 0, 0, 0, false
|
||||
}
|
||||
x0, y0 = pts[0][0], pts[0][1]
|
||||
x1, y1 = x0, y0
|
||||
for _, p := range pts {
|
||||
x0 = math.Min(x0, p[0])
|
||||
y0 = math.Min(y0, p[1])
|
||||
x1 = math.Max(x1, p[0])
|
||||
y1 = math.Max(y1, p[1])
|
||||
}
|
||||
return x0, y0, x1, y1, true
|
||||
}
|
||||
430
svg-maker/svg/parse.go
Normal file
430
svg-maker/svg/parse.go
Normal file
@@ -0,0 +1,430 @@
|
||||
// Package svg turns .svgd text descriptions into SVG images an agent
|
||||
// can verify: build (emit XML), preview (terminal raster) and info
|
||||
// (measurements + warnings).
|
||||
package svg
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Elem is one drawing element. Kind decides which fields matter:
|
||||
//
|
||||
// rect Nums: x y w h
|
||||
// circle Nums: cx cy r
|
||||
// ellipse Nums: cx cy rx ry
|
||||
// line Nums: x1 y1 x2 y2
|
||||
// polyline Points
|
||||
// polygon Points
|
||||
// path D (subset: M L H V C Q Z, absolute + relative)
|
||||
// text Nums: x y, Text
|
||||
// group Kids (inherits its Attrs to children)
|
||||
type Elem struct {
|
||||
Kind string
|
||||
Nums []float64
|
||||
Points [][2]float64
|
||||
D string
|
||||
Text string
|
||||
Attrs map[string]string
|
||||
Line int
|
||||
Kids []*Elem
|
||||
}
|
||||
|
||||
// Doc is a parsed .svgd file.
|
||||
type Doc struct {
|
||||
W, H float64
|
||||
Bg string
|
||||
Elems []*Elem
|
||||
}
|
||||
|
||||
// attrKeys maps .svgd attribute names to SVG presentation attributes.
|
||||
// Friendly aliases keep the format short; unknown keys are errors so
|
||||
// typos surface at build time instead of becoming invisible SVG.
|
||||
var attrKeys = map[string]string{
|
||||
"fill": "fill",
|
||||
"stroke": "stroke",
|
||||
"stroke-width": "stroke-width",
|
||||
"width": "stroke-width", // common shorthand on line/path
|
||||
"opacity": "opacity",
|
||||
"fill-opacity": "fill-opacity",
|
||||
"stroke-opacity": "stroke-opacity",
|
||||
"rx": "rx",
|
||||
"ry": "ry",
|
||||
"anchor": "text-anchor",
|
||||
"size": "font-size",
|
||||
"font": "font-family",
|
||||
"dash": "stroke-dasharray",
|
||||
"linecap": "stroke-linecap",
|
||||
"linejoin": "stroke-linejoin",
|
||||
"transform": "transform",
|
||||
"id": "id",
|
||||
}
|
||||
|
||||
// flag attributes expand to fixed key/values.
|
||||
var flagAttrs = map[string][2]string{
|
||||
"bold": {"font-weight", "bold"},
|
||||
"italic": {"font-style", "italic"},
|
||||
}
|
||||
|
||||
type parser struct {
|
||||
defs map[string]string
|
||||
line int
|
||||
}
|
||||
|
||||
// Parse reads a .svgd document.
|
||||
func Parse(src string) (*Doc, error) {
|
||||
p := &parser{defs: map[string]string{}}
|
||||
doc := &Doc{W: 100, H: 100}
|
||||
sawCanvas := false
|
||||
|
||||
stack := []*[]*Elem{&doc.Elems} // group nesting; top = current container
|
||||
groupLines := []int{}
|
||||
|
||||
for i, raw := range strings.Split(src, "\n") {
|
||||
p.line = i + 1
|
||||
line := strings.TrimSpace(raw)
|
||||
if idx := findComment(line); idx >= 0 {
|
||||
line = strings.TrimSpace(line[:idx])
|
||||
}
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
tokens, err := tokenize(line)
|
||||
if err != nil {
|
||||
return nil, p.errf("%v", err)
|
||||
}
|
||||
kind, rest := tokens[0], tokens[1:]
|
||||
|
||||
switch kind {
|
||||
case "canvas":
|
||||
nums, _, err := p.numsAndAttrs(rest, 2, "canvas needs: canvas <width> <height>")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if nums[0] <= 0 || nums[1] <= 0 {
|
||||
return nil, p.errf("canvas size must be positive")
|
||||
}
|
||||
doc.W, doc.H = nums[0], nums[1]
|
||||
sawCanvas = true
|
||||
|
||||
case "bg":
|
||||
if len(rest) != 1 {
|
||||
return nil, p.errf("bg needs: bg <color>")
|
||||
}
|
||||
c, err := p.color(rest[0])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
doc.Bg = c
|
||||
|
||||
case "def":
|
||||
if len(rest) != 2 {
|
||||
return nil, p.errf("def needs: def <name> <color>")
|
||||
}
|
||||
c, err := p.color(rest[1])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.defs[rest[0]] = c
|
||||
|
||||
case "group":
|
||||
attrs, err := p.attrs(rest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
g := &Elem{Kind: "group", Attrs: attrs, Line: p.line}
|
||||
*stack[len(stack)-1] = append(*stack[len(stack)-1], g)
|
||||
stack = append(stack, &g.Kids)
|
||||
groupLines = append(groupLines, p.line)
|
||||
|
||||
case "end":
|
||||
if len(stack) == 1 {
|
||||
return nil, p.errf("end without group")
|
||||
}
|
||||
stack = stack[:len(stack)-1]
|
||||
groupLines = groupLines[:len(groupLines)-1]
|
||||
|
||||
default:
|
||||
el, err := p.element(kind, rest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
*stack[len(stack)-1] = append(*stack[len(stack)-1], el)
|
||||
}
|
||||
}
|
||||
if len(stack) > 1 {
|
||||
return nil, fmt.Errorf("line %d: group is never closed (missing end)", groupLines[len(groupLines)-1])
|
||||
}
|
||||
if !sawCanvas {
|
||||
return nil, fmt.Errorf("missing canvas line (canvas <width> <height>)")
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (p *parser) element(kind string, rest []string) (*Elem, error) {
|
||||
el := &Elem{Kind: kind, Line: p.line}
|
||||
var err error
|
||||
switch kind {
|
||||
case "rect":
|
||||
el.Nums, el.Attrs, err = p.numsAndAttrs(rest, 4, "rect needs: rect <x> <y> <w> <h>")
|
||||
case "circle":
|
||||
el.Nums, el.Attrs, err = p.numsAndAttrs(rest, 3, "circle needs: circle <cx> <cy> <r>")
|
||||
case "ellipse":
|
||||
el.Nums, el.Attrs, err = p.numsAndAttrs(rest, 4, "ellipse needs: ellipse <cx> <cy> <rx> <ry>")
|
||||
case "line":
|
||||
el.Nums, el.Attrs, err = p.numsAndAttrs(rest, 4, "line needs: line <x1> <y1> <x2> <y2>")
|
||||
case "polyline", "polygon":
|
||||
el.Points, el.Attrs, err = p.pointsAndAttrs(rest, kind)
|
||||
case "path":
|
||||
var attrs map[string]string
|
||||
var dParts []string
|
||||
split := len(rest)
|
||||
for i, t := range rest {
|
||||
if strings.Contains(t, "=") {
|
||||
split = i
|
||||
break
|
||||
}
|
||||
dParts = append(dParts, t)
|
||||
}
|
||||
attrs, err = p.attrs(rest[split:])
|
||||
el.D, el.Attrs = strings.Join(dParts, " "), attrs
|
||||
if err == nil && el.D == "" {
|
||||
err = p.errf("path needs path data (e.g. path M0,0 L10,10 Z)")
|
||||
}
|
||||
if err == nil {
|
||||
if _, ferr := flattenPath(el.D); ferr != nil {
|
||||
err = p.errf("bad path data: %v", ferr)
|
||||
}
|
||||
}
|
||||
case "text":
|
||||
if len(rest) < 3 {
|
||||
return nil, p.errf(`text needs: text <x> <y> "string" [attrs]`)
|
||||
}
|
||||
var nums []float64
|
||||
nums, err = p.nums(rest[:2], 2, "text needs numeric x y")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
el.Nums = nums
|
||||
el.Text = rest[2]
|
||||
el.Attrs, err = p.attrs(rest[3:])
|
||||
default:
|
||||
return nil, p.errf("unknown element %q (rect, circle, ellipse, line, polyline, polygon, path, text, group, def, bg, canvas)", kind)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return el, nil
|
||||
}
|
||||
|
||||
func (p *parser) numsAndAttrs(tokens []string, n int, hint string) ([]float64, map[string]string, error) {
|
||||
if len(tokens) < n {
|
||||
return nil, nil, p.errf("%s", hint)
|
||||
}
|
||||
nums, err := p.nums(tokens[:n], n, hint)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
attrs, err := p.attrs(tokens[n:])
|
||||
return nums, attrs, err
|
||||
}
|
||||
|
||||
func (p *parser) nums(tokens []string, n int, hint string) ([]float64, error) {
|
||||
if len(tokens) != n {
|
||||
return nil, p.errf("%s", hint)
|
||||
}
|
||||
out := make([]float64, n)
|
||||
for i, t := range tokens {
|
||||
v, err := strconv.ParseFloat(t, 64)
|
||||
if err != nil {
|
||||
return nil, p.errf("%q is not a number — %s", t, hint)
|
||||
}
|
||||
out[i] = v
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (p *parser) pointsAndAttrs(tokens []string, kind string) ([][2]float64, map[string]string, error) {
|
||||
var pts [][2]float64
|
||||
i := 0
|
||||
for ; i < len(tokens); i++ {
|
||||
t := tokens[i]
|
||||
if strings.Contains(t, "=") {
|
||||
break
|
||||
}
|
||||
xy := strings.Split(t, ",")
|
||||
if len(xy) != 2 {
|
||||
return nil, nil, p.errf("%s point %q must be x,y", kind, t)
|
||||
}
|
||||
x, err1 := strconv.ParseFloat(xy[0], 64)
|
||||
y, err2 := strconv.ParseFloat(xy[1], 64)
|
||||
if err1 != nil || err2 != nil {
|
||||
return nil, nil, p.errf("%s point %q must be numeric x,y", kind, t)
|
||||
}
|
||||
pts = append(pts, [2]float64{x, y})
|
||||
}
|
||||
min := 2
|
||||
if kind == "polygon" {
|
||||
min = 3
|
||||
}
|
||||
if len(pts) < min {
|
||||
return nil, nil, p.errf("%s needs at least %d x,y points", kind, min)
|
||||
}
|
||||
attrs, err := p.attrs(tokens[i:])
|
||||
return pts, attrs, err
|
||||
}
|
||||
|
||||
func (p *parser) attrs(tokens []string) (map[string]string, error) {
|
||||
out := map[string]string{}
|
||||
for _, t := range tokens {
|
||||
if kv, ok := flagAttrs[t]; ok {
|
||||
out[kv[0]] = kv[1]
|
||||
continue
|
||||
}
|
||||
eq := strings.Index(t, "=")
|
||||
if eq <= 0 {
|
||||
return nil, p.errf("expected attribute key=value, got %q", t)
|
||||
}
|
||||
key, val := t[:eq], t[eq+1:]
|
||||
svgKey, ok := attrKeys[key]
|
||||
if !ok {
|
||||
return nil, p.errf("unknown attribute %q", key)
|
||||
}
|
||||
if val == "" {
|
||||
return nil, p.errf("attribute %s has empty value", key)
|
||||
}
|
||||
if key == "fill" || key == "stroke" {
|
||||
c, err := p.color(val)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
val = c
|
||||
}
|
||||
if key == "transform" {
|
||||
// commas keep the value one token: rotate(45,50,50)
|
||||
val = strings.ReplaceAll(val, ",", " ")
|
||||
}
|
||||
out[svgKey] = val
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// color resolves $vars and validates the value.
|
||||
func (p *parser) color(v string) (string, error) {
|
||||
if strings.HasPrefix(v, "$") {
|
||||
c, ok := p.defs[v[1:]]
|
||||
if !ok {
|
||||
return "", p.errf("undefined color variable %s (define it first: def %s #rrggbb)", v, v[1:])
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
if v == "none" || v == "transparent" {
|
||||
return v, nil
|
||||
}
|
||||
if strings.HasPrefix(v, "#") {
|
||||
hexPart := v[1:]
|
||||
if len(hexPart) != 3 && len(hexPart) != 6 {
|
||||
return "", p.errf("color %q must be #rgb or #rrggbb", v)
|
||||
}
|
||||
for _, r := range hexPart {
|
||||
if !strings.ContainsRune("0123456789abcdefABCDEF", r) {
|
||||
return "", p.errf("color %q has non-hex digits", v)
|
||||
}
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
for _, r := range v {
|
||||
if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') {
|
||||
return "", p.errf("color %q must be #hex, a CSS color name, none or $var", v)
|
||||
}
|
||||
}
|
||||
return v, nil // CSS named color — trust the renderer
|
||||
}
|
||||
|
||||
func (p *parser) errf(format string, args ...interface{}) error {
|
||||
return fmt.Errorf("line %d: %s", p.line, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// tokenize splits a line on whitespace, keeping "quoted strings" as
|
||||
// single tokens (quotes stripped).
|
||||
func tokenize(line string) ([]string, error) {
|
||||
var out []string
|
||||
var cur strings.Builder
|
||||
inQuote := false
|
||||
for _, r := range line {
|
||||
switch {
|
||||
case r == '"':
|
||||
if inQuote {
|
||||
out = append(out, cur.String())
|
||||
cur.Reset()
|
||||
inQuote = false
|
||||
} else {
|
||||
inQuote = true
|
||||
}
|
||||
case !inQuote && (r == ' ' || r == '\t'):
|
||||
if cur.Len() > 0 {
|
||||
out = append(out, cur.String())
|
||||
cur.Reset()
|
||||
}
|
||||
default:
|
||||
cur.WriteRune(r)
|
||||
}
|
||||
}
|
||||
if inQuote {
|
||||
return nil, fmt.Errorf("unterminated quote")
|
||||
}
|
||||
if cur.Len() > 0 {
|
||||
out = append(out, cur.String())
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil, fmt.Errorf("empty line")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// findComment returns the index of a # starting a comment (not inside
|
||||
// quotes, and not part of a color like #fff).
|
||||
func findComment(line string) int {
|
||||
inQuote := false
|
||||
for i, r := range line {
|
||||
if r == '"' {
|
||||
inQuote = !inQuote
|
||||
}
|
||||
if r == '#' && !inQuote {
|
||||
// a color literal follows =, whitespace-then-hex is a comment
|
||||
if i == 0 {
|
||||
return 0
|
||||
}
|
||||
prev := line[i-1]
|
||||
if prev == ' ' || prev == '\t' {
|
||||
// "... # comment" vs "def accent #fff": colors only appear
|
||||
// after def/bg or key=; a bare hex after a def/bg keyword is
|
||||
// data, so only treat as comment if it is not valid hex-ish
|
||||
rest := line[i+1:]
|
||||
stop := strings.IndexAny(rest, " \t")
|
||||
word := rest
|
||||
if stop >= 0 {
|
||||
word = rest[:stop]
|
||||
}
|
||||
if isHexWord(word) {
|
||||
continue
|
||||
}
|
||||
return i
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func isHexWord(w string) bool {
|
||||
if len(w) != 3 && len(w) != 6 {
|
||||
return false
|
||||
}
|
||||
for _, r := range w {
|
||||
if !strings.ContainsRune("0123456789abcdefABCDEF", r) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
195
svg-maker/svg/path.go
Normal file
195
svg-maker/svg/path.go
Normal file
@@ -0,0 +1,195 @@
|
||||
package svg
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// flattenPath turns a path-data subset (M L H V C Q Z, absolute and
|
||||
// relative) into one or more polylines, used for validation, preview
|
||||
// rasterization and measurements. Curves become 16 line segments.
|
||||
func flattenPath(d string) ([][][2]float64, error) {
|
||||
tokens, err := pathTokens(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var subpaths [][][2]float64
|
||||
var cur [][2]float64
|
||||
var x, y, startX, startY float64
|
||||
i := 0
|
||||
cmd := ""
|
||||
|
||||
need := func(n int) ([]float64, error) {
|
||||
if i+n > len(tokens) {
|
||||
return nil, fmt.Errorf("command %s needs %d numbers", cmd, n)
|
||||
}
|
||||
out := make([]float64, n)
|
||||
for j := 0; j < n; j++ {
|
||||
v, err := strconv.ParseFloat(tokens[i+j], 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("command %s: %q is not a number", cmd, tokens[i+j])
|
||||
}
|
||||
out[j] = v
|
||||
}
|
||||
i += n
|
||||
return out, nil
|
||||
}
|
||||
flush := func() {
|
||||
if len(cur) > 1 {
|
||||
subpaths = append(subpaths, cur)
|
||||
}
|
||||
cur = nil
|
||||
}
|
||||
|
||||
for i < len(tokens) {
|
||||
t := tokens[i]
|
||||
if len(t) == 1 && strings.ContainsAny(t, "MLHVCQZmlhvcqz") {
|
||||
cmd = t
|
||||
i++
|
||||
if cmd == "Z" || cmd == "z" {
|
||||
if len(cur) > 0 {
|
||||
cur = append(cur, [2]float64{startX, startY})
|
||||
x, y = startX, startY
|
||||
}
|
||||
flush()
|
||||
continue
|
||||
}
|
||||
} else if cmd == "" {
|
||||
return nil, fmt.Errorf("path must start with M/m, got %q", t)
|
||||
}
|
||||
// repeated coordinate groups reuse the current command
|
||||
rel := cmd >= "a" // lowercase = relative
|
||||
switch strings.ToUpper(cmd) {
|
||||
case "M":
|
||||
n, err := need(2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rel {
|
||||
n[0] += x
|
||||
n[1] += y
|
||||
}
|
||||
flush()
|
||||
x, y = n[0], n[1]
|
||||
startX, startY = x, y
|
||||
cur = [][2]float64{{x, y}}
|
||||
cmd = map[bool]string{true: "l", false: "L"}[rel] // subsequent pairs are implicit lineto
|
||||
case "L":
|
||||
n, err := need(2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rel {
|
||||
n[0] += x
|
||||
n[1] += y
|
||||
}
|
||||
x, y = n[0], n[1]
|
||||
cur = append(cur, [2]float64{x, y})
|
||||
case "H":
|
||||
n, err := need(1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rel {
|
||||
n[0] += x
|
||||
}
|
||||
x = n[0]
|
||||
cur = append(cur, [2]float64{x, y})
|
||||
case "V":
|
||||
n, err := need(1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rel {
|
||||
n[0] += y
|
||||
}
|
||||
y = n[0]
|
||||
cur = append(cur, [2]float64{x, y})
|
||||
case "Q":
|
||||
n, err := need(4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rel {
|
||||
n[0] += x
|
||||
n[1] += y
|
||||
n[2] += x
|
||||
n[3] += y
|
||||
}
|
||||
for s := 1; s <= 16; s++ {
|
||||
t := float64(s) / 16
|
||||
u := 1 - t
|
||||
px := u*u*x + 2*u*t*n[0] + t*t*n[2]
|
||||
py := u*u*y + 2*u*t*n[1] + t*t*n[3]
|
||||
cur = append(cur, [2]float64{px, py})
|
||||
}
|
||||
x, y = n[2], n[3]
|
||||
case "C":
|
||||
n, err := need(6)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rel {
|
||||
n[0] += x
|
||||
n[1] += y
|
||||
n[2] += x
|
||||
n[3] += y
|
||||
n[4] += x
|
||||
n[5] += y
|
||||
}
|
||||
for s := 1; s <= 16; s++ {
|
||||
t := float64(s) / 16
|
||||
u := 1 - t
|
||||
px := u*u*u*x + 3*u*u*t*n[0] + 3*u*t*t*n[2] + t*t*t*n[4]
|
||||
py := u*u*u*y + 3*u*u*t*n[1] + 3*u*t*t*n[3] + t*t*t*n[5]
|
||||
cur = append(cur, [2]float64{px, py})
|
||||
}
|
||||
x, y = n[4], n[5]
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported path command %q (supported: M L H V C Q Z)", cmd)
|
||||
}
|
||||
}
|
||||
flush()
|
||||
if len(subpaths) == 0 {
|
||||
return nil, fmt.Errorf("path draws nothing")
|
||||
}
|
||||
return subpaths, nil
|
||||
}
|
||||
|
||||
// pathTokens splits path data into command letters and numbers.
|
||||
func pathTokens(d string) ([]string, error) {
|
||||
var out []string
|
||||
var cur strings.Builder
|
||||
flush := func() {
|
||||
if cur.Len() > 0 {
|
||||
out = append(out, cur.String())
|
||||
cur.Reset()
|
||||
}
|
||||
}
|
||||
for _, r := range d {
|
||||
switch {
|
||||
case r == ' ' || r == '\t' || r == ',':
|
||||
flush()
|
||||
case (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z'):
|
||||
flush()
|
||||
out = append(out, string(r))
|
||||
case (r >= '0' && r <= '9') || r == '.' || r == 'e' || r == 'E':
|
||||
cur.WriteRune(r)
|
||||
case r == '-' || r == '+':
|
||||
// sign starts a new number unless it follows an exponent
|
||||
s := cur.String()
|
||||
if cur.Len() > 0 && !strings.HasSuffix(s, "e") && !strings.HasSuffix(s, "E") {
|
||||
flush()
|
||||
}
|
||||
cur.WriteRune(r)
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected character %q in path data", r)
|
||||
}
|
||||
}
|
||||
flush()
|
||||
if len(out) == 0 {
|
||||
return nil, fmt.Errorf("empty path data")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
332
svg-maker/svg/raster.go
Normal file
332
svg-maker/svg/raster.go
Normal file
@@ -0,0 +1,332 @@
|
||||
package svg
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Raster renders the document to a small RGBA grid so an agent can see
|
||||
// roughly what it drew without an image viewer. Painter's algorithm in
|
||||
// document order, 2x2 supersampling, honors fill/stroke/opacity.
|
||||
// Text is approximated by its baseline and an underline-box (real
|
||||
// glyph rendering is out of scope for a preview).
|
||||
type Raster struct {
|
||||
W, H int
|
||||
Pix [][4]float64 // r g b a, premultiplied-ish blend target
|
||||
}
|
||||
|
||||
type rgba struct{ r, g, b, a float64 }
|
||||
|
||||
// RenderGrid rasterizes doc to cols pixels wide (rows follow aspect).
|
||||
func RenderGrid(d *Doc, cols int) *Raster {
|
||||
if cols < 8 {
|
||||
cols = 8
|
||||
}
|
||||
if cols > 400 {
|
||||
cols = 400
|
||||
}
|
||||
rows := int(math.Round(float64(cols) * d.H / d.W))
|
||||
if rows < 1 {
|
||||
rows = 1
|
||||
}
|
||||
if rows > 400 {
|
||||
rows = 400
|
||||
}
|
||||
r := &Raster{W: cols, H: rows, Pix: make([][4]float64, cols*rows)}
|
||||
bg := parseColor(d.Bg)
|
||||
if d.Bg == "" {
|
||||
bg = rgba{0, 0, 0, 0}
|
||||
}
|
||||
for i := range r.Pix {
|
||||
r.Pix[i] = [4]float64{bg.r, bg.g, bg.b, bg.a}
|
||||
}
|
||||
scaleX := d.W / float64(cols)
|
||||
scaleY := d.H / float64(rows)
|
||||
|
||||
var walk func(els []*Elem, inherited map[string]string)
|
||||
walk = func(els []*Elem, inherited map[string]string) {
|
||||
for _, el := range els {
|
||||
attrs := merged(inherited, el.Attrs)
|
||||
if el.Kind == "group" {
|
||||
walk(el.Kids, attrs)
|
||||
continue
|
||||
}
|
||||
r.drawElem(el, attrs, scaleX, scaleY)
|
||||
}
|
||||
}
|
||||
walk(d.Elems, nil)
|
||||
return r
|
||||
}
|
||||
|
||||
func merged(parent, child map[string]string) map[string]string {
|
||||
if parent == nil {
|
||||
return child
|
||||
}
|
||||
out := map[string]string{}
|
||||
for k, v := range parent {
|
||||
out[k] = v
|
||||
}
|
||||
for k, v := range child {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *Raster) drawElem(el *Elem, attrs map[string]string, sx, sy float64) {
|
||||
fill, hasFill := paint(attrs, "fill", el.Kind)
|
||||
stroke, hasStroke := paint(attrs, "stroke", el.Kind)
|
||||
sw := attrFloat(attrs, "stroke-width", 1)
|
||||
opacity := attrFloat(attrs, "opacity", 1)
|
||||
|
||||
inFill, inStroke := coverageFuncs(el, sw, attrs)
|
||||
if inFill == nil && inStroke == nil {
|
||||
return
|
||||
}
|
||||
for py := 0; py < r.H; py++ {
|
||||
for px := 0; px < r.W; px++ {
|
||||
var fillCov, strokeCov float64
|
||||
for _, dx := range []float64{0.25, 0.75} {
|
||||
for _, dy := range []float64{0.25, 0.75} {
|
||||
ux := (float64(px) + dx) * sx
|
||||
uy := (float64(py) + dy) * sy
|
||||
if hasFill && inFill != nil && inFill(ux, uy) {
|
||||
fillCov += 0.25
|
||||
}
|
||||
if hasStroke && inStroke != nil && inStroke(ux, uy) {
|
||||
strokeCov += 0.25
|
||||
}
|
||||
}
|
||||
}
|
||||
if fillCov > 0 {
|
||||
r.blend(px, py, fill, fillCov*opacity*attrFloat(attrs, "fill-opacity", 1))
|
||||
}
|
||||
if strokeCov > 0 {
|
||||
r.blend(px, py, stroke, strokeCov*opacity*attrFloat(attrs, "stroke-opacity", 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// coverageFuncs returns point-inside tests for the fill body and the
|
||||
// stroke band of an element, in user coordinates.
|
||||
func coverageFuncs(el *Elem, sw float64, attrs map[string]string) (inFill, inStroke func(x, y float64) bool) {
|
||||
half := sw / 2
|
||||
switch el.Kind {
|
||||
case "rect":
|
||||
x0, y0, w, h := el.Nums[0], el.Nums[1], el.Nums[2], el.Nums[3]
|
||||
inFill = func(x, y float64) bool { return x >= x0 && x <= x0+w && y >= y0 && y <= y0+h }
|
||||
inStroke = func(x, y float64) bool {
|
||||
near := func(v, edge float64) bool { return math.Abs(v-edge) <= half }
|
||||
inX := x >= x0-half && x <= x0+w+half
|
||||
inY := y >= y0-half && y <= y0+h+half
|
||||
return (inX && (near(y, y0) || near(y, y0+h))) || (inY && (near(x, x0) || near(x, x0+w)))
|
||||
}
|
||||
case "circle":
|
||||
cx, cy, rad := el.Nums[0], el.Nums[1], el.Nums[2]
|
||||
inFill = func(x, y float64) bool { return math.Hypot(x-cx, y-cy) <= rad }
|
||||
inStroke = func(x, y float64) bool { return math.Abs(math.Hypot(x-cx, y-cy)-rad) <= half }
|
||||
case "ellipse":
|
||||
cx, cy, rx, ry := el.Nums[0], el.Nums[1], el.Nums[2], el.Nums[3]
|
||||
if rx <= 0 || ry <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
norm := func(x, y float64) float64 {
|
||||
dx, dy := (x-cx)/rx, (y-cy)/ry
|
||||
return math.Sqrt(dx*dx + dy*dy)
|
||||
}
|
||||
inFill = func(x, y float64) bool { return norm(x, y) <= 1 }
|
||||
inStroke = func(x, y float64) bool {
|
||||
// approximate band by comparing scaled radial distance
|
||||
n := norm(x, y)
|
||||
tol := half / math.Min(rx, ry)
|
||||
return math.Abs(n-1) <= tol
|
||||
}
|
||||
case "line":
|
||||
seg := [2][2]float64{{el.Nums[0], el.Nums[1]}, {el.Nums[2], el.Nums[3]}}
|
||||
inStroke = func(x, y float64) bool { return distSeg(x, y, seg[0], seg[1]) <= math.Max(half, 0.5) }
|
||||
case "polyline", "polygon":
|
||||
pts := el.Points
|
||||
inStroke = func(x, y float64) bool {
|
||||
last := len(pts) - 1
|
||||
for i := 0; i < last; i++ {
|
||||
if distSeg(x, y, pts[i], pts[i+1]) <= math.Max(half, 0.5) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if el.Kind == "polygon" && distSeg(x, y, pts[last], pts[0]) <= math.Max(half, 0.5) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
if el.Kind == "polygon" {
|
||||
inFill = func(x, y float64) bool { return pointInPolygon(x, y, pts) }
|
||||
}
|
||||
case "path":
|
||||
subs, err := flattenPath(el.D)
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
inStroke = func(x, y float64) bool {
|
||||
for _, sp := range subs {
|
||||
for i := 0; i < len(sp)-1; i++ {
|
||||
if distSeg(x, y, sp[i], sp[i+1]) <= math.Max(half, 0.5) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
inFill = func(x, y float64) bool {
|
||||
in := false
|
||||
for _, sp := range subs {
|
||||
if pointInPolygon(x, y, sp) {
|
||||
in = !in
|
||||
}
|
||||
}
|
||||
return in
|
||||
}
|
||||
case "text":
|
||||
// baseline box: width ~0.6em per char, height 1em above the
|
||||
// baseline, honoring text-anchor — real glyphs are out of scope
|
||||
size := attrFloat(attrs, "font-size", 16)
|
||||
x0, y0 := el.Nums[0], el.Nums[1]
|
||||
w := 0.6 * size * float64(len([]rune(el.Text)))
|
||||
switch attrs["text-anchor"] {
|
||||
case "middle":
|
||||
x0 -= w / 2
|
||||
case "end":
|
||||
x0 -= w
|
||||
}
|
||||
edge := math.Max(size/12, 0.75)
|
||||
inFill = func(x, y float64) bool {
|
||||
return x >= x0 && x <= x0+w && y >= y0-size && y <= y0 &&
|
||||
(y >= y0-edge || y <= y0-size+edge || x <= x0+edge || x >= x0+w-edge)
|
||||
}
|
||||
}
|
||||
return inFill, inStroke
|
||||
}
|
||||
|
||||
func paint(attrs map[string]string, key, kind string) (rgba, bool) {
|
||||
v := attrs[key]
|
||||
if v == "" {
|
||||
if key == "fill" && kind != "line" && kind != "polyline" && kind != "path" {
|
||||
return rgba{0, 0, 0, 1}, true // SVG default fill is black
|
||||
}
|
||||
return rgba{}, false
|
||||
}
|
||||
if v == "none" || v == "transparent" {
|
||||
return rgba{}, false
|
||||
}
|
||||
return parseColor(v), true
|
||||
}
|
||||
|
||||
func attrFloat(attrs map[string]string, key string, def float64) float64 {
|
||||
if v, ok := attrs[key]; ok {
|
||||
if f, err := strconv.ParseFloat(v, 64); err == nil {
|
||||
return f
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func (r *Raster) blend(x, y int, c rgba, a float64) {
|
||||
if a <= 0 {
|
||||
return
|
||||
}
|
||||
if a > 1 {
|
||||
a = 1
|
||||
}
|
||||
i := y*r.W + x
|
||||
p := r.Pix[i]
|
||||
p[0] = c.r*a + p[0]*(1-a)
|
||||
p[1] = c.g*a + p[1]*(1-a)
|
||||
p[2] = c.b*a + p[2]*(1-a)
|
||||
p[3] = math.Max(p[3], a)
|
||||
r.Pix[i] = p
|
||||
}
|
||||
|
||||
func distSeg(x, y float64, a, b [2]float64) float64 {
|
||||
dx, dy := b[0]-a[0], b[1]-a[1]
|
||||
l2 := dx*dx + dy*dy
|
||||
if l2 == 0 {
|
||||
return math.Hypot(x-a[0], y-a[1])
|
||||
}
|
||||
t := ((x-a[0])*dx + (y-a[1])*dy) / l2
|
||||
t = math.Max(0, math.Min(1, t))
|
||||
return math.Hypot(x-(a[0]+t*dx), y-(a[1]+t*dy))
|
||||
}
|
||||
|
||||
func pointInPolygon(x, y float64, pts [][2]float64) bool {
|
||||
in := false
|
||||
n := len(pts)
|
||||
for i, j := 0, n-1; i < n; j, i = i, i+1 {
|
||||
xi, yi := pts[i][0], pts[i][1]
|
||||
xj, yj := pts[j][0], pts[j][1]
|
||||
if (yi > y) != (yj > y) && x < (xj-xi)*(y-yi)/(yj-yi)+xi {
|
||||
in = !in
|
||||
}
|
||||
}
|
||||
return in
|
||||
}
|
||||
|
||||
// parseColor handles #rgb/#rrggbb plus the CSS names agents actually
|
||||
// use; unknown names render mid-gray rather than failing the preview.
|
||||
func parseColor(s string) rgba {
|
||||
s = strings.TrimSpace(strings.ToLower(s))
|
||||
if strings.HasPrefix(s, "#") {
|
||||
h := s[1:]
|
||||
if len(h) == 3 {
|
||||
h = string([]byte{h[0], h[0], h[1], h[1], h[2], h[2]})
|
||||
}
|
||||
if len(h) == 6 {
|
||||
r, err1 := strconv.ParseUint(h[0:2], 16, 8)
|
||||
g, err2 := strconv.ParseUint(h[2:4], 16, 8)
|
||||
b, err3 := strconv.ParseUint(h[4:6], 16, 8)
|
||||
if err1 == nil && err2 == nil && err3 == nil {
|
||||
return rgba{float64(r), float64(g), float64(b), 1}
|
||||
}
|
||||
}
|
||||
}
|
||||
if c, ok := cssColors[s]; ok {
|
||||
return c
|
||||
}
|
||||
return rgba{128, 128, 128, 1}
|
||||
}
|
||||
|
||||
var cssColors = map[string]rgba{
|
||||
"black": {0, 0, 0, 1}, "white": {255, 255, 255, 1}, "red": {255, 0, 0, 1},
|
||||
"green": {0, 128, 0, 1}, "lime": {0, 255, 0, 1}, "blue": {0, 0, 255, 1},
|
||||
"yellow": {255, 255, 0, 1}, "orange": {255, 165, 0, 1}, "purple": {128, 0, 128, 1},
|
||||
"gray": {128, 128, 128, 1}, "grey": {128, 128, 128, 1}, "silver": {192, 192, 192, 1},
|
||||
"cyan": {0, 255, 255, 1}, "magenta": {255, 0, 255, 1}, "pink": {255, 192, 203, 1},
|
||||
"brown": {165, 42, 42, 1}, "navy": {0, 0, 128, 1}, "teal": {0, 128, 128, 1},
|
||||
"olive": {128, 128, 0, 1}, "maroon": {128, 0, 0, 1}, "aqua": {0, 255, 255, 1},
|
||||
"fuchsia": {255, 0, 255, 1}, "gold": {255, 215, 0, 1},
|
||||
}
|
||||
|
||||
// ANSI renders the raster with truecolor half-blocks, two pixel rows
|
||||
// per text row — same technique as spritec's preview.
|
||||
func (r *Raster) ANSI() string {
|
||||
const reset = "\x1b[0m"
|
||||
var b strings.Builder
|
||||
for y := 0; y < r.H; y += 2 {
|
||||
for x := 0; x < r.W; x++ {
|
||||
top := r.Pix[y*r.W+x]
|
||||
var bot [4]float64
|
||||
if y+1 < r.H {
|
||||
bot = r.Pix[(y+1)*r.W+x]
|
||||
}
|
||||
if top[3] == 0 && bot[3] == 0 {
|
||||
b.WriteString(" ")
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&b, "\x1b[38;2;%d;%d;%dm\x1b[48;2;%d;%d;%dm▀%s",
|
||||
int(top[0]), int(top[1]), int(top[2]),
|
||||
int(bot[0]), int(bot[1]), int(bot[2]), reset)
|
||||
}
|
||||
b.WriteString("\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
201
svg-maker/svg/svg_test.go
Normal file
201
svg-maker/svg/svg_test.go
Normal file
@@ -0,0 +1,201 @@
|
||||
package svg
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const sample = `# test scene
|
||||
canvas 100 80
|
||||
bg #112233
|
||||
def accent #4f9cf9
|
||||
rect 10 10 30 20 fill=$accent rx=3
|
||||
circle 70 30 15 fill=#3fca7c stroke=white stroke-width=2
|
||||
line 0 70 100 70 stroke=red width=3
|
||||
polygon 10,60 30,40 50,60 fill=#e0a63f
|
||||
path M60,60 L80,70 L90,50 Z stroke=white
|
||||
text 50 25 "hi & <you>" size=10 fill=white anchor=middle
|
||||
group stroke=gray
|
||||
line 5 5 15 15
|
||||
end
|
||||
`
|
||||
|
||||
func TestParseAndEmit(t *testing.T) {
|
||||
xml, doc, err := Build(sample)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if doc.W != 100 || doc.H != 80 || doc.Bg != "#112233" {
|
||||
t.Errorf("canvas/bg wrong: %+v", doc)
|
||||
}
|
||||
for _, want := range []string{
|
||||
`viewBox="0 0 100 80"`,
|
||||
`<rect x="10" y="10" width="30" height="20"`,
|
||||
`fill="#4f9cf9"`, // $accent resolved
|
||||
`rx="3"`,
|
||||
`<circle cx="70" cy="30" r="15"`,
|
||||
`stroke-width="3"`, // width alias
|
||||
`<polygon points="10,60 30,40 50,60"`,
|
||||
`<path d="M60,60 L80,70 L90,50 Z"`,
|
||||
`hi & <you>`, // escaped text
|
||||
`text-anchor="middle"`,
|
||||
`font-size="10"`,
|
||||
`<g stroke="gray">`,
|
||||
} {
|
||||
if !strings.Contains(xml, want) {
|
||||
t.Errorf("emitted SVG missing %q\n%s", want, xml)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseErrorsCarryLineNumbers(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"canvas 100 100\nrect 1 2 3": "line 2",
|
||||
"canvas 100 100\nrect 1 2 3 four": "not a number",
|
||||
"canvas 100 100\ncircle 1 2 3 glow=yes": "unknown attribute",
|
||||
"canvas 100 100\nrect 1 2 3 4 fill=$missing": "undefined color variable",
|
||||
"canvas 100 100\nblob 1 2": "unknown element",
|
||||
"canvas 100 100\ngroup\nline 1 2 3 4": "never closed",
|
||||
"canvas 100 100\nend": "end without group",
|
||||
"canvas 100 100\npath X10,10": "path",
|
||||
"canvas 100 100\nrect 1 2 3 4 fill=#zzz": "non-hex",
|
||||
"rect 1 2 3 4": "missing canvas",
|
||||
}
|
||||
for src, want := range cases {
|
||||
_, _, err := Build(src)
|
||||
if err == nil {
|
||||
t.Errorf("no error for %q", src)
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("error for %q = %q, want substring %q", src, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisibilityDefaults(t *testing.T) {
|
||||
xml, _, err := Build("canvas 10 10\nline 0 0 10 10\npolyline 0,0 5,5 10,0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(xml, `<line x1="0" y1="0" x2="10" y2="10" stroke="black"/>`) {
|
||||
t.Errorf("line did not get default stroke:\n%s", xml)
|
||||
}
|
||||
if !strings.Contains(xml, `fill="none"`) {
|
||||
t.Errorf("polyline did not get fill=none:\n%s", xml)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlattenPath(t *testing.T) {
|
||||
subs, err := flattenPath("M0,0 L10,0 V10 H0 Z")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(subs) != 1 {
|
||||
t.Fatalf("want 1 subpath, got %d", len(subs))
|
||||
}
|
||||
pts := subs[0]
|
||||
last := pts[len(pts)-1]
|
||||
if last[0] != 0 || last[1] != 0 {
|
||||
t.Errorf("Z should close back to start, ended at %v", last)
|
||||
}
|
||||
// curves flatten into many segments
|
||||
subs, err = flattenPath("M0,0 Q50,100 100,0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(subs[0]) < 10 {
|
||||
t.Errorf("quadratic should flatten to many points, got %d", len(subs[0]))
|
||||
}
|
||||
// relative commands
|
||||
subs, err = flattenPath("m10,10 l10,0 l0,10 z")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := subs[0][2]; got[0] != 20 || got[1] != 20 {
|
||||
t.Errorf("relative path point = %v, want 20,20", got)
|
||||
}
|
||||
if _, err := flattenPath("L10,10"); err == nil {
|
||||
t.Error("path not starting with M should fail")
|
||||
}
|
||||
if _, err := flattenPath("M0,0 A5,5 0 0 1 10,10"); err == nil {
|
||||
t.Error("unsupported arc command should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRasterShapes(t *testing.T) {
|
||||
doc, err := Parse("canvas 100 100\nbg black\ncircle 50 50 30 fill=red")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
doc.normalize()
|
||||
r := RenderGrid(doc, 50)
|
||||
if r.W != 50 || r.H != 50 {
|
||||
t.Fatalf("grid %dx%d, want 50x50", r.W, r.H)
|
||||
}
|
||||
center := r.Pix[25*r.W+25]
|
||||
if center[0] < 200 || center[1] > 50 {
|
||||
t.Errorf("center should be red, got %v", center)
|
||||
}
|
||||
corner := r.Pix[0]
|
||||
if corner[0] > 50 && corner[1] > 50 && corner[2] > 50 {
|
||||
t.Errorf("corner should be black, got %v", corner)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRasterPolygonFill(t *testing.T) {
|
||||
doc, err := Parse("canvas 100 100\npolygon 0,0 100,0 100,100 0,100 fill=#00ff00")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
doc.normalize()
|
||||
r := RenderGrid(doc, 20)
|
||||
mid := r.Pix[10*r.W+10]
|
||||
if mid[1] < 200 {
|
||||
t.Errorf("polygon interior not filled: %v", mid)
|
||||
}
|
||||
}
|
||||
|
||||
func TestANSIPreviewShape(t *testing.T) {
|
||||
doc, _ := Parse("canvas 40 20\nbg #000000\nrect 0 0 40 20 fill=white")
|
||||
doc.normalize()
|
||||
out := RenderGrid(doc, 40).ANSI()
|
||||
lines := strings.Split(strings.TrimRight(out, "\n"), "\n")
|
||||
if len(lines) != 10 { // 20 pixel rows / 2 per text row
|
||||
t.Errorf("ANSI preview has %d rows, want 10", len(lines))
|
||||
}
|
||||
if !strings.Contains(out, "▀") {
|
||||
t.Error("preview contains no half-block characters")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInfoWarnsOutsideCanvas(t *testing.T) {
|
||||
doc, err := Parse("canvas 50 50\ncircle 25 25 10 fill=red\nrect 100 100 20 20 fill=blue\nline 40 40 60 60")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
doc.normalize()
|
||||
info := Info(doc)
|
||||
for _, want := range []string{
|
||||
"canvas: 50x50",
|
||||
"circle:1",
|
||||
"entirely outside",
|
||||
"sticks outside",
|
||||
} {
|
||||
if !strings.Contains(info, want) {
|
||||
t.Errorf("info missing %q:\n%s", want, info)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupAttrInheritanceInRaster(t *testing.T) {
|
||||
doc, err := Parse("canvas 10 10\ngroup fill=#ff0000\nrect 0 0 10 10\nend")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
doc.normalize()
|
||||
r := RenderGrid(doc, 10)
|
||||
if p := r.Pix[5*r.W+5]; p[0] < 200 {
|
||||
t.Errorf("group fill not inherited: %v", p)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user