Debian Codegraph @

shiny/iconvg/decode_test.go

raw symbols SCIP
1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package iconvg
6
7 import (
8 "bytes"
9 "fmt"
10 "image"
11 "image/color"
12 "image/draw"
13 "image/png"
14 "os"
15 "path/filepath"
16 "runtime"
17 "strings"
18 "testing"
19
20 "golang.org/x/image/math/f32"
21 )
22
23 // disassemble returns a disassembly of an encoded IconVG graphic. Users of
24 // this package aren't expected to want to do this, so it lives in a _test.go
25 // file, but it can be useful for debugging.
26 func disassemble(src []byte) ([]byte, error) {
27 w := new(bytes.Buffer)
28 p := func(b []byte, format string, args ...interface{}) {
29 const hex = "0123456789abcdef"
30 var buf [14]byte
31 for i := range buf {
32 buf[i] = ' '
33 }
34 for i, x := range b {
35 buf[3*i+0] = hex[x>>4]
36 buf[3*i+1] = hex[x&0x0f]
37 }
38 w.Write(buf[:])
39 fmt.Fprintf(w, format, args...)
40 }
41 m := Metadata{}
42 if err := decode(nil, p, &m, false, buffer(src), nil); err != nil {
43 return nil, err
44 }
45 return w.Bytes(), nil
46 }
47
48 var (
49 _ Destination = (*Encoder)(nil)
50 _ Destination = (*Rasterizer)(nil)
51 )
52
53 func encodePNG(dstFilename string, src image.Image) error {
54 f, err := os.Create(dstFilename)
55 if err != nil {
56 return err
57 }
58 encErr := png.Encode(f, src)
59 closeErr := f.Close()
60 if encErr != nil {
61 return encErr
62 }
63 return closeErr
64 }
65
66 func decodePNG(srcFilename string) (image.Image, error) {
67 f, err := os.Open(srcFilename)
68 if err != nil {
69 return nil, err
70 }
71 defer f.Close()
72 return png.Decode(f)
73 }
74
75 func checkApproxEqual(m0, m1 image.Image) error {
76 diff := func(a, b uint32) uint32 {
77 if a < b {
78 return b - a
79 }
80 return a - b
81 }
82
83 bounds0 := m0.Bounds()
84 bounds1 := m1.Bounds()
85 if bounds0 != bounds1 {
86 return fmt.Errorf("bounds differ: got %v, want %v", bounds0, bounds1)
87 }
88 for y := bounds0.Min.Y; y < bounds0.Max.Y; y++ {
89 for x := bounds0.Min.X; x < bounds0.Max.X; x++ {
90 r0, g0, b0, a0 := m0.At(x, y).RGBA()
91 r1, g1, b1, a1 := m1.At(x, y).RGBA()
92
93 // TODO: be more principled in picking this magic threshold, other
94 // than what the difference is, in practice, in x/image/vector's
95 // fixed and floating point rasterizer?
96 const D = 0xffff * 12 / 100 // Diff threshold of 12%.
97
98 if diff(r0, r1) > D || diff(g0, g1) > D || diff(b0, b1) > D || diff(a0, a1) > D {
99 return fmt.Errorf("at (%d, %d):\n"+
100 "got RGBA %#04x, %#04x, %#04x, %#04x\n"+
101 "want RGBA %#04x, %#04x, %#04x, %#04x",
102 x, y, r0, g0, b0, a0, r1, g1, b1, a1)
103 }
104 }
105 }
106 return nil
107 }
108
109 func diffLines(t *testing.T, got, want string) {
110 gotLines := strings.Split(got, "\n")
111 wantLines := strings.Split(want, "\n")
112 for i := 1; ; i++ {
113 if len(gotLines) == 0 {
114 t.Errorf("line %d:\ngot %q\nwant %q", i, "", wantLines[0])
115 return
116 }
117 if len(wantLines) == 0 {
118 t.Errorf("line %d:\ngot %q\nwant %q", i, gotLines[0], "")
119 return
120 }
121 g, w := gotLines[0], wantLines[0]
122 gotLines = gotLines[1:]
123 wantLines = wantLines[1:]
124 if g != w {
125 t.Errorf("line %d:\ngot %q\nwant %q", i, g, w)
126 return
127 }
128 }
129 }
130
131 var testdataTestCases = []struct {
132 filename string
133 variants string
134 }{
135 {"testdata/action-info.lores", ""},
136 {"testdata/action-info.hires", ""},
137 {"testdata/arcs", ""},
138 {"testdata/blank", ""},
139 {"testdata/cowbell", ""},
140 {"testdata/elliptical", ""},
141 {"testdata/favicon", ";pink"},
142 {"testdata/gradient", ""},
143 {"testdata/lod-polygon", ";64"},
144 {"testdata/video-005.primitive", ""},
145 }
146
147 func TestDisassembly(t *testing.T) {
148 for _, tc := range testdataTestCases {
149 ivgData, err := os.ReadFile(filepath.FromSlash(tc.filename) + ".ivg")
150 if err != nil {
151 t.Errorf("%s: ReadFile: %v", tc.filename, err)
152 continue
153 }
154 got, err := disassemble(ivgData)
155 if err != nil {
156 t.Errorf("%s: disassemble: %v", tc.filename, err)
157 continue
158 }
159 wantFilename := filepath.FromSlash(tc.filename) + ".ivg.disassembly"
160 if *updateFlag {
161 if err := os.WriteFile(filepath.FromSlash(wantFilename), got, 0666); err != nil {
162 t.Errorf("%s: WriteFile: %v", tc.filename, err)
163 }
164 continue
165 }
166 want, err := os.ReadFile(wantFilename)
167 if err != nil {
168 t.Errorf("%s: ReadFile: %v", tc.filename, err)
169 continue
170 }
171 if !bytes.Equal(got, want) {
172 t.Errorf("%s: got:\n%s\nwant:\n%s", tc.filename, got, want)
173 diffLines(t, string(got), string(want))
174 }
175 }
176 }
177
178 // The IconVG decoder and encoder are expected to be completely deterministic,
179 // so check that we get the original bytes after a decode + encode round-trip.
180 func TestDecodeEncodeRoundTrip(t *testing.T) {
181 for _, tc := range testdataTestCases {
182 ivgData, err := os.ReadFile(filepath.FromSlash(tc.filename) + ".ivg")
183 if err != nil {
184 t.Errorf("%s: ReadFile: %v", tc.filename, err)
185 continue
186 }
187 var e resolutionPreservingEncoder
188 e.HighResolutionCoordinates = strings.HasSuffix(tc.filename, ".hires")
189 if err := Decode(&e, ivgData, nil); err != nil {
190 t.Errorf("%s: Decode: %v", tc.filename, err)
191 continue
192 }
193 got, err := e.Bytes()
194 if err != nil {
195 t.Errorf("%s: Encoder.Bytes: %v", tc.filename, err)
196 continue
197 }
198 if want := ivgData; !bytes.Equal(got, want) {
199 t.Errorf("%s:\ngot %d bytes (on GOOS=%s GOARCH=%s, using compiler %q):\n% x\nwant %d bytes:\n% x",
200 tc.filename, len(got), runtime.GOOS, runtime.GOARCH, runtime.Compiler, got, len(want), want)
201 gotDisasm, err1 := disassemble(got)
202 wantDisasm, err2 := disassemble(want)
203 if err1 == nil && err2 == nil {
204 diffLines(t, string(gotDisasm), string(wantDisasm))
205 }
206 }
207 }
208 }
209
210 // resolutionPreservingEncoder is an Encoder
211 // whose Reset method keeps prior resolution.
212 type resolutionPreservingEncoder struct {
213 Encoder
214 }
215
216 // Reset resets the Encoder for the given Metadata.
217 //
218 // Unlike Encoder.Reset, it leaves the value
219 // of e.HighResolutionCoordinates unmodified.
220 func (e *resolutionPreservingEncoder) Reset(m Metadata) {
221 orig := e.HighResolutionCoordinates
222 e.Encoder.Reset(m)
223 e.HighResolutionCoordinates = orig
224 }
225
226 func TestDecodeAndRasterize(t *testing.T) {
227 for _, tc := range testdataTestCases {
228 ivgData, err := os.ReadFile(filepath.FromSlash(tc.filename) + ".ivg")
229 if err != nil {
230 t.Errorf("%s: ReadFile: %v", tc.filename, err)
231 continue
232 }
233 md, err := DecodeMetadata(ivgData)
234 if err != nil {
235 t.Errorf("%s: DecodeMetadata: %v", tc.filename, err)
236 continue
237 }
238
239 for _, variant := range strings.Split(tc.variants, ";") {
240 length := 256
241 if variant == "64" {
242 length = 64
243 }
244 width, height := length, length
245 if dx, dy := md.ViewBox.AspectRatio(); dx < dy {
246 width = int(float32(length) * dx / dy)
247 } else {
248 height = int(float32(length) * dy / dx)
249 }
250
251 opts := &DecodeOptions{}
252 if variant == "pink" {
253 pal := DefaultPalette
254 pal[0] = color.RGBA{0xfe, 0x76, 0xea, 0xff}
255 opts.Palette = &pal
256 }
257
258 got := image.NewRGBA(image.Rect(0, 0, width, height))
259 var z Rasterizer
260 z.SetDstImage(got, got.Bounds(), draw.Src)
261 if err := Decode(&z, ivgData, opts); err != nil {
262 t.Errorf("%s %q variant: Decode: %v", tc.filename, variant, err)
263 continue
264 }
265
266 wantFilename := filepath.FromSlash(tc.filename)
267 if variant != "" {
268 wantFilename += "." + variant
269 }
270 wantFilename += ".png"
271 if *updateFlag {
272 if err := encodePNG(filepath.FromSlash(wantFilename), got); err != nil {
273 t.Errorf("%s %q variant: encodePNG: %v", tc.filename, variant, err)
274 }
275 continue
276 }
277 want, err := decodePNG(wantFilename)
278 if err != nil {
279 t.Errorf("%s %q variant: decodePNG: %v", tc.filename, variant, err)
280 continue
281 }
282 if err := checkApproxEqual(got, want); err != nil {
283 t.Errorf("%s %q variant: %v", tc.filename, variant, err)
284 continue
285 }
286 }
287 }
288 }
289
290 func TestInvalidAlphaPremultipliedColor(t *testing.T) {
291 // See http://golang.org/issue/39526 for some discussion.
292
293 dst := image.NewRGBA(image.Rect(0, 0, 1, 1))
294 var z Rasterizer
295 z.SetDstImage(dst, dst.Bounds(), draw.Over)
296 z.Reset(Metadata{
297 ViewBox: Rectangle{
298 Min: f32.Vec2{0.0, 0.0},
299 Max: f32.Vec2{1.0, 1.0},
300 },
301 })
302
303 // Fill the unit square with red.
304 z.SetCReg(0, false, RGBAColor(color.RGBA{0x55, 0x00, 0x00, 0x66}))
305 z.StartPath(0, 0.0, 0.0)
306 z.AbsLineTo(1.0, 0.0)
307 z.AbsLineTo(1.0, 1.0)
308 z.AbsLineTo(0.0, 1.0)
309 z.ClosePathEndPath()
310
311 // Fill the unit square with an invalid (non-gradient) alpha-premultiplied
312 // color (super-saturated green). This should be a no-op (and not crash).
313 z.SetCReg(0, false, RGBAColor(color.RGBA{0x00, 0x99, 0x00, 0x88}))
314 z.StartPath(0, 0.0, 0.0)
315 z.AbsLineTo(1.0, 0.0)
316 z.AbsLineTo(1.0, 1.0)
317 z.AbsLineTo(0.0, 1.0)
318 z.ClosePathEndPath()
319
320 // We should see red.
321 got := dst.Pix
322 want := []byte{0x55, 0x00, 0x00, 0x66}
323 if !bytes.Equal(got, want) {
324 t.Errorf("got [% 02x], want [% 02x]", got, want)
325 }
326 }
327
328 func TestBlendColor(t *testing.T) {
329 // This example comes from doc.go. Look for "orange" in the "Colors"
330 // section.
331 pal := Palette{
332 2: color.RGBA{0xff, 0xcc, 0x80, 0xff}, // "Material Design Orange 200".
333 }
334 cReg := [64]color.RGBA{}
335 got := BlendColor(0x40, 0x7f, 0x82).Resolve(&pal, &cReg)
336 want := color.RGBA{0x40, 0x33, 0x20, 0x40} // 25% opaque "Orange 200", alpha-premultiplied.
337 if got != want {
338 t.Errorf("\ngot %x\nwant %x", got, want)
339 }
340 }