forked from mmp/vice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfonts.go
368 lines (327 loc) · 11.9 KB
/
fonts.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// fonts.go
// Copyright(c) 2022 Matt Pharr, licensed under the GNU Public License, Version 3.
// SPDX: GPL-3.0-only
package main
import (
"C"
_ "embed"
"fmt"
"image"
"math"
"runtime"
"sort"
"unicode/utf8"
"unsafe"
"github.com/mmp/IconFontCppHeaders"
"github.com/mmp/imgui-go/v4"
)
// imgui lets us to embed icons within regular fonts which makes it
// possible to use them directly in text without changing to the icon
// font. However, we have a fair number of fonts and sizes. Thereore, so
// save space, we require that the used icons be tracked in fonts.go so
// that only they need to be copied into all of the regular fonts.
// Given that, code elsewhere uses the following variables to get the
// string encoding that gives the corresponding icon.
var (
FontAwesomeIconArrowDown = faUsedIcons["ArrowDown"]
FontAwesomeIconArrowLeft = faUsedIcons["ArrowLeft"]
FontAwesomeIconArrowRight = faUsedIcons["ArrowRight"]
FontAwesomeIconArrowUp = faUsedIcons["ArrowUp"]
FontAwesomeIconBug = faUsedIcons["Bug"]
FontAwesomeIconCaretDown = faUsedIcons["CaretDown"]
FontAwesomeIconCaretRight = faUsedIcons["CaretRight"]
FontAwesomeIconCheckSquare = faUsedIcons["CheckSquare"]
FontAwesomeIconCopyright = faUsedIcons["Copyright"]
FontAwesomeIconDiscord = faBrandsUsedIcons["Discord"]
FontAwesomeIconExclamationTriangle = faUsedIcons["ExclamationTriangle"]
FontAwesomeIconFile = faUsedIcons["File"]
FontAwesomeIconFolder = faUsedIcons["Folder"]
FontAwesomeIconGithub = faBrandsUsedIcons["Github"]
FontAwesomeIconHome = faUsedIcons["Home"]
FontAwesomeIconHandPointLeft = faUsedIcons["HandPointLeft"]
FontAwesomeIconLevelUpAlt = faUsedIcons["LevelUpAlt"]
FontAwesomeIconLock = faUsedIcons["Lock"]
FontAwesomeIconSquare = faUsedIcons["Square"]
FontAwesomeIconTrash = faUsedIcons["Trash"]
)
var (
// All of the available fonts.
fonts map[FontIdentifier]*Font
// This and the following faBrandsUsedIcons map are what drives
// determining which icons are copied into regular fonts; see
// InitializeFonts() below.
faUsedIcons map[string]string = map[string]string{
"ArrowDown": FontAwesomeString("ArrowDown"),
"ArrowLeft": FontAwesomeString("ArrowLeft"),
"ArrowRight": FontAwesomeString("ArrowRight"),
"ArrowUp": FontAwesomeString("ArrowUp"),
"Bug": FontAwesomeString("Bug"),
"CaretDown": FontAwesomeString("CaretDown"),
"CaretRight": FontAwesomeString("CaretRight"),
"CheckSquare": FontAwesomeString("CheckSquare"),
"Copyright": FontAwesomeString("Copyright"),
"ExclamationTriangle": FontAwesomeString("ExclamationTriangle"),
"File": FontAwesomeString("File"),
"Folder": FontAwesomeString("Folder"),
"Home": FontAwesomeString("Home"),
"HandPointLeft": FontAwesomeString("HandPointLeft"),
"LevelUpAlt": FontAwesomeString("LevelUpAlt"),
"Lock": FontAwesomeString("Lock"),
"Square": FontAwesomeString("Square"),
"Trash": FontAwesomeString("Trash"),
}
faBrandsUsedIcons map[string]string = map[string]string{
"Discord": FontAwesomeBrandsString("Discord"),
"Github": FontAwesomeBrandsString("Github"),
}
// Font data; they're all embedded in the executable as strings at
// compile time, which saves us any worries about having trouble
// finding them at runtime.
//go:embed resources/Roboto-Regular.ttf.zst
robotoRegularTTF string
//go:embed resources/VT323-Regular.ttf.zst
vt323RegularTTF string
//go:embed resources/Inconsolata/static/Inconsolata_Condensed/Inconsolata_Condensed-Regular.ttf.zst
inconsolataCondensedRegularTTF string
//go:embed "resources/Font Awesome 5 Brands-Regular-400.otf.zst"
fa5BrandsRegularTTF string
//go:embed "resources/Font Awesome 5 Free-Regular-400.otf.zst"
fa5RegularTTF string
//go:embed "resources/Font Awesome 5 Free-Solid-900.otf.zst"
fa5SolidTTF string
//----go:embed "resources/ibm_ega_8x14.ttf.zst"
//ibmEGA8x14 string
)
// Each loaded (font,size) combination is represented by (surprise) a Font.
type Font struct {
// Glyphs for the commonly-used ASCII range can be looked up using a
// directly-mapped array, for efficiency.
lowGlyphs [128]*Glyph
// The remaining glyphs (generally, the used FontAwesome icons, are
// stored in a map.
glyphs map[rune]*Glyph
// Font size
size int
mono bool
ifont imgui.Font
id FontIdentifier
}
// While the following could be found via the imgui.FontGlyph interface, cgo calls into C++ code are
// slow, especially if we do ~10 of them for each character drawn. So we cache the information we need
// to draw each one here.
type Glyph struct {
// Vertex positions for the quad to draw
X0, Y0, X1, Y1 float32
// Texture coordinates in the font atlas
U0, V0, U1, V1 float32
// Distance to advance in x after the character.
AdvanceX float32
// Is it a visible character (i.e., not space, tab, CR, ...)
Visible bool
}
// FontIdentifier is used for looking up
type FontIdentifier struct {
Name string
Size int
}
// Internal: lookup the glyph for a rune in imgui's font atlas and then
// copy over the necessary information into our Glyph structure.
func (f *Font) createGlyph(ch rune) *Glyph {
ig := f.ifont.FindGlyph(ch)
return &Glyph{X0: ig.X0(), Y0: ig.Y0(), X1: ig.X1(), Y1: ig.Y1(),
U0: ig.U0(), V0: ig.V0(), U1: ig.U1(), V1: ig.V1(),
AdvanceX: ig.AdvanceX(), Visible: ig.Visible()}
}
// LookupGlyph returns the Glyph for the specified rune.
func (f *Font) LookupGlyph(ch rune) *Glyph {
if int(ch) < len(f.lowGlyphs) {
if g := f.lowGlyphs[ch]; g == nil {
g = f.createGlyph(ch)
f.lowGlyphs[ch] = g
return g
} else {
return g
}
} else if g, ok := f.glyphs[ch]; !ok {
g = f.createGlyph(ch)
f.glyphs[ch] = g
return g
} else {
return g
}
}
// Returns the bound of the specified text in the given font, assuming the
// given pixel spacing between lines.
func (font *Font) BoundText(s string, spacing int) (int, int) {
dy := font.size + spacing
py := dy
var px, xmax float32
for _, ch := range s {
if ch == '\n' {
px = 0
py += dy
} else {
glyph := font.LookupGlyph(ch)
px += glyph.AdvanceX
if px > xmax {
xmax = px
}
}
}
return int(math.Ceil(float64(xmax))), py
}
// From imgui-go:
// unrealisticLargePointer is used to cast an arbitrary native pointer to a slice.
// Its value is chosen to fit into a 32bit architecture, and still be large
// enough to cover "any" data blob. Note that this value is in bytes.
const unrealisticLargePointer = 1 << 30
func ptrToUint16Slice(p unsafe.Pointer) []uint16 {
return (*[unrealisticLargePointer / 2]uint16)(p)[:]
}
func fontsInit(r Renderer) {
lg.Printf("Starting to initialize fonts")
fonts = make(map[FontIdentifier]*Font)
io := imgui.CurrentIO()
// Given a map that specifies the icons used in an icon font, returns
// an imgui.GlyphRanges that encompasses those icons. This GlyphRanges
// is then used shortly when the fonts are loaded.
glyphRangeForIcons := func(icons map[string]string) imgui.GlyphRanges {
// imgui represents such glyph ranges as an array of uint16s, where
// each range is given by two successive values and where a value
// of 0 denotes the end of the array. We need to resort to malloc
// for this array since imgui's AddFontFromMemoryTTF() function
// holds on to its pointer. (Thus, using a slice or go's new fails
// unpredictably, since go's GC will happily reclaim the memory.)
r := C.malloc(C.size_t(4*len(icons) + 2))
ranges := ptrToUint16Slice(r)
i := 0
for _, str := range icons {
unicode, _ := utf8.DecodeRuneInString(str)
// The specified range is inclusive so we just double-up the
// unicode value.
ranges[i] = uint16(unicode)
ranges[i+1] = uint16(unicode)
i += 2
}
ranges[i] = 0
return imgui.GlyphRanges(r)
}
// Decompress and get the glyph ranges for the Font Awesome fonts just once.
faTTF := []byte(decompressZstd(fa5SolidTTF))
faGlyphRange := glyphRangeForIcons(faUsedIcons)
fabrTTF := []byte(decompressZstd(fa5BrandsRegularTTF))
faBrandsGlyphRange := glyphRangeForIcons(faBrandsUsedIcons)
add := func(ttfZstd string, mono bool, name string) {
ttf := []byte(decompressZstd(ttfZstd))
for _, size := range []int{8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 22, 24, 28} {
sp := float32(size)
if runtime.GOOS == "windows" {
// Fix font sizes to account for Windows using 96dpi but
// everyone else using 72...
sp *= 96. / 72.
}
ifont := io.Fonts().AddFontFromMemoryTTFV(ttf, sp, imgui.DefaultFontConfig, imgui.EmptyGlyphRanges)
config := imgui.NewFontConfig()
config.SetMergeMode(true)
// Scale down the font size by an ad-hoc factor to (generally)
// make the icon sizes match the font's character sizes.
io.Fonts().AddFontFromMemoryTTFV(faTTF, .8*sp, config, faGlyphRange)
io.Fonts().AddFontFromMemoryTTFV(fabrTTF, .8*sp, config, faBrandsGlyphRange)
id := FontIdentifier{Name: name, Size: size}
fonts[id] = &Font{
glyphs: make(map[rune]*Glyph),
size: int(sp),
mono: mono,
ifont: ifont,
id: id}
}
}
add(robotoRegularTTF, false, "Roboto Regular")
add(vt323RegularTTF, true, "VT323 Regular")
add(inconsolataCondensedRegularTTF, true, "Inconsolata Condensed Regular")
img := io.Fonts().TextureDataRGBA32()
lg.Printf("Fonts texture used %.1f MB", float32(img.Width*img.Height*4)/(1024*1024))
rgb8Image := &image.RGBA{
Pix: unsafe.Slice((*uint8)(img.Pixels), 4*img.Width*img.Height),
Stride: 4 * img.Width,
Rect: image.Rectangle{Max: image.Point{X: img.Width, Y: img.Height}}}
fontId := r.CreateTextureFromImage(rgb8Image)
io.Fonts().SetTextureID(imgui.TextureID(fontId))
lg.Printf("Finished initializing fonts")
}
// GetAllFonts returns a FontIdentifier slice that gives identifiers for
// all of the available fonts, sorted by font name and then within each
// name, by font size.
func GetAllFonts() []FontIdentifier {
var fs []FontIdentifier
for f := range fonts {
fs = append(fs, f)
}
sort.Slice(fs, func(i, j int) bool {
if fs[i].Name == fs[j].Name {
return fs[i].Size < fs[j].Size
}
return fs[i].Name < fs[j].Name
})
return fs
}
func DrawFontPicker(id *FontIdentifier, label string) (newFont *Font, changed bool) {
f := GetAllFonts()
lastFontName := ""
if imgui.BeginComboV(label+fmt.Sprintf("##%p", id), id.Name, imgui.ComboFlagsHeightLarge) {
// Take advantage of the sort order returned by GetAllFonts()--that
// all fonts of the same name come consecutively.
for _, font := range f {
if font.Name != lastFontName {
lastFontName = font.Name
// Use the 14pt version of the font in the combo box.
displayFont := GetFont(FontIdentifier{Name: font.Name, Size: 14})
imgui.PushFont(displayFont.ifont)
if imgui.SelectableV(font.Name, id.Name == font.Name, 0, imgui.Vec2{}) {
id.Name = font.Name
changed = true
newFont = GetFont(*id)
}
imgui.PopFont()
}
}
imgui.EndCombo()
}
if imgui.BeginComboV(fmt.Sprintf("Size##%p", id), fmt.Sprintf("%d", id.Size), imgui.ComboFlagsHeightLarge) {
for _, font := range f {
if font.Name == id.Name {
if imgui.SelectableV(fmt.Sprintf("%d", font.Size), id.Size == font.Size, 0, imgui.Vec2{}) {
id.Size = font.Size
newFont = GetFont(*id)
changed = true
}
}
}
imgui.EndCombo()
}
return
}
func GetFont(id FontIdentifier) *Font {
if font, ok := fonts[id]; ok {
return font
} else {
return nil
}
}
func GetDefaultFont() *Font {
return GetFont(FontIdentifier{Name: "Roboto Regular", Size: 14})
}
func FontAwesomeString(id string) string {
s, ok := IconFontCppHeaders.FontAwesome5.Icons[id]
if !ok {
lg.Errorf("%s: FA string unknown", id)
}
return s
}
func FontAwesomeBrandsString(id string) string {
s, ok := IconFontCppHeaders.FontAwesome5Brands.Icons[id]
if !ok {
lg.Errorf("%s: FA string unknown", id)
}
return s
}