Debian Codegraph @

vendor/github.com/xyproto/tinysvg/tinysvg.go

raw
1 // Package tinysvg supports generating and writing TinySVG 1.2 images
2 //
3 // Some function names are suffixed with "2" if they take structs instead of ints/floats,
4 // "i" if they take ints and "f" if they take floats. Using generics might be an option.
5 package tinysvg
6
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "strconv"
12 "strings"
13 )
14
15 const (
16 TRANSPARENT = 0.0
17 OPAQUE = 1.0
18
19 NO = iota
20 YES
21 AUTO
22 )
23
24 type (
25 Vec2 struct {
26 X, Y float64
27 }
28
29 Pos Vec2
30 Radius Vec2
31
32 Size struct {
33 W, H float64
34 }
35
36 Color struct {
37 R, G, B int // red, green, blue (0..255)
38 A float64 // alpha, 0.0..1.0
39 N string // name (optional, will override the above values)
40 }
41
42 Font struct {
43 Family string
44 Size int
45 }
46
47 YesNoAuto int
48 )
49
50 const (
51 xmlVersionEncoding = `<?xml version="1.0" encoding="UTF-8"?>`
52 xmlNS = "http://www.w3.org/2000/svg"
53 svgTag = "svg"
54 svgProfile = "tiny"
55 svgVersion = "1.2"
56 )
57
58 var (
59 ErrPair = errors.New("position pairs must be exactly two comma separated numbers")
60 sizeOne = Size{1.0, 1.0}
61 )
62
63 // NewTinySVG will create a new TinySVG document, where the width and height is defined in pixels, using the "px" suffix.
64 func NewTinySVG(w, h int) (*Document, *Tag) {
65 page := NewDocument([]byte{}, []byte(xmlVersionEncoding))
66 svg := page.root.AddNewTag([]byte(svgTag))
67 // Add attributes to the tag
68 svg.AddAttribMap(map[string][]byte{
69 "xmlns": []byte(xmlNS),
70 "version": []byte(svgVersion),
71 "baseProfile": []byte(svgProfile),
72 "viewBox": []byte(fmt.Sprintf("%d %d %d %d", 0, 0, w, h)),
73 "width": []byte(fmt.Sprintf("%dpx", w)),
74 "height": []byte(fmt.Sprintf("%dpx", h)),
75 })
76 return page, svg
77 }
78
79 // NewTinySVG2 creates new TinySVG 1.2 image. Pos and Size defines the viewbox
80 func NewTinySVG2(p *Pos, s *Size) (*Document, *Tag) {
81 // No page title is needed when building an SVG tag tree
82 page := NewDocument([]byte{}, []byte(xmlVersionEncoding))
83
84 // No longer needed for TinySVG 1.2. See: https://www.w3.org/TR/SVGTiny12/intro.html#defining
85 // <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Tiny//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd">
86
87 // Add the root tag
88 svg := page.root.AddNewTag([]byte(svgTag))
89 // Add attributes to the tag
90 svg.AddAttribMap(map[string][]byte{
91 "xmlns": []byte(xmlNS),
92 "version": []byte(svgVersion),
93 "baseProfile": []byte(svgProfile),
94 "viewBox": []byte(fmt.Sprintf("%f %f %f %f", p.X, p.Y, s.W, s.H)),
95 })
96 return page, svg
97 }
98
99 // f2b converts the given float64 to a string representation.
100 // .0 or .000000 suffixes are stripped.
101 // The string is returned as a byte slice.
102 func f2b(x float64) []byte {
103 return []byte(strings.TrimSuffix(strings.TrimSuffix(fmt.Sprintf("%f", x), ".0"), ".000000"))
104 }
105
106 // Rect2 creates a rectangle, given x and y position, width and height.
107 // No color is being set.
108 func (svg *Tag) Rect2(p *Pos, s *Size, c *Color) *Tag {
109 rect := svg.AddNewTag([]byte("rect"))
110 rect.AddAttribMap(map[string][]byte{
111 "x": f2b(p.X),
112 "y": f2b(p.Y),
113 "width": f2b(s.W),
114 "height": f2b(s.H),
115 })
116 rect.Fill2(c)
117 return rect
118 }
119
120 // RoundedRect2 a rectangle, given x and y position, width and height.
121 // No color is being set.
122 func (svg *Tag) RoundedRect2(p *Pos, r *Radius, s *Size, c *Color) *Tag {
123 rect := svg.AddNewTag([]byte("rect"))
124 rect.AddAttribMap(map[string][]byte{
125 "x": f2b(p.X),
126 "y": f2b(p.Y),
127 "rx": f2b(r.X),
128 "ry": f2b(r.Y),
129 "width": f2b(s.W),
130 "height": f2b(s.H),
131 })
132 rect.Fill2(c)
133 return rect
134 }
135
136 // Text2 adds text. No color is being set
137 func (svg *Tag) Text2(p *Pos, f *Font, message string, c *Color) *Tag {
138 text := svg.AddNewTag([]byte("text"))
139 text.AddAttribMap(map[string][]byte{
140 "x": f2b(p.X),
141 "y": f2b(p.Y),
142 "font-family": []byte(f.Family),
143 "font-size": []byte(strconv.Itoa(f.Size)),
144 })
145 text.Fill2(c)
146 text.AddContent([]byte(message))
147 return text
148 }
149
150 // Circle2 adds a circle, given a position, radius and color
151 func (svg *Tag) Circle2(p *Pos, radius int, c *Color) *Tag {
152 circle := svg.AddNewTag([]byte("circle"))
153 circle.AddAttribMap(map[string][]byte{
154 "cx": f2b(p.X),
155 "cy": f2b(p.Y),
156 "r": []byte(strconv.Itoa(radius)),
157 })
158 circle.Fill2(c)
159 return circle
160 }
161
162 // Circlef adds a circle, given a position, radius and color
163 func (svg *Tag) Circlef(p *Pos, radius float64, c *Color) *Tag {
164 circle := svg.AddNewTag([]byte("circle"))
165 circle.AddAttribMap(map[string][]byte{
166 "cx": f2b(p.X),
167 "cy": f2b(p.Y),
168 "r": f2b(radius),
169 })
170 circle.Fill2(c)
171 return circle
172 }
173
174 // Ellipse2 adds an ellipse with a given position (x,y) and radius (rx, ry).
175 func (svg *Tag) Ellipse2(p *Pos, r *Radius, c *Color) *Tag {
176 ellipse := svg.AddNewTag([]byte("ellipse"))
177 ellipse.AddAttribMap(map[string][]byte{
178 "cx": f2b(p.X),
179 "cy": f2b(p.Y),
180 "rx": f2b(r.X),
181 "ry": f2b(r.Y),
182 })
183 ellipse.Fill2(c)
184 return ellipse
185 }
186
187 // Line2 adds a line from (x1, y1) to (x2, y2) with a given stroke width and color
188 func (svg *Tag) Line2(p1, p2 *Pos, thickness int, c *Color) *Tag {
189 line := svg.AddNewTag([]byte("line"))
190 line.AddAttribMap(map[string][]byte{
191 "x1": f2b(p1.X),
192 "y1": f2b(p1.Y),
193 "x2": f2b(p2.X),
194 "y2": f2b(p2.Y),
195 })
196 line.Thickness(thickness)
197 line.Stroke2(c)
198 return line
199 }
200
201 // Triangle2 adds a colored triangle
202 func (svg *Tag) Triangle2(p1, p2, p3 *Pos, c *Color) *Tag {
203 triangle := svg.AddNewTag([]byte("path"))
204 triangle.AddAttrib("d", []byte(fmt.Sprintf("M %f %f L %f %f L %f %f L %f %f", p1.X, p1.Y, p2.X, p2.Y, p3.X, p3.Y, p1.X, p1.Y)))
205 triangle.Fill2(c)
206 return triangle
207 }
208
209 // Poly2 adds a colored path with 4 points
210 func (svg *Tag) Poly2(p1, p2, p3, p4 *Pos, c *Color) *Tag {
211 poly4 := svg.AddNewTag([]byte("path"))
212 poly4.AddAttrib("d", []byte(fmt.Sprintf("M %f %f L %f %f L %f %f L %f %f L %f %f", p1.X, p1.Y, p2.X, p2.Y, p3.X, p3.Y, p4.X, p4.Y, p1.X, p1.Y)))
213 poly4.Fill2(c)
214 return poly4
215 }
216
217 // Fill2 selects the fill color that will be used when drawing
218 func (svg *Tag) Fill2(c *Color) {
219 // If no color name is given and the color is transparent, don't set a fill color
220 if (c == nil) || (len(c.N) == 0 && c.A == TRANSPARENT) {
221 return
222 }
223 svg.AddAttrib("fill", c.Bytes())
224 }
225
226 // Stroke2 selects the stroke color that will be used when drawing
227 func (svg *Tag) Stroke2(c *Color) {
228 // If no color name is given and the color is transparent, don't set a stroke color
229 if (c == nil) || (len(c.N) == 0 && c.A == TRANSPARENT) {
230 return
231 }
232 svg.AddAttrib("stroke", c.Bytes())
233 }
234
235 // RGBBytes converts r, g and b (integers in the range 0..255)
236 // to a color string on the form "#nnnnnn", returned as a byte slice.
237 // May also return colors strings on the form "#nnn".
238 func RGBBytes(r, g, b int) []byte {
239 rs := strconv.FormatInt(int64(r), 16)
240 gs := strconv.FormatInt(int64(g), 16)
241 bs := strconv.FormatInt(int64(b), 16)
242 if len(rs) == 1 && len(gs) == 1 && len(bs) == 1 {
243 // short form
244 return []byte("#" + rs + gs + bs)
245 }
246 // long form
247 return []byte(fmt.Sprintf("#%02x%02x%02x", r, g, b))
248 }
249
250 // RGBABytes converts integers r, g and b (the color) and also
251 // a given alpha (opacity) to a color-string on the form
252 // "rgba(255, 255, 255, 1.0)".
253 func RGBABytes(r, g, b int, a float64) []byte {
254 return []byte(fmt.Sprintf("rgba(%d, %d, %d, %f)", r, g, b, a))
255 }
256
257 // RGB creates a new Color with the given red, green and blue values.
258 // The colors are in the range 0..255.
259 func RGB(r, g, b int) *Color {
260 return &Color{r, g, b, OPAQUE, ""}
261 }
262
263 // RGBA creates a new Color with the given red, green, blue and alpha values.
264 // Alpha is between 0 and 1, the rest are 0..255.
265 // For the alpha value, 0 is transparent and 1 is opaque.
266 func RGBA(r, g, b int, a float64) *Color {
267 return &Color{r, g, b, a, ""}
268 }
269
270 // ColorByName creates a new Color with a given name, like "blue"
271 func ColorByName(name string) *Color {
272 return &Color{N: name}
273 }
274
275 // NewColor is the same as ColorByName
276 func NewColor(name string) *Color {
277 return ColorByName(name)
278 }
279
280 // Bytes returns the color as an RGB (#1234FF) byte slice,
281 // or as an RGBA (rgba(0, 1, 2 ,3)) byte slice.
282 func (c *Color) Bytes() []byte {
283 // Return an empty string if nil
284 if c == nil {
285 return make([]byte, 0)
286 }
287 // Return the name, if specified
288 if len(c.N) != 0 {
289 return []byte(c.N)
290 }
291 // Return a regular RGB string if alpha is 1.0
292 if c.A == OPAQUE {
293 // Generate a rgb string
294 return RGBBytes(c.R, c.G, c.B)
295 }
296 // Generate a rgba string if alpha is < 1.0
297 return RGBABytes(c.R, c.G, c.B, c.A)
298 }
299
300 // --- Convenience functions and functions for backward compatibility ---
301
302 func NewTinySVGi(x, y, w, h int) (*Document, *Tag) {
303 return NewTinySVG2(&Pos{float64(x), float64(y)}, &Size{float64(w), float64(h)})
304 }
305
306 func NewTinySVGf(x, y, w, h float64) (*Document, *Tag) {
307 return NewTinySVG2(&Pos{x, y}, &Size{w, h})
308 }
309
310 // AddRect adds a rectangle, given x and y position, width and height.
311 // No color is being set.
312 func (svg *Tag) AddRect(x, y, w, h int) *Tag {
313 return svg.Rect2(&Pos{float64(x), float64(y)}, &Size{float64(w), float64(h)}, nil)
314 }
315
316 // AddRoundedRect adds a rectangle, given x and y position, radius x, radius y, width and height.
317 // No color is being set.
318 func (svg *Tag) AddRoundedRect(x, y, rx, ry, w, h int) *Tag {
319 return svg.RoundedRect2(&Pos{float64(x), float64(y)}, &Radius{float64(rx), float64(ry)}, &Size{float64(w), float64(h)}, nil)
320 }
321
322 // AddRectf adds a rectangle, given x and y position, width and height.
323 // No color is being set.
324 func (svg *Tag) AddRectf(x, y, w, h float64) *Tag {
325 return svg.Rect2(&Pos{x, y}, &Size{w, h}, nil)
326 }
327
328 // AddRoundedRectf adds a rectangle, given x and y position, radius x, radius y, width and height.
329 // No color is being set.
330 func (svg *Tag) AddRoundedRectf(x, y, rx, ry, w, h float64) *Tag {
331 return svg.RoundedRect2(&Pos{x, y}, &Radius{rx, ry}, &Size{w, h}, nil)
332 }
333
334 // AddText adds text. No color is being set
335 func (svg *Tag) AddText(x, y, fontSize int, fontFamily, text string) *Tag {
336 return svg.Text2(&Pos{float64(x), float64(y)}, &Font{fontFamily, fontSize}, text, nil)
337 }
338
339 // Box adds a rectangle, given x and y position, width, height and color
340 func (svg *Tag) Box(x, y, w, h int, color string) *Tag {
341 return svg.Rect2(&Pos{float64(x), float64(y)}, &Size{float64(w), float64(h)}, ColorByName(color))
342 }
343
344 // AddCircle adds a circle Add a circle, given a position (x, y) and a radius.
345 // No color is being set.
346 func (svg *Tag) AddCircle(x, y, radius int) *Tag {
347 return svg.Circle2(&Pos{float64(x), float64(y)}, radius, nil)
348 }
349
350 // AddCirclef adds a circle Add a circle, given a position (x, y) and a radius.
351 // No color is being set.
352 func (svg *Tag) AddCirclef(x, y, radius float64) *Tag {
353 return svg.Circlef(&Pos{x, y}, radius, nil)
354 }
355
356 // AddEllipse adds an ellipse with a given position (x,y) and radius (rx, ry).
357 // No color is being set.
358 func (svg *Tag) AddEllipse(x, y, rx, ry int) *Tag {
359 return svg.Ellipse2(&Pos{float64(x), float64(y)}, &Radius{float64(rx), float64(ry)}, nil)
360 }
361
362 // AddEllipsef adds an ellipse with a given position (x,y) and radius (rx, ry).
363 // No color is being set.
364 func (svg *Tag) AddEllipsef(x, y, rx, ry float64) *Tag {
365 return svg.Ellipse2(&Pos{x, y}, &Radius{rx, ry}, nil)
366 }
367
368 // Line adds a line from (x1, y1) to (x2, y2) with a given stroke width and color
369 func (svg *Tag) Line(x1, y1, x2, y2, thickness int, color string) *Tag {
370 return svg.Line2(&Pos{float64(x1), float64(y1)}, &Pos{float64(x2), float64(y2)}, thickness, ColorByName(color))
371 }
372
373 // Triangle adds a colored triangle
374 func (svg *Tag) Triangle(x1, y1, x2, y2, x3, y3 int, color string) *Tag {
375 return svg.Triangle2(&Pos{float64(x1), float64(y1)}, &Pos{float64(x2), float64(y2)}, &Pos{float64(x3), float64(y3)}, ColorByName(color))
376 }
377
378 // Poly4 adds a colored path with 4 points
379 func (svg *Tag) Poly4(x1, y1, x2, y2, x3, y3, x4, y4 int, color string) *Tag {
380 return svg.Poly2(&Pos{float64(x1), float64(y1)}, &Pos{float64(x2), float64(y2)}, &Pos{float64(x3), float64(y3)}, &Pos{float64(x4), float64(y4)}, ColorByName(color))
381 }
382
383 // Circle adds a circle, given x and y position, radius and color
384 func (svg *Tag) Circle(x, y, radius int, color string) *Tag {
385 return svg.Circle2(&Pos{float64(x), float64(y)}, radius, ColorByName(color))
386 }
387
388 // Ellipse adds an ellipse, given x and y position, radiuses and color
389 func (svg *Tag) Ellipse(x, y, xr, yr int, color string) *Tag {
390 return svg.Ellipse2(&Pos{float64(x), float64(y)}, &Radius{float64(xr), float64(yr)}, ColorByName(color))
391 }
392
393 // Fill selects the fill color that will be used when drawing
394 func (svg *Tag) Fill(color string) {
395 svg.AddAttrib("fill", []byte(color))
396 }
397
398 // ColorBytes converts r, g and b (integers in the range 0..255)
399 // to a color string on the form "#nnnnnn".
400 func ColorBytes(r, g, b int) []byte {
401 return RGB(r, g, b).Bytes()
402 }
403
404 // ColorBytesAlpha converts integers r, g and b (the color) and also
405 // a given alpha (opacity) to a color-string on the form
406 // "rgba(255, 255, 255, 1.0)".
407 func ColorBytesAlpha(r, g, b int, a float64) []byte {
408 return RGBA(r, g, b, a).Bytes()
409 }
410
411 // Pixel creates a rectangle that is 1 wide with the given color.
412 // Note that the size of the "pixel" depends on how large the viewBox is.
413 func (svg *Tag) Pixel(x, y, r, g, b int) *Tag {
414 return svg.Rect2(&Pos{float64(x), float64(y)}, &sizeOne, RGB(r, g, b))
415 }
416
417 // AlphaDot creates a small circle that can be transparent.
418 // Takes a position (x, y) and a color (r, g, b, a).
419 func (svg *Tag) AlphaDot(x, y, r, g, b int, a float32) *Tag {
420 return svg.Circle2(&Pos{float64(x), float64(y)}, 1, RGBA(r, g, b, float64(a)))
421 }
422
423 // Dot adds a small colored circle.
424 // Takes a position (x, y) and a color (r, g, b).
425 func (svg *Tag) Dot(x, y, r, g, b int) *Tag {
426 return svg.Circle2(&Pos{float64(x), float64(y)}, 1, RGB(r, g, b))
427 }
428
429 // Text adds text, with a color
430 func (svg *Tag) Text(x, y, fontSize int, fontFamily, text, color string) *Tag {
431 return svg.Text2(&Pos{float64(x), float64(y)}, &Font{fontFamily, fontSize}, text, ColorByName(color))
432 }
433
434 // NewYesNoAuto will create a new Yes/No/Auto struct. If auto is true, it overrides the yes value.
435 func NewYesNoAuto(yes bool, auto bool) YesNoAuto {
436 if auto {
437 return AUTO
438 }
439 if yes {
440 return YES
441 }
442 return NO
443 }
444
445 func (yna YesNoAuto) Bytes() []byte {
446 switch yna {
447 case YES:
448 return []byte("true")
449 case AUTO:
450 return []byte("auto")
451 default:
452 return []byte("false")
453 }
454 }
455
456 // Focusable sets the "focusable" attribute to either true, false or auto
457 // If "auto" is true, it overrides the value of "yes".
458 func (svg *Tag) Focusable(yes bool, auto bool) {
459 svg.AddAttrib("focusable", NewYesNoAuto(yes, auto).Bytes())
460 }
461
462 // Thickness sets the stroke-width attribute
463 func (svg *Tag) Thickness(thickness int) {
464 svg.AddAttrib("stroke-width", []byte(strconv.Itoa(thickness)))
465 }
466
467 // Polyline adds a set of connected straight lines, an open shape
468 func (svg *Tag) Polyline(points []*Pos, c *Color) *Tag {
469 polyline := svg.AddNewTag([]byte("polyline"))
470 var buf bytes.Buffer
471 lastIndex := len(points) - 1
472 for i, p := range points {
473 buf.Write(f2b(p.X))
474 buf.WriteByte(',')
475 buf.Write(f2b(p.Y))
476 if i != lastIndex {
477 buf.WriteByte(' ')
478 }
479 }
480 polyline.AddAttrib("points", buf.Bytes())
481 return polyline
482 }
483
484 // Polygon adds a set of connected straight lines, a closed shape
485 func (svg *Tag) Polygon(points []*Pos, c *Color) *Tag {
486 polygon := svg.AddNewTag([]byte("polygon"))
487 var buf bytes.Buffer
488 lastIndex := len(points) - 1
489 for i, p := range points {
490 buf.Write(f2b(p.X))
491 buf.WriteByte(',')
492 buf.Write(f2b(p.Y))
493 if i != lastIndex {
494 buf.WriteByte(' ')
495 }
496 }
497 polygon.AddAttrib("points", buf.Bytes())
498 polygon.Fill2(c)
499 return polygon
500 }
501
502 func NewPos(xString, yString string) (*Pos, error) {
503 x, err := strconv.ParseFloat(xString, 64)
504 if err != nil {
505 return nil, err
506 }
507 y, err := strconv.ParseFloat(yString, 64)
508 if err != nil {
509 return nil, err
510 }
511 return &Pos{x, y}, nil
512 }
513
514 func NewPosf(x, y float64) *Pos {
515 return &Pos{x, y}
516 }
517
518 func PointsFromString(pointString string) ([]*Pos, error) {
519 points := make([]*Pos, 0)
520 for _, positionPair := range strings.Split(pointString, " ") {
521 elements := strings.Split(positionPair, ",")
522 if len(elements) != 2 {
523 return nil, ErrPair
524 }
525 p, err := NewPos(elements[0], elements[1])
526 if err != nil {
527 return nil, err
528 }
529 points = append(points, p)
530 }
531 return points, nil
532 }
533
534 // Describe can be used for adding a description to the SVG header
535 func (svg *Tag) Describe(description string) {
536 desc := svg.AddNewTag([]byte("desc"))
537 desc.AddContent([]byte(description))
538 }