1 package messeji
2
3 import (
4 "bytes"
5 "embed"
6 "fmt"
7 "image"
8 "sync"
9 "testing"
10
11 "github.com/hajimehoshi/ebiten/v2/examples/resources/fonts"
12 "github.com/hajimehoshi/ebiten/v2/text/v2"
13 )
14
15
16 var testDataFS embed.FS
17
18 var testTextField *TextField
19
20 func defaultFont() *text.GoTextFaceSource {
21 source, err := text.NewGoTextFaceSource(bytes.NewReader(fonts.MPlus1pRegular_ttf))
22 if err != nil {
23 panic(err)
24 }
25 return source
26 }
27
28 func cacheGlyphs(source *text.GoTextFaceSource, size int) {
29 testFiles := []string{"loremipsum", "long"}
30 for _, fileName := range testFiles {
31 content, err := testDataFS.ReadFile(fmt.Sprintf("testdata/%s.txt", fileName))
32 if err != nil {
33 panic("failed to open testdata")
34 }
35 face := &text.GoTextFace{
36 Source: source,
37 Size: float64(size),
38 }
39 text.CacheGlyphs(string(content), face)
40 }
41 }
42
43 func TestWrapContent(t *testing.T) {
44 const fontSize = 24
45 fontSource := defaultFont()
46
47 cacheGlyphs(fontSource, fontSize)
48
49 testCases := []struct {
50 long bool
51 wordWrap bool
52
53 }{
54 {false, false},
55 {false, true},
56 {true, false},
57 {true, true},
58 }
59
60 testRect := image.Rect(0, 0, 200, 400)
61
62 for _, c := range testCases {
63 var name string
64 if !c.long {
65 name = "loremipsum"
66 } else {
67 name = "long"
68 }
69
70 content, err := testDataFS.ReadFile(fmt.Sprintf("testdata/%s.txt", name))
71 if err != nil {
72 t.Errorf("failed to open testdata: %s", err)
73 }
74
75 if !c.wordWrap {
76 name += "/wrapChar"
77 } else {
78 name += "/wrapWord"
79 }
80
81 t.Run(name, func(t *testing.T) {
82 textField := NewTextField(fontSource, fontSize, &sync.Mutex{})
83 testTextField = textField
84 textField.SetRect(testRect)
85 textField.SetWordWrap(c.wordWrap)
86 textField.Write(content)
87 textField.bufferModified()
88 })
89 }
90 }
91
92 func BenchmarkWrapContent(b *testing.B) {
93 const fontSize = 24
94 fontSource := defaultFont()
95
96 cacheGlyphs(fontSource, fontSize)
97
98 testCases := []struct {
99 long bool
100 wordWrap bool
101
102 }{
103 {false, false},
104 {false, true},
105 {true, false},
106 {true, true},
107 }
108
109 testRect := image.Rect(0, 0, 200, 400)
110
111 for _, c := range testCases {
112 var name string
113 if !c.long {
114 name = "loremipsum"
115 } else {
116 name = "long"
117 }
118
119 content, err := testDataFS.ReadFile(fmt.Sprintf("testdata/%s.txt", name))
120 if err != nil {
121 b.Errorf("failed to open testdata: %s", err)
122 }
123
124 if !c.wordWrap {
125 name += "/wrapChar"
126 } else {
127 name += "/wrapWord"
128 }
129
130 textField := NewTextField(fontSource, fontSize, &sync.Mutex{})
131 testTextField = textField
132 textField.SetRect(testRect)
133 textField.SetWordWrap(c.wordWrap)
134
135 b.Run(name, func(b *testing.B) {
136 for i := 0; i < b.N; i++ {
137 textField.SetText("")
138 textField.Write(content)
139 textField.bufferModified()
140 }
141 })
142 }
143 }
144
View as plain text