diff --git a/internal/glyph/faces.go b/internal/glyph/faces.go new file mode 100644 index 0000000..1606f30 --- /dev/null +++ b/internal/glyph/faces.go @@ -0,0 +1,171 @@ +package glyph + +import ( + "slices" + + giofont "gioui.org/font" + "gioui.org/font/opentype" + "github.com/go-text/typesetting/font" + "github.com/go-text/typesetting/fontscan" + "github.com/go-text/typesetting/language" +) + +// faces finds the font each character is drawn in, for the segmenter, as +// Ghostty's font collection does: it tries the faces of the families asked +// for, in their order, then the fallback faces found so far, in the order +// they were found, and only searches the system's fonts for a character +// none of them has. +// +// Searching is what is slow. fontscan works out its candidate fonts again, +// from every font on the system, whenever its query or script is set, even +// to what it already was, and the segmenter sets the script for every run +// it splits. A terminal asks for one new character at a time, so asking +// fontscan for each made every new character cost 75–350µs, against +// about 8µs to draw it. Here each style's candidates are worked out once, +// and fontscan is told the script only when it changes. +type faces struct { + fonts *fontscan.FontMap + families []string // as given, for fontscan's query + norm []string // the same, normalised, to recognise their faces + + style Style + aspect font.Aspect + queried bool // fonts has the query for style + + script language.Script + scripted bool // fonts has script + + byStyle map[Style]*found + cur *found // byStyle[style] +} + +// found is what has been found for one style. +type found struct { + // primary are faces of the families asked for, in the families' + // order: rank is the family's index. + primary []ranked + // fallback are other faces, in the order found. + fallback []*font.Face +} + +type ranked struct { + face *font.Face + rank int +} + +func newFaces(fm *fontscan.FontMap, families []string) faces { + f := faces{fonts: fm, families: families, byStyle: make(map[Style]*found)} + for _, fam := range families { + f.norm = append(f.norm, font.NormalizeFamily(fam)) + } + return f +} + +// use makes style the one characters are next resolved in. +func (f *faces) use(style Style) { + if f.queried && style == f.style { + return + } + f.style, f.aspect = style, aspectOf(style) + f.cur = f.byStyle[style] + if f.cur == nil { + f.cur = new(found) + f.byStyle[style] = f.cur + f.seed() + } + f.fonts.SetQuery(fontscan.Query{Families: f.families, Aspect: f.aspect}) + f.queried = true +} + +// seed finds the faces of the families asked for, so that they come +// before any fallback, whatever characters are asked for first: a CJK +// font found first must not draw the Latin letters that follow. A family +// is found by asking for it alone, for a letter; one whose font has no +// letters is found when it's first needed instead, by ResolveFace. +func (f *faces) seed() { + for _, fam := range f.families { + f.fonts.SetQuery(fontscan.Query{Families: []string{fam}, Aspect: f.aspect}) + // A family that isn't installed resolves to another font: that + // isn't a fallback yet, until a character needs it. + if face := f.fonts.ResolveFace('M'); face != nil && f.rank(face) >= 0 { + f.add(face) + } + } + f.queried = false // the query is for one family: set it again +} + +// SetScript tells fontscan the script of the characters that follow, if +// it changed. +func (f *faces) SetScript(s language.Script) { + if f.scripted && s == f.script { + return + } + f.fonts.SetScript(s) + f.script, f.scripted = s, true +} + +// ResolveFace returns the face to draw r in, which has it if any font +// does. +func (f *faces) ResolveFace(r rune) *font.Face { + for _, p := range f.cur.primary { + if has(p.face, r) { + return p.face + } + } + for _, face := range f.cur.fallback { + if has(face, r) { + return face + } + } + face := f.fonts.ResolveFace(r) + if face != nil && has(face, r) { // not the arbitrary face for none + f.add(face) + } + return face +} + +// add keeps face for the current style: among the primary faces, in its +// family's place, if it is one of the families asked for, else as the +// last fallback. +func (f *faces) add(face *font.Face) { + c := f.cur + rank := f.rank(face) + if rank < 0 { + if !slices.Contains(c.fallback, face) { + c.fallback = append(c.fallback, face) + } + return + } + if slices.ContainsFunc(c.primary, func(p ranked) bool { return p.face == face }) { + return + } + i, _ := slices.BinarySearchFunc(c.primary, rank, func(p ranked, rank int) int { return p.rank - rank }) + for i < len(c.primary) && c.primary[i].rank == rank { + i++ // after faces of the same family found before + } + c.primary = slices.Insert(c.primary, i, ranked{face, rank}) +} + +// rank is the index of face's family among those asked for, or -1. +func (f *faces) rank(face *font.Face) int { + family, _ := f.fonts.FontMetadata(face.Font) + return slices.Index(f.norm, font.NormalizeFamily(family)) +} + +func has(face *font.Face, r rune) bool { + _, ok := face.NominalGlyph(r) + return ok +} + +// aspectOf is the weight and slant a style asks fonts for, as Gio's +// shaper asks for them. +func aspectOf(style Style) font.Aspect { + var f giofont.Font + if style.Bold { + f.Weight = giofont.Bold + } + if style.Italic { + f.Style = giofont.Italic + } + return opentype.FontToDescription(f).Aspect +} diff --git a/internal/glyph/glyph.go b/internal/glyph/glyph.go index 94b7d07..e4247d3 100644 --- a/internal/glyph/glyph.go +++ b/internal/glyph/glyph.go @@ -65,10 +65,9 @@ type Metrics struct { // safe for concurrent use, but the glyphs it returns may be read from any // goroutine: they never change. type Rasterizer struct { - fonts *fontscan.FontMap - families []string - seg shaping.Segmenter - shaper shaping.HarfbuzzShaper + faces faces + seg shaping.Segmenter + shaper shaping.HarfbuzzShaper glyphs map[key]*Glyph runes []rune @@ -121,7 +120,7 @@ func New(opts Options) *Rasterizer { families = append(families, f) } } - return &Rasterizer{fonts: fm, families: families, glyphs: make(map[key]*Glyph)} + return &Rasterizer{faces: newFaces(fm, families), glyphs: make(map[key]*Glyph)} } type quietLogger struct{} @@ -175,14 +174,7 @@ func (r *Rasterizer) GlyphRunes(text []rune, style Style, px int) *Glyph { // shape shapes text in the fonts that have its characters. func (r *Rasterizer) shape(text []rune, style Style, px int) []shaping.Output { - f := giofont.Font{Typeface: giofont.Typeface(strings.Join(r.families, ","))} - if style.Bold { - f.Weight = giofont.Bold - } - if style.Italic { - f.Style = giofont.Italic - } - r.fonts.SetQuery(fontscan.Query{Families: r.families, Aspect: opentype.FontToDescription(f).Aspect}) + r.faces.use(style) r.runes = append(r.runes[:0], text...) in := shaping.Input{ Text: r.runes, @@ -192,7 +184,7 @@ func (r *Rasterizer) shape(text []rune, style Style, px int) []shaping.Output { Size: fixed.I(px), } var outs []shaping.Output - for _, in := range r.seg.Split(in, r.fonts) { + for _, in := range r.seg.Split(in, &r.faces) { if in.Face == nil { continue // no font has it } diff --git a/internal/glyph/glyph_test.go b/internal/glyph/glyph_test.go index f555f95..52de654 100644 --- a/internal/glyph/glyph_test.go +++ b/internal/glyph/glyph_test.go @@ -1,10 +1,12 @@ package glyph import ( + "bytes" "image" "image/color" "math" "testing" + "time" "gioui.org/f32" giofont "gioui.org/font" @@ -208,3 +210,73 @@ func toSRGB(l float64) uint8 { } return uint8(math.Round(255 * (1.055*math.Pow(l, 1/2.4) - 0.055))) } + +// TestFallbackOrder keeps a fallback font from drawing what the families +// asked for have, whatever is drawn first: a CJK font, found first, has +// Latin letters too. +func TestFallbackOrder(t *testing.T) { + const families = testFamilies + ", monospace, emoji" + r := New(Options{Families: families, Faces: gofont.Collection()}) + if g := r.Glyph("漢", Style{}, 20); g.Mask == nil { + t.Skip("no CJK font installed") + } + fresh := New(Options{Families: families, Faces: gofont.Collection()}) + for _, s := range []string{"A", "g", "é", "Ж"} { + for _, style := range []Style{{}, {Bold: true}, {Italic: true}} { + if got, want := r.Glyph(s, style, 20), fresh.Glyph(s, style, 20); !sameDrawing(got, want) { + t.Errorf("%q %+v, drawn after 漢, isn't drawn as it is first", s, style) + } + } + } +} + +func sameDrawing(a, b *Glyph) bool { + if a.Origin != b.Origin || (a.Mask == nil) != (b.Mask == nil) { + return false + } + return a.Mask == nil || (a.Mask.Rect == b.Mask.Rect && bytes.Equal(a.Mask.Pix, b.Mask.Pix)) +} + +// TestMissCost keeps drawing a character not drawn before cheap, once the +// fonts it needs are loaded: finding its font, rather than drawing it, was +// most of the cost, and made a screen of new characters, as random output +// or a page of Japanese is, take tens of milliseconds. Characters that +// change script each time are the worst case. +func TestMissCost(t *testing.T) { + if testing.Short() { + t.Skip("measures time") + } + const limit = 50 * time.Microsecond // about 10µs on a Ryzen 9 7900; 75–350µs before + var latin, cjk, japanese, mixed []rune + for c := rune(0xA1); c < 0xA1+200; c++ { + latin = append(latin, c) + } + for c := rune(0x4E00); c < 0x4E00+400; c++ { + cjk = append(cjk, c) + } + for i := range 400 { // Han, Hiragana and Katakana in turn, as Japanese text is + japanese = append(japanese, []rune{0x5000 + rune(i), 0x3041 + rune(i%80), 0x30A1 + rune(i%80)}[i%3]) + } + for i := range 400 { // Latin, Han, Cyrillic and Thai in turn + mixed = append(mixed, []rune{0x100 + rune(i), 0x6000 + rune(i), 0x400 + rune(i%200), 0xE01 + rune(i%45)}[i%4]) + } + for _, set := range []struct { + name string + runes []rune + }{{"latin", latin}, {"cjk", cjk}, {"japanese", japanese}, {"mixed scripts", mixed}} { + r := New(Options{Families: "Iosevka Nerd Font, Iosevka, Go Mono, monospace, emoji", Faces: gofont.Collection()}) + half := len(set.runes) / 2 + for _, c := range set.runes[:half] { // loads the fonts the rest need + r.GlyphRunes([]rune{c}, Style{}, 20) + } + start := time.Now() + for _, c := range set.runes[half:] { + r.GlyphRunes([]rune{c}, Style{}, 20) + } + per := time.Since(start) / time.Duration(len(set.runes)-half) + t.Logf("%s: %v per new character", set.name, per) + if per > limit { + t.Errorf("%s: %v per new character, over %v", set.name, per, limit) + } + } +}