ref: 5c3dcc6f9a07dc22a26319616adc2c63e33da966 gio/ui/measure/measure.go -rw-r--r-- 5.9 KiB View raw
                                                                                
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
// SPDX-License-Identifier: Unlicense OR MIT

package measure

import (
	"math"
	"unicode"
	"unicode/utf8"

	"gioui.org/ui"
	"gioui.org/ui/f32"
	"gioui.org/ui/text"
	"gioui.org/ui/paint"
	"golang.org/x/image/font"
	"golang.org/x/image/font/sfnt"
	"golang.org/x/image/math/fixed"
)

type Faces struct {
	config      ui.Config
	faceCache   map[faceKey]*textFace
	layoutCache map[layoutKey]cachedLayout
	pathCache   map[pathKey]cachedPath
}

type cachedLayout struct {
	active bool
	layout *text.Layout
}

type cachedPath struct {
	active bool
	path   ui.MacroOp
}

type layoutKey struct {
	f    *sfnt.Font
	ppem fixed.Int26_6
	str  string
	opts text.LayoutOptions
}

type pathKey struct {
	f    *sfnt.Font
	ppem fixed.Int26_6
	str  string
}

type faceKey struct {
	font *sfnt.Font
	size ui.Value
}

type textFace struct {
	faces *Faces
	size  ui.Value
	font  *opentype
}

func (f *Faces) Reset(c ui.Config) {
	f.config = c
	f.init()
	for pk, p := range f.pathCache {
		if !p.active {
			delete(f.pathCache, pk)
			continue
		}
		p.active = false
		f.pathCache[pk] = p
	}
	for lk, l := range f.layoutCache {
		if !l.active {
			delete(f.layoutCache, lk)
			continue
		}
		l.active = false
		f.layoutCache[lk] = l
	}
}

func (f *Faces) For(fnt *sfnt.Font, size ui.Value) text.Face {
	f.init()
	fk := faceKey{fnt, size}
	if f, exist := f.faceCache[fk]; exist {
		return f
	}
	face := &textFace{
		faces: f,
		size:  size,
		font:  &opentype{Font: fnt, Hinting: font.HintingFull},
	}
	f.faceCache[fk] = face
	return face
}

func (f *Faces) init() {
	if f.faceCache != nil {
		return
	}
	f.faceCache = make(map[faceKey]*textFace)
	f.pathCache = make(map[pathKey]cachedPath)
	f.layoutCache = make(map[layoutKey]cachedLayout)
}

func (f *textFace) Layout(str string, opts text.LayoutOptions) *text.Layout {
	ppem := fixed.Int26_6(f.faces.config.Px(f.size) * 64)
	lk := layoutKey{
		f:    f.font.Font,
		ppem: ppem,
		str:  str,
		opts: opts,
	}
	if l, ok := f.faces.layoutCache[lk]; ok {
		l.active = true
		f.faces.layoutCache[lk] = l
		return l.layout
	}
	l := layoutText(ppem, str, f.font, opts)
	f.faces.layoutCache[lk] = cachedLayout{active: true, layout: l}
	return l
}

func (f *textFace) Path(str text.String) ui.MacroOp {
	ppem := fixed.Int26_6(f.faces.config.Px(f.size) * 64)
	pk := pathKey{
		f:    f.font.Font,
		ppem: ppem,
		str:  str.String,
	}
	if p, ok := f.faces.pathCache[pk]; ok {
		p.active = true
		f.faces.pathCache[pk] = p
		return p.path
	}
	p := textPath(ppem, f.font, str)
	f.faces.pathCache[pk] = cachedPath{active: true, path: p}
	return p
}

func layoutText(ppem fixed.Int26_6, str string, f *opentype, opts text.LayoutOptions) *text.Layout {
	m := f.Metrics(ppem)
	lineTmpl := text.Line{
		Ascent: m.Ascent,
		// m.Height is equal to m.Ascent + m.Descent + linegap.
		// Compute the descent including the linegap.
		Descent: m.Height - m.Ascent,
		Bounds:  f.Bounds(ppem),
	}
	var lines []text.Line
	maxDotX := fixed.Int26_6(math.MaxInt32)
	maxDotX = fixed.I(opts.MaxWidth)
	type state struct {
		r     rune
		advs  []fixed.Int26_6
		adv   fixed.Int26_6
		x     fixed.Int26_6
		idx   int
		valid bool
	}
	var prev, word state
	endLine := func() {
		line := lineTmpl
		line.Text.Advances = prev.advs
		line.Text.String = str[:prev.idx]
		line.Width = prev.x + prev.adv
		line.Bounds.Max.X += prev.x
		lines = append(lines, line)
		str = str[prev.idx:]
		prev = state{}
		word = state{}
	}
	for prev.idx < len(str) {
		c, s := utf8.DecodeRuneInString(str[prev.idx:])
		nl := text.IsNewline(c)
		if opts.SingleLine && nl {
			nl = false
			c = ' '
			s = 1
		}
		a, ok := f.GlyphAdvance(ppem, c)
		if !ok {
			prev.idx += s
			continue
		}
		next := state{
			r:     c,
			advs:  prev.advs,
			idx:   prev.idx + s,
			x:     prev.x + prev.adv,
			valid: true,
		}
		if nl {
			// The newline is zero width; use the previous
			// character for line measurements.
			prev.advs = append(prev.advs, 0)
			prev.idx = next.idx
			endLine()
			continue
		}
		next.adv = a
		var k fixed.Int26_6
		if prev.valid {
			k = f.Kern(ppem, prev.r, next.r)
		}
		// Break the line if we're out of space.
		if prev.idx > 0 && next.x+next.adv+k >= maxDotX {
			// If the line contains no word breaks, break off the last rune.
			if word.idx == 0 {
				word = prev
			}
			next.x -= word.x + word.adv
			next.idx -= word.idx
			next.advs = next.advs[len(word.advs):]
			prev = word
			endLine()
		} else {
			next.adv += k
		}
		next.advs = append(next.advs, next.adv)
		if unicode.IsSpace(next.r) {
			word = next
		}
		prev = next
	}
	endLine()
	return &text.Layout{Lines: lines}
}

func textPath(ppem fixed.Int26_6, f *opentype, str text.String) ui.MacroOp {
	var lastPos f32.Point
	var builder paint.PathBuilder
	ops := new(ui.Ops)
	builder.Init(ops)
	var x fixed.Int26_6
	var advIdx int
	var m ui.MacroOp
	m.Record(ops)
	for _, r := range str.String {
		if !unicode.IsSpace(r) {
			segs, ok := f.LoadGlyph(ppem, r)
			if !ok {
				continue
			}
			// Move to glyph position.
			pos := f32.Point{
				X: float32(x) / 64,
			}
			builder.Move(pos.Sub(lastPos))
			lastPos = pos
			var lastArg f32.Point
			// Convert sfnt.Segments to relative segments.
			for _, fseg := range segs {
				nargs := 1
				switch fseg.Op {
				case sfnt.SegmentOpQuadTo:
					nargs = 2
				case sfnt.SegmentOpCubeTo:
					nargs = 3
				}
				var args [3]f32.Point
				for i := 0; i < nargs; i++ {
					a := f32.Point{
						X: float32(fseg.Args[i].X) / 64,
						Y: float32(fseg.Args[i].Y) / 64,
					}
					args[i] = a.Sub(lastArg)
					if i == nargs-1 {
						lastArg = a
					}
				}
				switch fseg.Op {
				case sfnt.SegmentOpMoveTo:
					builder.Move(args[0])
				case sfnt.SegmentOpLineTo:
					builder.Line(args[0])
				case sfnt.SegmentOpQuadTo:
					builder.Quad(args[0], args[1])
				case sfnt.SegmentOpCubeTo:
					builder.Cube(args[0], args[1], args[2])
				default:
					panic("unsupported segment op")
				}
			}
			lastPos = lastPos.Add(lastArg)
		}
		x += str.Advances[advIdx]
		advIdx++
	}
	builder.End()
	m.Stop()
	return m
}