mirror of
https://git.sr.ht/~eliasnaur/gio
synced 2026-07-07 18:35:34 +00:00
font/{gofont,opentype},text,widget{,/material}: [API] add font fallback and bidi support
This commit restructures the entire text shaping stack to enable lines of shaped text to
have non-homogeneous properties like which font face they belong to and which direction
a segment of text is going.
The text package now provides a concrete type text.Shaper which can be used to convert
strings into sequences of renderable text.Glyphs. At a high level, the API is used
like this:
// Prepare some fonts.
var collection []text.FontFace
// Make a shaper with those fonts loaded.
shaper := text.NewShaper(collection)
// Shape a string.
shaper.LayoutString(text.Parameters{
PxPerEm: fixed.I(12),
}, 0, 100, system.Locale{}, "Hello")
// Iterate the glyphs from that string.
for glyph, ok := shaper.NextGlyph(); ok; glyph, ok = shaper.NextGlyph() {
// Convert the glyph data into a path. In real uses, convert batches of glyphs
// rather than single glyphs to reduce the number of individual paths and offsets
// required to display your text.
shape := shaper.Shape([]text.Glyph{glyph})
// Offset the glyph to the position it declares within its fields. This will
// automatically handle correct bidirectional text glyph positioning.
offset := op.Offset(image.Pt(glyph.X.Floor(), int(glyph.Y))).Push(gtx.Ops)
// Create a clip area from the shape of the glyph.
area := clip.Outline{Path: shape}.Push(gtx.Ops)
// Paint whatever the current color is within the glyph's shape.
paint.PaintOp{}.Add(gtx.Ops)
area.Pop()
offset.Pop()
}
This API will transparently handle both font fallback (choosing appropriate fonts
from those loaded when the primary font doesn't contain a required glyph) and
bidirectional text (mixed left-to-right and right-to-left text). Glyphs are
iterated in order of the input runes, not their visual order, but proper use
of the provided offsets will ensure that text always displays correctly.
Thanks to Elias Naur for suggesting this glyph iterator strategy. It let us cut
through a lot of accumulated complexity from trying to match our old text APIs,
meaning that this change actually is a net negative change in lines of code.
This commit consumes the upstream github.com/go-text/typesetting/shaping API
now that my prior work is merged there, removing the need for the font/opentype/internal
package entirely.
As part of my efforts, I fuzzed both the low-level text shaping stack and the
editor widget extensively. I've committed regression tests found that way into
the appropriate testdata files to ensure the fuzzer re-checks them.
Fixes: https://todo.sr.ht/~eliasnaur/gio/425
Fixes: https://todo.sr.ht/~eliasnaur/gio/211
Signed-off-by: Chris Waldon <christopher.waldon.dev@gmail.com>
This commit is contained in:
+10
-117
@@ -7,132 +7,25 @@ package opentype
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"io"
|
||||
|
||||
"github.com/benoitkugler/textlayout/fonts"
|
||||
"github.com/benoitkugler/textlayout/fonts/truetype"
|
||||
"github.com/benoitkugler/textlayout/harfbuzz"
|
||||
"github.com/go-text/typesetting/shaping"
|
||||
"golang.org/x/image/font"
|
||||
"golang.org/x/image/math/fixed"
|
||||
|
||||
"gioui.org/f32"
|
||||
"gioui.org/font/opentype/internal"
|
||||
"gioui.org/io/system"
|
||||
"gioui.org/op"
|
||||
"gioui.org/op/clip"
|
||||
"gioui.org/text"
|
||||
"github.com/go-text/typesetting/font"
|
||||
)
|
||||
|
||||
// Font implements the text.Shaper interface using a rich text
|
||||
// shaping engine.
|
||||
type Font struct {
|
||||
font *truetype.Font
|
||||
// Face is a shapeable representation of a font.
|
||||
type Face struct {
|
||||
face font.Face
|
||||
}
|
||||
|
||||
// Parse constructs a Font from source bytes.
|
||||
func Parse(src []byte) (*Font, error) {
|
||||
// Parse constructs a Face from source bytes.
|
||||
func Parse(src []byte) (Face, error) {
|
||||
face, err := truetype.Parse(bytes.NewReader(src))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed parsing truetype font: %w", err)
|
||||
return Face{}, fmt.Errorf("failed parsing truetype font: %w", err)
|
||||
}
|
||||
return &Font{
|
||||
font: face,
|
||||
}, nil
|
||||
return Face{face: face}, nil
|
||||
}
|
||||
|
||||
func (f *Font) Layout(ppem fixed.Int26_6, maxWidth int, lc system.Locale, txt io.RuneReader) ([]text.Line, error) {
|
||||
return internal.Document(shaping.Shape, f.font, ppem, maxWidth, lc, txt), nil
|
||||
}
|
||||
|
||||
func (f *Font) Shape(ppem fixed.Int26_6, str text.Layout) clip.PathSpec {
|
||||
return textPath(ppem, f, str)
|
||||
}
|
||||
|
||||
func (f *Font) Metrics(ppem fixed.Int26_6) font.Metrics {
|
||||
metrics := font.Metrics{}
|
||||
font := harfbuzz.NewFont(f.font)
|
||||
font.XScale = int32(ppem.Ceil()) << 6
|
||||
font.YScale = font.XScale
|
||||
// Use any horizontal direction.
|
||||
fontExtents := font.ExtentsForDirection(harfbuzz.LeftToRight)
|
||||
ascender := fixed.I(int(fontExtents.Ascender * 64))
|
||||
descender := fixed.I(int(fontExtents.Descender * 64))
|
||||
gap := fixed.I(int(fontExtents.LineGap * 64))
|
||||
metrics.Height = ascender + descender + gap
|
||||
metrics.Ascent = ascender
|
||||
metrics.Descent = descender
|
||||
// These three are not readily available.
|
||||
// TODO(whereswaldon): figure out how to get these values.
|
||||
metrics.XHeight = ascender
|
||||
metrics.CapHeight = ascender
|
||||
metrics.CaretSlope = image.Pt(0, 1)
|
||||
|
||||
return metrics
|
||||
}
|
||||
|
||||
func textPath(ppem fixed.Int26_6, font *Font, str text.Layout) clip.PathSpec {
|
||||
var lastPos f32.Point
|
||||
var builder clip.Path
|
||||
ops := new(op.Ops)
|
||||
var x fixed.Int26_6
|
||||
builder.Begin(ops)
|
||||
rune := 0
|
||||
ppemInt := ppem.Round()
|
||||
ppem16 := uint16(ppemInt)
|
||||
scaleFactor := float32(ppemInt) / float32(font.font.Upem())
|
||||
for _, g := range str.Glyphs {
|
||||
advance := g.XAdvance
|
||||
outline, ok := font.font.GlyphData(g.ID, ppem16, ppem16).(fonts.GlyphOutline)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// Move to glyph position.
|
||||
pos := f32.Point{
|
||||
X: float32(x)/64 - float32(g.XOffset)/64,
|
||||
Y: -float32(g.YOffset) / 64,
|
||||
}
|
||||
builder.Move(pos.Sub(lastPos))
|
||||
lastPos = pos
|
||||
var lastArg f32.Point
|
||||
|
||||
// Convert sfnt.Segments to relative segments.
|
||||
for _, fseg := range outline.Segments {
|
||||
nargs := 1
|
||||
switch fseg.Op {
|
||||
case fonts.SegmentOpQuadTo:
|
||||
nargs = 2
|
||||
case fonts.SegmentOpCubeTo:
|
||||
nargs = 3
|
||||
}
|
||||
var args [3]f32.Point
|
||||
for i := 0; i < nargs; i++ {
|
||||
a := f32.Point{
|
||||
X: fseg.Args[i].X * scaleFactor,
|
||||
Y: -fseg.Args[i].Y * scaleFactor,
|
||||
}
|
||||
args[i] = a.Sub(lastArg)
|
||||
if i == nargs-1 {
|
||||
lastArg = a
|
||||
}
|
||||
}
|
||||
switch fseg.Op {
|
||||
case fonts.SegmentOpMoveTo:
|
||||
builder.Move(args[0])
|
||||
case fonts.SegmentOpLineTo:
|
||||
builder.Line(args[0])
|
||||
case fonts.SegmentOpQuadTo:
|
||||
builder.Quad(args[0], args[1])
|
||||
case fonts.SegmentOpCubeTo:
|
||||
builder.Cube(args[0], args[1], args[2])
|
||||
default:
|
||||
panic("unsupported segment op")
|
||||
}
|
||||
}
|
||||
lastPos = lastPos.Add(lastArg)
|
||||
x += advance
|
||||
rune++
|
||||
}
|
||||
return builder.End()
|
||||
func (f Face) Face() font.Face {
|
||||
return f.face
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user