fit_test.go raw
1 // SPDX-License-Identifier: Unlicense OR MIT
2
3 package widget
4
5 import (
6 "bytes"
7 "encoding/binary"
8 "image"
9 "math"
10 "testing"
11
12 "github.com/p9c/p9/pkg/gel/gio/f32"
13 "github.com/p9c/p9/pkg/gel/gio/layout"
14 "github.com/p9c/p9/pkg/gel/gio/op"
15 )
16
17 func TestFit(t *testing.T) {
18 type test struct {
19 Dims image.Point
20 Scale f32.Point
21 Result image.Point
22 }
23
24 fittests := [...][]test{
25 Unscaled: {
26 {
27 Dims: image.Point{0, 0},
28 Scale: f32.Point{X: 1, Y: 1},
29 Result: image.Point{X: 0, Y: 0},
30 }, {
31 Dims: image.Point{50, 25},
32 Scale: f32.Point{X: 1, Y: 1},
33 Result: image.Point{X: 50, Y: 25},
34 }, {
35 Dims: image.Point{50, 200},
36 Scale: f32.Point{X: 1, Y: 1},
37 Result: image.Point{X: 50, Y: 100},
38 }},
39 Contain: {
40 {
41 Dims: image.Point{50, 25},
42 Scale: f32.Point{X: 2, Y: 2},
43 Result: image.Point{X: 100, Y: 50},
44 }, {
45 Dims: image.Point{50, 200},
46 Scale: f32.Point{X: 0.5, Y: 0.5},
47 Result: image.Point{X: 25, Y: 100},
48 }},
49 Cover: {
50 {
51 Dims: image.Point{50, 25},
52 Scale: f32.Point{X: 4, Y: 4},
53 Result: image.Point{X: 100, Y: 100},
54 }, {
55 Dims: image.Point{50, 200},
56 Scale: f32.Point{X: 2, Y: 2},
57 Result: image.Point{X: 100, Y: 100},
58 }},
59 ScaleDown: {
60 {
61 Dims: image.Point{50, 25},
62 Scale: f32.Point{X: 1, Y: 1},
63 Result: image.Point{X: 50, Y: 25},
64 }, {
65 Dims: image.Point{50, 200},
66 Scale: f32.Point{X: 0.5, Y: 0.5},
67 Result: image.Point{X: 25, Y: 100},
68 }},
69 Fill: {
70 {
71 Dims: image.Point{50, 25},
72 Scale: f32.Point{X: 2, Y: 4},
73 Result: image.Point{X: 100, Y: 100},
74 }, {
75 Dims: image.Point{50, 200},
76 Scale: f32.Point{X: 2, Y: 0.5},
77 Result: image.Point{X: 100, Y: 100},
78 }},
79 }
80
81 for fit, tests := range fittests {
82 fit := Fit(fit)
83 for i, test := range tests {
84 ops := new(op.Ops)
85 gtx := layout.Context{
86 Ops: ops,
87 Constraints: layout.Constraints{
88 Max: image.Point{X: 100, Y: 100},
89 },
90 }
91
92 result := fit.scale(gtx, layout.NW, layout.Dimensions{Size: test.Dims})
93
94 if test.Scale.X != 1 || test.Scale.Y != 1 {
95 opsdata := gtx.Ops.Data()
96 scaleX := float32Bytes(test.Scale.X)
97 scaleY := float32Bytes(test.Scale.Y)
98 if !bytes.Contains(opsdata, scaleX) {
99 t.Errorf("did not find scale.X:%v (%x) in ops: %x", test.Scale.X, scaleX, opsdata)
100 }
101 if !bytes.Contains(opsdata, scaleY) {
102 t.Errorf("did not find scale.Y:%v (%x) in ops: %x", test.Scale.Y, scaleY, opsdata)
103 }
104 }
105
106 if result.Size != test.Result {
107 t.Errorf("fit %v, #%v: expected %#v, got %#v", fit, i, test.Result, result.Size)
108 }
109 }
110 }
111 }
112
113 func float32Bytes(v float32) []byte {
114 var dst [4]byte
115 binary.LittleEndian.PutUint32(dst[:], math.Float32bits(v))
116 return dst[:]
117 }
118