-
-
Notifications
You must be signed in to change notification settings - Fork 662
/
gotextfacesource.go
297 lines (252 loc) · 7.33 KB
/
gotextfacesource.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
// Copyright 2023 The Ebitengine Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package text
import (
"bytes"
"io"
"sync"
"github.com/go-text/typesetting/font"
"github.com/go-text/typesetting/language"
"github.com/go-text/typesetting/opentype/api"
ofont "github.com/go-text/typesetting/opentype/api/font"
"github.com/go-text/typesetting/opentype/loader"
"github.com/go-text/typesetting/shaping"
"golang.org/x/image/math/fixed"
"github.com/hajimehoshi/ebiten/v2"
)
type goTextOutputCacheKey struct {
text string
direction Direction
size float64
language string
script string
variations string
features string
}
type glyph struct {
shapingGlyph *shaping.Glyph
startIndex int
endIndex int
scaledSegments []api.Segment
bounds fixed.Rectangle26_6
}
type goTextOutputCacheValue struct {
outputs []shaping.Output
glyphs []glyph
atime int64
}
type goTextGlyphImageCacheKey struct {
gid api.GID
xoffset fixed.Int26_6
yoffset fixed.Int26_6
variations string
}
// GoTextFaceSource is a source of a GoTextFace. This can be shared by multiple GoTextFace objects.
type GoTextFaceSource struct {
f font.Face
metadata Metadata
outputCache map[goTextOutputCacheKey]*goTextOutputCacheValue
glyphImageCache map[float64]*glyphImageCache[goTextGlyphImageCacheKey]
addr *GoTextFaceSource
m sync.Mutex
}
func toFontResource(source io.Reader) (font.Resource, error) {
// font.Resource has io.Seeker and io.ReaderAt in addition to io.Reader.
// If source has it, use it as it is.
if s, ok := source.(font.Resource); ok {
return s, nil
}
// Read all the bytes and convert this to bytes.Reader.
// This is a very rough solution, but it works.
// TODO: Implement io.ReaderAt in a more efficient way when source is io.Seeker.
bs, err := io.ReadAll(source)
if err != nil {
return nil, err
}
return bytes.NewReader(bs), nil
}
// NewGoTextFaceSource parses an OpenType or TrueType font and returns a GoTextFaceSource object.
func NewGoTextFaceSource(source io.Reader) (*GoTextFaceSource, error) {
src, err := toFontResource(source)
if err != nil {
return nil, err
}
l, err := loader.NewLoader(src)
if err != nil {
return nil, err
}
f, err := ofont.NewFont(l)
if err != nil {
return nil, err
}
s := &GoTextFaceSource{
f: &ofont.Face{Font: f},
}
s.addr = s
s.metadata = metadataFromLoader(l)
return s, nil
}
// NewGoTextFaceSourcesFromCollection parses an OpenType or TrueType font collection and returns a slice of GoTextFaceSource objects.
func NewGoTextFaceSourcesFromCollection(source io.Reader) ([]*GoTextFaceSource, error) {
src, err := toFontResource(source)
if err != nil {
return nil, err
}
ls, err := loader.NewLoaders(src)
if err != nil {
return nil, err
}
sources := make([]*GoTextFaceSource, len(ls))
for i, l := range ls {
f, err := ofont.NewFont(l)
if err != nil {
return nil, err
}
s := &GoTextFaceSource{
f: &ofont.Face{Font: f},
}
s.addr = s
s.metadata = metadataFromLoader(l)
sources[i] = s
}
return sources, nil
}
func (g *GoTextFaceSource) copyCheck() {
if g.addr != g {
panic("text: illegal use of non-zero GoTextFaceSource copied by value")
}
}
// Metadata returns its metadata.
func (g *GoTextFaceSource) Metadata() Metadata {
return g.metadata
}
// UnsafeInternal returns its font.Face.
//
// This is unsafe since this might make internal cache states out of sync.
func (g *GoTextFaceSource) UnsafeInternal() font.Face {
return g.f
}
func (g *GoTextFaceSource) shape(text string, face *GoTextFace) ([]shaping.Output, []glyph) {
g.copyCheck()
g.m.Lock()
defer g.m.Unlock()
key := face.outputCacheKey(text)
if out, ok := g.outputCache[key]; ok {
out.atime = now()
return out.outputs, out.glyphs
}
g.f.SetVariations(face.variations)
runes := []rune(text)
input := shaping.Input{
Text: runes,
RunStart: 0,
RunEnd: len(runes),
Direction: face.diDirection(),
Face: face.Source.f,
FontFeatures: face.features,
Size: float64ToFixed26_6(face.Size),
Script: face.gScript(),
Language: language.Language(face.Language.String()),
}
var seg shaping.Segmenter
inputs := seg.Split(input, &singleFontmap{face: face.Source.f})
if face.Direction == DirectionRightToLeft {
// Reverse the input for RTL texts.
for i, j := 0, len(inputs)-1; i < j; i, j = i+1, j-1 {
inputs[i], inputs[j] = inputs[j], inputs[i]
}
}
outputs := make([]shaping.Output, len(inputs))
var gs []glyph
for i, input := range inputs {
out := (&shaping.HarfbuzzShaper{}).Shape(input)
outputs[i] = out
(shaping.Line{out}).AdjustBaselines()
var indices []int
for i := range text {
indices = append(indices, i)
}
indices = append(indices, len(text))
for _, gl := range out.Glyphs {
gl := gl
var segs []api.Segment
switch data := g.f.GlyphData(gl.GlyphID).(type) {
case api.GlyphOutline:
if out.Direction.IsSideways() {
data.Sideways(fixed26_6ToFloat32(-gl.YOffset) / fixed26_6ToFloat32(out.Size) * float32(face.Source.f.Upem()))
}
segs = data.Segments
case api.GlyphSVG:
segs = data.Outline.Segments
case api.GlyphBitmap:
if data.Outline != nil {
segs = data.Outline.Segments
}
}
scaledSegs := make([]api.Segment, len(segs))
scale := float32(g.scale(fixed26_6ToFloat64(out.Size)))
for i, seg := range segs {
scaledSegs[i] = seg
for j := range seg.Args {
scaledSegs[i].Args[j].X *= scale
scaledSegs[i].Args[j].Y *= -scale
}
}
gs = append(gs, glyph{
shapingGlyph: &gl,
startIndex: indices[gl.ClusterIndex],
endIndex: indices[gl.ClusterIndex+gl.RuneCount],
scaledSegments: scaledSegs,
bounds: segmentsToBounds(scaledSegs),
})
}
}
if g.outputCache == nil {
g.outputCache = map[goTextOutputCacheKey]*goTextOutputCacheValue{}
}
g.outputCache[key] = &goTextOutputCacheValue{
outputs: outputs,
glyphs: gs,
atime: now(),
}
const cacheSoftLimit = 512
if len(g.outputCache) > cacheSoftLimit {
for key, e := range g.outputCache {
// 60 is an arbitrary number.
if e.atime >= now()-60 {
continue
}
delete(g.outputCache, key)
}
}
return outputs, gs
}
func (g *GoTextFaceSource) scale(size float64) float64 {
return size / float64(g.f.Upem())
}
func (g *GoTextFaceSource) getOrCreateGlyphImage(goTextFace *GoTextFace, key goTextGlyphImageCacheKey, create func() *ebiten.Image) *ebiten.Image {
if g.glyphImageCache == nil {
g.glyphImageCache = map[float64]*glyphImageCache[goTextGlyphImageCacheKey]{}
}
if _, ok := g.glyphImageCache[goTextFace.Size]; !ok {
g.glyphImageCache[goTextFace.Size] = &glyphImageCache[goTextGlyphImageCacheKey]{}
}
return g.glyphImageCache[goTextFace.Size].getOrCreate(goTextFace, key, create)
}
type singleFontmap struct {
face font.Face
}
func (s *singleFontmap) ResolveFace(r rune) font.Face {
return s.face
}