feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+129
View File
@@ -0,0 +1,129 @@
package text
import (
"strconv"
"strings"
"testing"
)
// BenchmarkLayout lays out a wrapped paragraph without the cache, as each
// keystroke in an editor does.
func BenchmarkLayout(b *testing.B) {
s := Shared()
p := Params{Text: "The quick brown fox jumps over the lazy dog, and then some more words follow to wrap the paragraph over a few lines.", Style: Style{Size: 14}, Width: 300}
s.Layout(p)
b.ResetTimer()
for range b.N {
// What a keystroke's new text finds: nothing of its shaping kept.
s.ReleaseShaping()
s.mu.Lock()
s.layout(p)
s.mu.Unlock()
}
}
// BenchmarkLayoutLabel lays out a short label without the cache, as each
// text of a list's row coming into view does, and BenchmarkLayoutTruncated
// a line cut short with an ellipsis.
func BenchmarkLayoutLabel(b *testing.B) {
benchLayout(b, Params{Text: "Grace Hopper", Style: Style{Size: 12}})
}
func BenchmarkLayoutTruncated(b *testing.B) {
benchLayout(b, Params{Text: "fix the list scroll when rows change height and keep focus", Style: Style{Size: 12}, Width: 160, MaxLines: 1})
}
func BenchmarkLayoutTruncatedMiddle(b *testing.B) {
Shared().UseTruncateMiddle()
benchLayout(b, Params{Text: "src/components/settings/appearance/theme/picker.go", Style: Style{Size: 12}, Width: 160, MaxLines: 1, TruncateMiddle: true})
}
func BenchmarkLayoutTruncatedStart(b *testing.B) {
Shared().UseTruncateStart()
benchLayout(b, Params{Text: "src/components/settings/appearance/theme/picker.go", Style: Style{Size: 12}, Width: 160, MaxLines: 1, TruncateStart: true})
}
func benchLayout(b *testing.B, p Params) {
s := Shared()
s.Layout(p)
b.ReportAllocs()
for b.Loop() {
s.mu.Lock()
s.layout(p)
s.mu.Unlock()
}
}
// BenchmarkLayoutDocument lays out the paragraphs of a document taking a
// little more than the cache's budget, as each frame of a window showing
// it does, with the cache.
func BenchmarkLayoutDocument(b *testing.B) {
s := newSystem()
ps := document(s)
for _, p := range ps {
s.Layout(p)
}
s.EndFrame()
made := s.LayoutsMade()
b.ReportAllocs()
for b.Loop() {
for _, p := range ps {
s.Layout(p)
}
s.EndFrame()
}
b.ReportMetric(float64(s.LayoutsMade()-made)/float64(b.N), "layouts/op")
}
// BenchmarkLayoutResize wraps the 40 paragraphs of a document to another width
// in each frame, as a window being resized does, or a sidebar sliding, and
// BenchmarkLayoutResizeChinese in a language Core Text breaks lines of with a
// break iterator of its own.
func BenchmarkLayoutResize(b *testing.B) {
benchResize(b, "window button layout render scroll update shadow cursor memory thread signal bitmap stroke column editor kernel", "en")
}
func BenchmarkLayoutResizeChinese(b *testing.B) {
benchResize(b, "窗口 按钮 布局 渲染 滚动 更新 阴影 光标 内存 线程 信号 位图 笔画 栏目 编辑器 内核", "zh-Hans")
}
func benchResize(b *testing.B, list, lang string) {
s := newSystem()
words := strings.Fields(list)
var paragraphs []string
for i := range 40 {
var p strings.Builder
for j := range 70 {
p.WriteString(words[(i*7+j*j*3+j)%len(words)])
p.WriteByte(' ')
}
paragraphs = append(paragraphs, p.String())
}
width := float32(450)
b.ReportAllocs()
for b.Loop() {
if width++; width > 750 {
width = 450
}
for _, p := range paragraphs {
s.Layout(Params{Text: p, Width: width, Style: Style{Size: 13, Lang: lang}})
}
s.EndFrame()
}
}
// BenchmarkLayoutNumbers lays out the 600 numbers of a dashboard, each new in
// each frame.
func BenchmarkLayoutNumbers(b *testing.B) {
s := newSystem()
frame := 0
b.ReportAllocs()
for b.Loop() {
frame++
for i := range 600 {
v := (i*7919 + frame*31) % 100000
s.Layout(Params{Text: strconv.Itoa(v/100) + "." + strconv.Itoa(v%100 + 100)[1:], NoWrap: true, Style: Style{Size: 11}})
}
s.EndFrame()
}
}
+357
View File
@@ -0,0 +1,357 @@
//go:build js
package text
import (
"errors"
"math"
"strconv"
"strings"
"syscall/js"
"github.com/egoist/mygo/internal/scene"
)
// newEngine returns the canvas engine, or where there is no canvas to
// measure and draw text with (Node, workers of browsers without
// OffscreenCanvas), the stub engine.
func newEngine() engine {
if js.Global().Get("document").IsUndefined() && js.Global().Get("OffscreenCanvas").IsUndefined() {
return &stubEngine{}
}
return newCanvas()
}
// canvasEngine lays out and draws text with a canvas's 2D context, in
// browsers: the browser finds the fonts, falls back for what one lacks and
// shapes, as for its pages. Canvases tell how wide text is and draw it,
// not its glyphs: the engine's glyphs are grapheme clusters, measured
// within their words, which keeps the fonts' kerning, and drawn alone; a
// word of a script that joins or reorders its letters (Arabic, the scripts
// of India, …) is one glyph, drawn whole. go-text's segmenter finds the
// clusters and where lines may break, and its bidi package the direction
// of runs.
type canvasEngine struct {
clusterEngine
canvas, ctx js.Value
// current is the context's font now, kerning its fontKerning and fill
// its fillStyle.
current, kerning, fill string
fonts map[string]*Font
// names are the families the app registered fonts under.
names []string
// image is the canvas's pixels read back, reused.
image []byte
w, h int
}
// fontCSS is a CSS font without its size: the style and weight before it,
// the families after.
type fontCSS struct{ pre, family string }
// canvasFont is what the engine keeps of a Font (Font.data): its CSS font,
// and the texts of its glyphs, which a layout kept after the System let go
// of the Font still draws.
type canvasFont struct {
css fontCSS
glyphs *glyphTexts
}
func newCanvas() *canvasEngine {
e := &canvasEngine{fonts: map[string]*Font{}}
e.clusterEngine.init(e)
doc := js.Global().Get("document")
if doc.IsUndefined() {
e.canvas = js.Global().Get("OffscreenCanvas").New(64, 64)
} else {
e.canvas = doc.Call("createElement", "canvas")
e.canvas.Set("width", 64)
e.canvas.Set("height", 64)
}
e.w, e.h = 64, 64
e.ctx = e.canvas.Call("getContext", "2d", map[string]any{"willReadFrequently": true})
e.ctx.Set("textBaseline", "alphabetic")
e.ctx.Set("textAlign", "left")
e.ctx.Set("direction", "ltr")
e.ctx.Set("fillStyle", "#fff")
return e
}
// cssFamily turns a list of families into CSS's, with the generic ones
// the system's own.
func cssFamily(list string) string {
var out []string
for _, f := range familyList(list) {
switch generic(f) {
case "system-ui":
out = append(out, `system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji"`)
case "sans-serif":
out = append(out, "sans-serif")
case "serif":
out = append(out, "serif")
case "monospace":
out = append(out, `ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace`)
default:
out = append(out, strconv.Quote(f))
}
}
if len(out) == 0 {
return cssFamily("system-ui")
}
return strings.Join(out, ", ")
}
// cssOf returns the CSS font of a style.
func cssOf(style Style) fontCSS {
pre := strconv.Itoa(style.weight()) + " "
if style.Italic {
pre = "italic " + pre
}
return fontCSS{pre, cssFamily(style.Family)}
}
// at returns the CSS font at size px.
func (c fontCSS) at(size float32) string {
return c.pre + strconv.FormatFloat(float64(size), 'f', -1, 32) + "px " + c.family
}
func (e *canvasEngine) setFont(css string) {
if css != e.current {
e.current = css
e.ctx.Set("font", css)
}
}
func (e *canvasEngine) font(style Style) *Font {
size := style.FontSize()
fc := cssOf(style)
css := fc.at(size)
if f, ok := e.fonts[css]; ok {
return f
}
e.setFont(css)
m := e.ctx.Call("measureText", "Hg")
// Shaded: browsers draw text of each color with its own coverage, as
// Core Text's font smoothing emboldens lighter text more, and Skia
// corrects coverage by the text's luminance. Thick text is drawn in
// white, the boldest.
f := &Font{Size: size, data: &canvasFont{fc, e.glyphs}, shaded: true, thickens: true}
if a := m.Get("fontBoundingBoxAscent"); a.Type() == js.TypeNumber {
f.Ascent, f.Descent = float32(a.Float()), float32(m.Get("fontBoundingBoxDescent").Float())
} else {
f.Ascent, f.Descent = size*0.9, size*0.25
}
// Underlines a tenth of an em below the baseline, strikethroughs
// through the middle of an x.
thick := max(size/14, 1)
f.underlineTop, f.underlineThick = -size/10, thick
x := e.ctx.Call("measureText", "x").Get("actualBoundingBoxAscent")
if x.Type() == js.TypeNumber {
f.strikeTop = float32(x.Float())/2 + thick/2
} else {
f.strikeTop = size * 0.3
}
f.strikeThick = thick
e.fonts[css] = f
return f
}
// measure returns how wide text is in f, kerned unless noKern.
func (e *canvasEngine) measure(f *Font, text string, noKern bool) float32 {
e.setFont(e.sized(f, f.Size))
kerning := "normal"
if noKern {
kerning = "none"
}
if kerning != e.kerning {
e.kerning = kerning
e.ctx.Set("fontKerning", kerning)
}
return float32(e.ctx.Call("measureText", text).Get("width").Float())
}
// sized returns the CSS font of f at size px.
func (e *canvasEngine) sized(f *Font, size float32) string {
return f.data.(*canvasFont).css.at(size)
}
// shadeGray is the gray glyphs of text of each shade are drawn in: of
// relative luminance 0, 1/4, 1/2 and 3/4 (ShadeOf), and white for Thick.
// Canvases draw no text unsmoothed: Flat is drawn as the darkest shade.
var shadeGray = [...]uint8{0, 137, 188, 225, 255, 0}
// glyph draws a glyph's text in the gray of its shade and reads its
// coverage back: gray, or color for color fonts (emoji).
func (e *canvasEngine) glyph(f *Font, id uint32, scale, dx float32, shade Shade, _ bool) bitmap {
// The texts of the glyphs of f's time: the engine's may be newer.
texts := f.data.(*canvasFont).glyphs.texts
if int(id) >= len(texts) || id == 0 {
return bitmap{}
}
text := texts[id]
if strings.TrimSpace(text) == "" {
return bitmap{}
}
// The font at the size text was measured at, the canvas scaled: at
// the pixels' size, the system's font may take another optical size
// (SF Pro Display rather than Text), whose glyphs the advances measured
// do not fit, as pages draw at the CSS size, scaled.
e.setFont(e.sized(f, f.Size))
m := e.ctx.Call("measureText", text)
s := float64(scale)
l, r := s*m.Get("actualBoundingBoxLeft").Float(), s*m.Get("actualBoundingBoxRight").Float()
a, d := s*m.Get("actualBoundingBoxAscent").Float(), s*m.Get("actualBoundingBoxDescent").Float()
const pad = 1
left := int(math.Floor(-l+float64(dx))) - pad
right := int(math.Ceil(r+float64(dx))) + pad
top := int(math.Floor(-a)) - pad
bottom := int(math.Ceil(d)) + pad
w, h := right-left, bottom-top
if w <= 2*pad || h <= 2*pad || w > 2048 || h > 2048 {
return bitmap{}
}
if w > e.w || h > e.h {
e.w, e.h = max(w, e.w), max(h, e.h)
e.canvas.Set("width", e.w)
e.canvas.Set("height", e.h)
// A canvas resized forgets its state.
e.current = ""
e.setFont(e.sized(f, f.Size))
e.ctx.Set("textBaseline", "alphabetic")
e.ctx.Set("textAlign", "left")
e.fill = ""
}
gray := shadeGray[0]
if int(shade) < len(shadeGray) {
gray = shadeGray[shade]
}
if fill := "rgb(" + strconv.Itoa(int(gray)) + "," + strconv.Itoa(int(gray)) + "," + strconv.Itoa(int(gray)) + ")"; fill != e.fill {
e.fill = fill
e.ctx.Set("fillStyle", fill)
}
e.ctx.Call("clearRect", 0, 0, w, h)
e.ctx.Call("setTransform", s, 0, 0, s, 0, 0)
e.ctx.Call("fillText", text, (float64(dx)-float64(left))/s, -float64(top)/s)
e.ctx.Call("setTransform", 1, 0, 0, 1, 0, 0)
data := e.ctx.Call("getImageData", 0, 0, w, h).Get("data")
n := 4 * w * h
if cap(e.image) < n {
e.image = make([]byte, n)
}
px := e.image[:n]
js.CopyBytesToGo(px, data)
// The ink's box: measurements leave room around it.
x0, y0, x1, y1 := w, h, 0, 0
for y := range h {
for x := range w {
if px[4*(y*w+x)+3] != 0 {
x0, y0, x1, y1 = min(x0, x), min(y0, y), max(x1, x+1), max(y1, y+1)
}
}
}
if x0 >= x1 {
return bitmap{}
}
if x0 > 0 || y0 > 0 || x1 < w || y1 < h {
cw, ch := x1-x0, y1-y0
for y := range ch {
copy(px[4*y*cw:4*(y+1)*cw], px[4*((y+y0)*w+x0):4*((y+y0)*w+x1)])
}
left, top, w, h = left+x0, top+y0, cw, ch
n = 4 * w * h
px = px[:n]
}
// Gray text is its gray where it covers: the alpha is the coverage.
// Others are colored.
color := false
far := func(c uint8) bool { return int(c) > int(gray)+32 || int(gray) > int(c)+32 }
for i := 0; i < n; i += 4 {
if px[i+3] > 32 && (far(px[i]) || far(px[i+1]) || far(px[i+2])) {
color = true
break
}
}
bm := bitmap{left: left, top: top, w: w, h: h, color: color}
if color {
bm.pix = make([]byte, n)
for i := 0; i < n; i += 4 {
al := uint16(px[i+3])
bm.pix[i] = uint8((uint16(px[i])*al + 127) / 255)
bm.pix[i+1] = uint8((uint16(px[i+1])*al + 127) / 255)
bm.pix[i+2] = uint8((uint16(px[i+2])*al + 127) / 255)
bm.pix[i+3] = px[i+3]
}
return bm
}
bm.pix = make([]byte, w*h)
for i := range w * h {
bm.pix[i] = px[4*i+3]
}
return bm
}
// maxTexts is how many glyphs, texts, the engine keeps before it has the
// System let go of its fonts with them: a glyph is a cluster, or a whole
// word of some scripts, which pile up with what a long session shows.
const maxTexts = 1 << 16
func (e *canvasEngine) fontCount() int {
if len(e.glyphs.texts) > maxTexts {
return maxFonts + 1
}
return len(e.fonts)
}
// forgetFonts lets go of the fonts, and of the glyphs and measurements.
// A Font kept by a layout keeps its CSS font and its glyphs' texts.
func (e *canvasEngine) forgetFonts() {
clear(e.fonts)
e.forgetGlyphs()
}
// releaseFonts has nothing to release: the browser keeps its fonts.
func (e *canvasEngine) releaseFonts() {}
// pens leaves the browser's words to measure, cluster by cluster.
func (e *canvasEngine) pens(*Font, []rune, []int, bool) []float32 { return nil }
// textParams leaves coverage as the browser drew it, without subpixel
// antialiasing, which canvases do not read back.
func (e *canvasEngine) textParams() (scene.TextParams, bool) { return scene.TextParams{}, false }
// appFamilies lists the app's families. A family is monospaced when an
// "i" is as wide as a "W" in it, which tells only once its face has
// loaded.
func (e *canvasEngine) appFamilies() []FontFamily {
out := make([]FontFamily, len(e.names))
for i, name := range e.names {
e.setFont("100px " + strconv.Quote(name))
mono := e.ctx.Call("measureText", "i").Get("width").Float() == e.ctx.Call("measureText", "W").Get("width").Float()
out[i] = FontFamily{Name: name, Monospaced: mono}
}
return out
}
// systemFamilies lists none: a browser does not tell what fonts it has.
func (e *canvasEngine) systemFamilies() func() []FontFamily { return nil }
// register adds a font file to the document's fonts, as a FontFace of
// family, or of its own family when family is "" (which the browser does
// not tell: the face needs a family). Browsers load faces in the
// background: text laid out before draws with others.
func (e *canvasEngine) register(data []byte, family string) error {
if family == "" {
return errNoFamily
}
buf := js.Global().Get("Uint8Array").New(len(data))
js.CopyBytesToJS(buf, data)
face := js.Global().Get("FontFace").New(family, buf.Get("buffer"))
fonts := js.Global().Get("document").Get("fonts")
fonts.Call("add", face)
face.Call("load").Call("catch", js.Global().Get("Function").New(""))
e.names = append(e.names, family)
clear(e.words)
return nil
}
var errNoFamily = errors.New("mygo: browsers need the family of a font to add")
+72
View File
@@ -0,0 +1,72 @@
package text
import (
"slices"
"syscall/js"
"testing"
"unicode/utf8"
)
// fakeCanvas has the canvas engine measure every character 10 DIPs wide,
// where no browser gives it a canvas, as Node.js.
func fakeCanvas(t *testing.T) {
g := js.Global()
if !g.Get("document").IsUndefined() || !g.Get("OffscreenCanvas").IsUndefined() {
return
}
measure := js.FuncOf(func(this js.Value, args []js.Value) any {
return map[string]any{
"width": 10 * utf8.RuneCountInString(args[0].String()),
"fontBoundingBoxAscent": 8,
"fontBoundingBoxDescent": 2,
"actualBoundingBoxAscent": 5,
}
})
getContext := js.FuncOf(func(this js.Value, args []js.Value) any {
ctx := g.Get("Object").New()
ctx.Set("measureText", measure)
return ctx
})
canvas := js.FuncOf(func(this js.Value, args []js.Value) any {
c := g.Get("Object").New()
c.Set("getContext", getContext)
return c
})
g.Set("OffscreenCanvas", canvas)
t.Cleanup(func() {
g.Delete("OffscreenCanvas")
canvas.Release()
getContext.Release()
measure.Release()
})
}
// The canvas engine breaks Korean between words (#1403).
func TestCanvasKeepAll(t *testing.T) {
fakeCanvas(t)
e := newCanvas()
ends := func(text, lang string, width float32, wholeWords bool) []int {
var out []int
for _, l := range e.shape([]rune(text), Style{Size: 16, Lang: lang}, nil, width, false, wholeWords) {
out = append(out, l.end)
}
return out
}
const text = "안녕하세요 반갑습니다 오늘은 날씨가 좋네요"
for _, c := range []struct {
text, lang string
wholeWords bool
want []int
}{
{text, "ko", false, []int{6, 12, 16, 20, 23}},
{text, "ko-KR", false, []int{6, 12, 16, 20, 23}},
{text, "en", false, []int{6, 12, 17, 22, 23}},
// A word longer than a line breaks within itself.
{"가나 다라마바사아자 차", "ko", false, []int{3, 8, 12}},
{"가나 다라마바사아자 차", "ko", true, []int{3, 11, 12}},
} {
if got := ends(c.text, c.lang, 50, c.wholeWords); !slices.Equal(got, c.want) {
t.Errorf("%q in %q, whole words %v: lines end at %v, want %v", c.text, c.lang, c.wholeWords, got, c.want)
}
}
}
+285
View File
@@ -0,0 +1,285 @@
package text
import "slices"
// Affinity chooses the preceding or following logical text at a boundary.
// The two edges can occupy different positions in bidi text or at a wrap.
type Affinity uint8
const (
Downstream Affinity = iota
Upstream
)
type CaretPosition struct {
Index int
Affinity Affinity
}
type Range struct{ Start, End int }
type caretStop struct {
position CaretPosition
x float32
// arrival is the visual direction from which this edge is reached.
arrival int
}
func (l *Layout) visualStops(li int) []caretStop {
line := &l.Lines[li]
if line.stops != nil {
return line.stops
}
if l.boundaries == nil {
var b Boundaries
b.Reset(l.Runes)
l.boundaries = b.GraphemeOffsets()
}
var stops []caretStop
// Offsets the glyph scan appended, so the boundary sweep below skips
// them without rescanning the stops. Stops outside the line's range
// can't match a swept offset, so only in-range ones set a flag.
seen := make([]bool, line.End-line.Start+1)
line.upstream = slices.Clone(line.lineCarets())
for i := 0; i < len(line.Glyphs); {
g := line.Glyphs[i]
x0, x1 := g.X, g.X+g.Advance
i++
for i < len(line.Glyphs) && line.Glyphs[i].Cluster == g.Cluster && line.Glyphs[i].Runes == g.Runes {
x0 = min(x0, line.Glyphs[i].X)
x1 = max(x1, line.Glyphs[i].X+line.Glyphs[i].Advance)
i++
}
if g.Runes <= 0 {
continue
}
for k := 0; k <= g.Runes; k++ {
at := g.Cluster + k
if _, ok := slices.BinarySearch(l.boundaries, at); !ok {
continue
}
x := x0 + (x1-x0)*float32(k)/float32(g.Runes)
if g.RTL {
x = x1 - (x1-x0)*float32(k)/float32(g.Runes)
}
affinity, arrival := Downstream, 0
if k == 0 {
arrival = -1
}
if k == g.Runes {
affinity, arrival = Upstream, 1
}
if g.RTL {
arrival = -arrival
}
if affinity == Upstream && at >= line.Start && at <= line.End {
line.upstream[at-line.Start] = x
}
stops = append(stops, caretStop{CaretPosition{at, affinity}, x, arrival})
if at >= line.Start && at <= line.End {
seen[at-line.Start] = true
}
}
}
// Keep trimmed spaces and empty lines navigable too.
carets := line.lineCarets()
first, _ := slices.BinarySearch(l.boundaries, line.Start)
for k := first; k < len(l.boundaries) && l.boundaries[k] <= line.End; k++ {
at := l.boundaries[k]
if !seen[at-line.Start] {
stops = append(stops, caretStop{CaretPosition{at, Downstream}, carets[at-line.Start], 0})
}
}
if len(stops) == 0 {
stops = append(stops, caretStop{CaretPosition{line.Start, Downstream}, line.X, 0})
}
slices.SortStableFunc(stops, func(a, b caretStop) int {
if a.x < b.x {
return -1
}
if a.x > b.x {
return 1
}
return 0
})
line.stops = stops
return stops
}
func (l *Layout) caretLine(p CaretPosition) int {
li := l.LineAt(p.Index)
if p.Affinity == Upstream && li > 0 && l.Lines[li].Start == p.Index && l.Lines[li-1].End == p.Index {
li--
}
return li
}
// CaretAt preserves affinity at bidi boundaries and soft line breaks.
func (l *Layout) CaretAt(p CaretPosition) (x, y, h float32) {
if len(l.Lines) == 0 {
return 0, 0, 0
}
p.Index = max(0, min(p.Index, len(l.Runes)))
li := l.caretLine(p)
l.visualStops(li)
line := &l.Lines[li]
i := max(0, min(p.Index-line.Start, len(line.carets)-1))
x = line.carets[i]
if p.Affinity == Upstream {
x = line.upstream[i]
}
return x, line.Y, line.Height
}
// PositionAt hit-tests whole graphemes, retaining the visual edge chosen.
func (l *Layout) PositionAt(x, y float32) CaretPosition {
if len(l.Lines) == 0 {
return CaretPosition{}
}
li := len(l.Lines) - 1
for i := range l.Lines {
if y < l.Lines[i].Y+l.Lines[i].Height {
li = i
break
}
}
stops := l.visualStops(li)
best, distance := stops[0], float32(-1)
for _, s := range stops {
d := abs(s.x - x)
// Affinity breaks ties at one offset, not across offsets sharing
// an edge, such as the positions before and after a trimmed space.
if distance < 0 || d < distance || d == distance && s.position.Index == best.position.Index && s.position.Affinity == Downstream {
best, distance = s, d
}
}
return best.position
}
func abs(x float32) float32 {
if x < 0 {
return -x
}
return x
}
func arriving(stops []caretStop, x float32, direction int) CaretPosition {
var p CaretPosition
for _, s := range stops {
// Native runs can disagree by a few float32 rounding bits at their
// shared edge, especially when fallback fonts precede a bidi run.
if abs(s.x-x) > 0.01 {
continue
}
p = s.position
if s.arrival == direction {
return p
}
}
return p
}
// MoveCaret advances one visual grapheme, preserving the edge arrived at.
func (l *Layout) MoveCaret(p CaretPosition, direction int) CaretPosition {
if len(l.Lines) == 0 || direction == 0 {
return p
}
if direction < 0 {
direction = -1
} else {
direction = 1
}
li := l.caretLine(p)
x, _, _ := l.CaretAt(p)
stops := l.visualStops(li)
if direction > 0 {
for _, s := range stops {
if s.x > x+0.001 {
return arriving(stops, s.x, direction)
}
}
} else {
for i := len(stops) - 1; i >= 0; i-- {
if stops[i].x < x-0.001 {
return arriving(stops, stops[i].x, direction)
}
}
}
next := li + direction
if l.Lines[li].RTL {
next = li - direction
}
if next < 0 || next >= len(l.Lines) {
return p
}
stops = l.visualStops(next)
x = stops[0].x
if direction < 0 {
x = stops[len(stops)-1].x
}
return arriving(stops, x, direction)
}
// SelectionRanges returns logical ranges covered by a visual gesture.
// A gesture through mixed-direction text can cover discontiguous ranges.
func (l *Layout) SelectionRanges(a, b CaretPosition) []Range {
if len(l.Lines) == 0 {
return nil
}
ai, bi := l.caretLine(a), l.caretLine(b)
ax, _, _ := l.CaretAt(a)
bx, _, _ := l.CaretAt(b)
if ai > bi {
ai, bi, ax, bx = bi, ai, bx, ax
}
var ranges []Range
for li := ai; li <= bi; li++ {
line := &l.Lines[li]
lo, hi := line.X, line.X+line.Width
if ai == bi {
lo, hi = min(ax, bx), max(ax, bx)
} else {
if li == ai {
if line.RTL {
hi = ax
} else {
lo = ax
}
}
if li == bi {
if line.RTL {
lo = bx
} else {
hi = bx
}
}
}
l.visualStops(li)
first, _ := slices.BinarySearch(l.boundaries, line.Start)
for k := first; k+1 < len(l.boundaries) && l.boundaries[k] < line.End; k++ {
start, end := l.boundaries[k], l.boundaries[k+1]
if start < line.Start || end > line.End {
continue
}
x0, _, _ := l.CaretAt(CaretPosition{start, Downstream})
x1, _, _ := l.CaretAt(CaretPosition{end, Upstream})
left, right := min(x0, x1), max(x0, x1)
if right > left && left >= lo-0.01 && right <= hi+0.01 {
ranges = append(ranges, Range{start, end})
}
}
if li < bi && li+1 < len(l.Lines) && l.Lines[li+1].Start > line.End {
ranges = append(ranges, Range{line.End, l.Lines[li+1].Start})
}
}
slices.SortFunc(ranges, func(a, b Range) int { return a.Start - b.Start })
out := ranges[:0]
for _, r := range ranges {
if n := len(out); n > 0 && out[n-1].End >= r.Start {
out[n-1].End = max(out[n-1].End, r.End)
} else {
out = append(out, r)
}
}
return out
}
+28
View File
@@ -0,0 +1,28 @@
package text
import "testing"
// BenchmarkVisualStopsLongLine computes the visual caret stops of one very
// long line, as opening a minified or generated file does. Fixed advances
// keep the fixture independent of installed fonts; shaping and setup are not
// timed, and the stops cache is dropped every iteration, as an edit does.
func BenchmarkVisualStopsLongLine(b *testing.B) {
const runes = 200_000
l := &Layout{Runes: make([]rune, runes), Lines: []Line{{Start: 0, End: runes, Width: runes * 8, Height: 20}}}
for i := range l.Runes {
l.Runes[i] = 'a'
}
line := &l.Lines[0]
line.Glyphs = make([]Glyph, runes)
for i := range line.Glyphs {
line.Glyphs[i] = Glyph{X: float32(i) * 8, Advance: 8, Cluster: i, Runes: 1}
}
b.ReportAllocs()
for b.Loop() {
line.stops = nil
stops := l.visualStops(0)
if len(stops) != 2*runes {
b.Fatalf("got %d stops, want %d", len(stops), 2*runes)
}
}
}
+382
View File
@@ -0,0 +1,382 @@
package text
import (
"slices"
"strings"
"testing"
)
// Fixed advances keep geometry regressions independent of installed fonts.
func mixedLayout() *Layout {
runes := []rune("abc אבג def")
l := &Layout{Runes: runes, Lines: []Line{{Start: 0, End: len(runes), Width: 110, Height: 20}}}
for i := range runes {
x, rtl := float32(i*10), i >= 4 && i < 7
if rtl {
x = float32((10 - i) * 10)
}
l.Lines[0].Glyphs = append(l.Lines[0].Glyphs, Glyph{X: x, Advance: 10, Cluster: i, Runes: 1, RTL: rtl})
}
return l
}
func TestVisualCaretAffinityAndNavigation(t *testing.T) {
l := mixedLayout()
a, _, _ := l.CaretAt(CaretPosition{4, Upstream})
b, _, _ := l.CaretAt(CaretPosition{4, Downstream})
if a != 40 || b != 70 {
t.Fatalf("bidi edges %v %v", a, b)
}
p := CaretPosition{3, Downstream}
for _, want := range []CaretPosition{{4, Upstream}, {6, Downstream}, {5, Downstream}, {4, Downstream}, {8, Upstream}} {
p = l.MoveCaret(p, 1)
if p != want {
t.Fatalf("right: got %+v want %+v", p, want)
}
}
for _, want := range []CaretPosition{{7, Downstream}, {5, Upstream}, {6, Upstream}, {7, Upstream}, {3, Downstream}} {
p = l.MoveCaret(p, -1)
if p != want {
t.Fatalf("left: got %+v want %+v", p, want)
}
}
}
func TestVisualSelectionKeepsBidiGaps(t *testing.T) {
l := mixedLayout()
ranges := l.SelectionRanges(CaretPosition{6, Downstream}, CaretPosition{8, Upstream})
if !slices.Equal(ranges, []Range{{4, 6}, {7, 8}}) {
t.Fatalf("selection %v", ranges)
}
var rects []Rect
for _, r := range ranges {
rects = append(rects, l.SelectionVisual(r.Start, r.End, false)...)
}
if len(rects) != 2 || rects[0].X != 50 || rects[1].X != 70 {
t.Fatalf("bidi rectangles %v", rects)
}
}
func TestVisualCaretFractionalRunEdges(t *testing.T) {
l := mixedLayout()
l.Lines[0].Glyphs[4].Advance += 0.00001
p := l.MoveCaret(CaretPosition{Index: 5}, 1)
if p != (CaretPosition{Index: 4, Affinity: Downstream}) {
t.Fatalf("rounding selected the wrong run edge: %+v", p)
}
}
func TestVisualCaretWrapAndGraphemes(t *testing.T) {
l := &Layout{Runes: []rune("é😀x"), Lines: []Line{
{Start: 0, End: 3, Width: 20, Height: 20, Glyphs: []Glyph{{Advance: 10, Cluster: 0, Runes: 2}, {X: 10, Advance: 10, Cluster: 2, Runes: 1}}},
{Start: 3, End: 4, Y: 20, Width: 10, Height: 20, Glyphs: []Glyph{{Advance: 10, Cluster: 3, Runes: 1}}},
}}
p := l.MoveCaret(CaretPosition{}, 1)
if p.Index != 2 {
t.Fatalf("split grapheme %+v", p)
}
_, up, _ := l.CaretAt(CaretPosition{3, Upstream})
_, down, _ := l.CaretAt(CaretPosition{3, Downstream})
if up != 0 || down != 20 {
t.Fatalf("wrap affinity %v %v", up, down)
}
p = l.PositionAt(20, 10)
if p != (CaretPosition{3, Upstream}) {
t.Fatalf("wrap hit %+v", p)
}
p = l.MoveCaret(p, 1)
if p.Index != 3 || p.Affinity != Downstream {
t.Fatalf("wrap movement %+v", p)
}
}
// A trimmed wrap space shares the last visible glyph's edge. Choosing the
// later offset on a tie would copy whitespace the pointer never crossed.
func TestVisualCaretHitBeforeTrimmedWrapSpace(t *testing.T) {
l := &Layout{Runes: []rune("ab cd"), Lines: []Line{
{Start: 0, End: 3, Width: 20, Height: 20, Glyphs: []Glyph{{Advance: 10, Cluster: 0, Runes: 1}, {X: 10, Advance: 10, Cluster: 1, Runes: 1}}},
{Start: 3, End: 5, Y: 20, Width: 20, Height: 20, Glyphs: []Glyph{{Advance: 10, Cluster: 3, Runes: 1}, {X: 10, Advance: 10, Cluster: 4, Runes: 1}}},
}}
x, y, h := l.Caret(2)
if p := l.PositionAt(x, y+h/2); p != (CaretPosition{Index: 2, Affinity: Upstream}) {
t.Fatalf("hit before trimmed space selected %+v", p)
}
}
// Compare the line filter with the original glyph-by-glyph scan. Fixed geometry
// covers every boundary without depending on platform fonts or shaping engines.
func TestSelectionVisualLineSkipMatchesFullScan(t *testing.T) {
wrapped := &Layout{Runes: []rune("aaaa bbbb\ncccc dddd")}
for _, span := range [][2]int{{0, 5}, {5, 9}, {10, 19}} {
line := Line{Start: span[0], End: span[1], Width: float32((span[1] - span[0]) * 10), Height: 20, Y: float32(len(wrapped.Lines) * 20)}
for i := span[0]; i < span[1]; i++ {
line.Glyphs = append(line.Glyphs, Glyph{X: float32((i - span[0]) * 10), Advance: 10, Cluster: i, Runes: 1})
}
wrapped.Lines = append(wrapped.Lines, line)
}
// The initial and final empty lines and the consecutive newlines all have
// selectable newline boxes, even though they contain no glyphs.
emptyLines := &Layout{Runes: []rune("\nx\n\n"), Lines: []Line{
{Start: 0, End: 0, Height: 20},
{Start: 1, End: 2, Y: 20, Width: 10, Height: 20, Glyphs: []Glyph{{Advance: 10, Cluster: 1, Runes: 1}}},
{Start: 3, End: 3, Y: 40, Height: 20, RTL: true},
{Start: 4, End: 4, Y: 60, Height: 20},
}}
// A bidi line between two wrapped lines also has a cluster with multiple
// glyphs and runes, plus an ellipsis (zero runes) on the final line.
bidi := mixedLayout()
bidi.Runes = append([]rune("fi"), append(bidi.Runes, 'x')...)
bidi.Lines[0].Start, bidi.Lines[0].End = 2, len(bidi.Runes)-1
bidi.Lines[0].Y = 20
for i := range bidi.Lines[0].Glyphs {
bidi.Lines[0].Glyphs[i].Cluster += 2
}
bidi.Lines = append([]Line{{Start: 0, End: 2, Width: 20, Height: 20, Glyphs: []Glyph{
{Advance: 12, Cluster: 0, Runes: 2}, {X: 10, Advance: 10, Cluster: 0, Runes: 2},
}}}, bidi.Lines...)
bidi.Lines = append(bidi.Lines, Line{Start: len(bidi.Runes) - 1, End: len(bidi.Runes), Y: 40, Width: 20, Height: 20, Glyphs: []Glyph{
{Advance: 10, Cluster: len(bidi.Runes) - 1, Runes: 1}, {X: 10, Advance: 10, Cluster: len(bidi.Runes), Runes: 0},
}})
for _, tc := range []struct {
name string
layout *Layout
}{
{"wrapped", wrapped}, {"empty_lines", emptyLines}, {"bidi_ligature", bidi},
{"empty", &Layout{Lines: []Line{{Height: 20}}}},
{"no_lines", &Layout{}},
} {
t.Run(tc.name, func(t *testing.T) {
for start := -1; start <= len(tc.layout.Runes)+1; start++ {
for end := -1; end <= len(tc.layout.Runes)+1; end++ {
for _, on := range []bool{false, true} {
got := tc.layout.SelectionVisual(start, end, on)
want := selectionVisualFullScan(tc.layout, start, end, on)
if !slices.Equal(got, want) {
t.Fatalf("range %d..%d on=%v: got %v, full scan %v", start, end, on, got, want)
}
}
}
}
})
}
}
// selectionVisualFullScan preserves the pre-filter implementation as an oracle:
// changes to which lines are visited must preserve its rectangles exactly.
func selectionVisualFullScan(l *Layout, start, end int, on bool) []Rect {
if start > end {
start, end = end, start
}
if on {
end = len(l.Runes) + 1
}
var out []Rect
for li := range l.Lines {
line := &l.Lines[li]
var pieces []Rect
for i := 0; i < len(line.Glyphs); {
first := line.Glyphs[i]
x0, x1 := first.X, first.X+first.Advance
i++
for i < len(line.Glyphs) && line.Glyphs[i].Cluster == first.Cluster && line.Glyphs[i].Runes == first.Runes {
x0, x1 = min(x0, line.Glyphs[i].X), max(x1, line.Glyphs[i].X+line.Glyphs[i].Advance)
i++
}
a, z := max(start, first.Cluster), min(end, first.Cluster+first.Runes)
if a >= z || first.Runes <= 0 {
continue
}
width := x1 - x0
left, right := float32(a-first.Cluster)/float32(first.Runes), float32(z-first.Cluster)/float32(first.Runes)
if first.RTL {
left, right = 1-right, 1-left
}
pieces = append(pieces, Rect{x0 + left*width, line.Y, (right - left) * width, line.Height})
}
if start <= line.End && end > line.End && (li < len(l.Lines)-1 && l.Lines[li+1].Start > line.End || li == len(l.Lines)-1 && on) {
x, width := line.X+line.Width, l.Params.Style.FontSize()/3
if line.RTL {
x = line.X - width
}
pieces = append(pieces, Rect{x, line.Y, width, line.Height})
}
slices.SortFunc(pieces, func(a, b Rect) int {
if a.X < b.X {
return -1
}
if a.X > b.X {
return 1
}
return 0
})
for _, r := range pieces {
if r.W <= 0 {
continue
}
if n := len(out); n > 0 && out[n-1].Y == r.Y && out[n-1].X+out[n-1].W >= r.X-0.01 {
out[n-1].W = max(out[n-1].X+out[n-1].W, r.X+r.W) - out[n-1].X
} else {
out = append(out, r)
}
}
}
return out
}
// TestVisualStopsMatchesFullScan compares visualStops with the original
// pairwise scan as an oracle, on fixtures for every stop source: glyph
// edges, fractionally split clusters, bidi runs, offsets only the boundary
// sweep visits (trimmed wrap spaces, empty lines) and glyphs outside the
// line's range. Fixed geometry covers every boundary without depending on
// platform fonts or shaping engines.
func TestVisualStopsMatchesFullScan(t *testing.T) {
var long strings.Builder
for i := 0; i < 4096; i++ {
long.WriteRune('a')
if i%7 == 3 {
long.WriteRune('\u0301')
}
}
// Duplicate clusters append two stops at one offset, a ligature shares
// one cluster between glyphs, and the ellipsis has no runes at all.
ligature := mixedLayout()
ligature.Runes = append([]rune("fi"), append(ligature.Runes, 'x')...)
ligature.Lines[0].Start, ligature.Lines[0].End = 2, len(ligature.Runes)-1
ligature.Lines[0].Y = 20
for i := range ligature.Lines[0].Glyphs {
ligature.Lines[0].Glyphs[i].Cluster += 2
}
ligature.Lines = append([]Line{{Start: 0, End: 2, Width: 20, Height: 20, Glyphs: []Glyph{
{Advance: 12, Cluster: 0, Runes: 2}, {X: 10, Advance: 10, Cluster: 0, Runes: 2},
}}}, ligature.Lines...)
ligature.Lines = append(ligature.Lines, Line{Start: len(ligature.Runes) - 1, End: len(ligature.Runes), Y: 40, Width: 20, Height: 20, Glyphs: []Glyph{
{Advance: 10, Cluster: len(ligature.Runes) - 1, Runes: 1}, {X: 10, Advance: 10, Cluster: len(ligature.Runes), Runes: 0},
}})
for _, tc := range []struct {
name string
layout *Layout
}{
{"ascii", graphemeLayout("hello world")},
{"crlf", graphemeLayout("a\r\nb")},
{"emoji_zwj", graphemeLayout("\U0001F468\u200D\U0001F469\u200D\U0001F466x")},
{"flags", graphemeLayout("🇯🇵🇯🇵")},
{"cjk", graphemeLayout("你好世界")},
{"combining", graphemeLayout("a\u0301e\u0327x")},
{"trailing_spaces", graphemeLayout("ab ")},
{"rtl_bidi", mixedLayout()},
{"long_mixed", graphemeLayout(long.String())},
{"wrapped_trimmed_space", &Layout{Runes: []rune("ab cd"), Lines: []Line{
{Start: 0, End: 3, Width: 20, Height: 20, Glyphs: []Glyph{{Advance: 10, Cluster: 0, Runes: 1}, {X: 10, Advance: 10, Cluster: 1, Runes: 1}}},
{Start: 3, End: 5, Y: 20, Width: 20, Height: 20, Glyphs: []Glyph{{Advance: 10, Cluster: 3, Runes: 1}, {X: 10, Advance: 10, Cluster: 4, Runes: 1}}},
}}},
{"empty_lines", &Layout{Runes: []rune("\nx\n\n"), Lines: []Line{
{Start: 0, End: 0, Height: 20},
{Start: 1, End: 2, Y: 20, Width: 10, Height: 20, Glyphs: []Glyph{{Advance: 10, Cluster: 1, Runes: 1}}},
{Start: 3, End: 3, Y: 40, Height: 20, RTL: true},
{Start: 4, End: 4, Y: 60, Height: 20},
}}},
{"ligature", ligature},
{"glyphs_outside_line", &Layout{Runes: []rune("abcd"), Lines: []Line{
{Start: 0, End: 2, Width: 20, Height: 20, Glyphs: []Glyph{{Advance: 10, Cluster: 3, Runes: 1}}},
{Start: 2, End: 4, Y: 20, Width: 20, Height: 20, Glyphs: []Glyph{{Advance: 10, Cluster: 0, Runes: 1}}},
}}},
} {
t.Run(tc.name, func(t *testing.T) {
for li := range tc.layout.Lines {
got := tc.layout.visualStops(li)
want := visualStopsFullScan(tc.layout, li)
if !slices.Equal(got, want) {
t.Fatalf("line %d: got %v, full scan %v", li, got, want)
}
}
})
}
}
// graphemeLayout lays out s as one line of fixed-advance glyphs, one per
// grapheme at the offsets the segmenter reports, so multi-rune graphemes
// split their edge positions fractionally.
func graphemeLayout(s string) *Layout {
runes := []rune(s)
var b Boundaries
b.Reset(runes)
offsets := b.GraphemeOffsets()
l := &Layout{Runes: runes, Lines: []Line{{Start: 0, End: len(runes), Width: float32(len(runes)) * 10, Height: 20}}}
for k := 0; k+1 < len(offsets); k++ {
l.Lines[0].Glyphs = append(l.Lines[0].Glyphs, Glyph{X: float32(offsets[k]) * 10, Advance: 10, Cluster: offsets[k], Runes: offsets[k+1] - offsets[k]})
}
return l
}
// visualStopsFullScan preserves the pre-mask implementation as an oracle:
// it rebuilds a line's stops with the original pairwise ContainsFunc scan,
// without touching the cache.
func visualStopsFullScan(l *Layout, li int) []caretStop {
line := &l.Lines[li]
if l.boundaries == nil {
var b Boundaries
b.Reset(l.Runes)
l.boundaries = b.GraphemeOffsets()
}
var stops []caretStop
line.upstream = slices.Clone(line.lineCarets())
for i := 0; i < len(line.Glyphs); {
g := line.Glyphs[i]
x0, x1 := g.X, g.X+g.Advance
i++
for i < len(line.Glyphs) && line.Glyphs[i].Cluster == g.Cluster && line.Glyphs[i].Runes == g.Runes {
x0 = min(x0, line.Glyphs[i].X)
x1 = max(x1, line.Glyphs[i].X+line.Glyphs[i].Advance)
i++
}
if g.Runes <= 0 {
continue
}
for k := 0; k <= g.Runes; k++ {
at := g.Cluster + k
if _, ok := slices.BinarySearch(l.boundaries, at); !ok {
continue
}
x := x0 + (x1-x0)*float32(k)/float32(g.Runes)
if g.RTL {
x = x1 - (x1-x0)*float32(k)/float32(g.Runes)
}
affinity, arrival := Downstream, 0
if k == 0 {
arrival = -1
}
if k == g.Runes {
affinity, arrival = Upstream, 1
}
if g.RTL {
arrival = -arrival
}
if affinity == Upstream && at >= line.Start && at <= line.End {
line.upstream[at-line.Start] = x
}
stops = append(stops, caretStop{CaretPosition{at, affinity}, x, arrival})
}
}
// Keep trimmed spaces and empty lines navigable too.
carets := line.lineCarets()
first, _ := slices.BinarySearch(l.boundaries, line.Start)
for k := first; k < len(l.boundaries) && l.boundaries[k] <= line.End; k++ {
at := l.boundaries[k]
if !slices.ContainsFunc(stops, func(s caretStop) bool { return s.position.Index == at }) {
stops = append(stops, caretStop{CaretPosition{at, Downstream}, carets[at-line.Start], 0})
}
}
if len(stops) == 0 {
stops = append(stops, caretStop{CaretPosition{line.Start, Downstream}, line.X, 0})
}
slices.SortStableFunc(stops, func(a, b caretStop) int {
if a.x < b.x {
return -1
}
if a.x > b.x {
return 1
}
return 0
})
return stops
}
+545
View File
@@ -0,0 +1,545 @@
//go:build js || android
package text
import (
"math"
"slices"
"unicode"
"github.com/go-text/typesetting/bidi"
"github.com/go-text/typesetting/segmenter"
)
// clusterEngine lays out text with a text stack that measures and draws
// text, rather than giving glyphs: a browser's canvas, Android's Paint.
// The engine's glyphs are grapheme clusters, measured within their words,
// which keeps the fonts' kerning, and drawn alone; a word of a script
// that joins or reorders its letters (Arabic, the scripts of India, …) is
// one glyph, drawn whole. go-text's segmenter finds the clusters and
// where lines may break, and its bidi package the direction of runs. The
// text stack's engine embeds it, and gives it its fonts and measures.
type clusterEngine struct {
shapeScratch
host clusterHost
// emoji are the twins of fonts that draw emoji, unshaded: emoji
// keep their colors whatever the text's.
emoji map[*Font]*Font
// glyphs are the texts of the glyphs of the Fonts made since the
// System last let go of them.
glyphs *glyphTexts
// words caches the pen positions of the clusters of words.
words map[wordKey][]float32
seg segmenter.Segmenter
para bidi.Paragraph
}
// clusterHost is the text stack of a clusterEngine.
type clusterHost interface {
// font returns the font of a style at its size.
font(style Style) *Font
// measure returns how wide text is in f, kerned unless noKern.
measure(f *Font, text string, noKern bool) float32
// pens returns the pen positions of the boundaries of the clusters
// of a word, bounds into text, from 0 at its start, as the stack lays
// the word out, or nil for the engine to measure them.
pens(f *Font, text []rune, bounds []int, noKern bool) []float32
}
// glyphTexts are the texts of glyphs, by ID: the engine's glyphs are
// texts drawn whole. A Font keeps the table of its time, so that a layout
// kept after the System let go of it still draws.
type glyphTexts struct {
ids map[string]uint32
texts []string
}
func newGlyphTexts() *glyphTexts {
return &glyphTexts{ids: map[string]uint32{"": 0}, texts: []string{""}}
}
type wordKey struct {
font *Font
word string
noKern bool
}
func (e *clusterEngine) init(host clusterHost) {
e.host = host
e.glyphs = newGlyphTexts()
e.words = map[wordKey][]float32{}
}
// forgetGlyphs lets go of the glyphs and the measurements, which Fonts
// that layouts keep still hold.
func (e *clusterEngine) forgetGlyphs() {
clear(e.emoji)
clear(e.words)
e.glyphs = newGlyphTexts()
}
// glyphID returns the ID of a glyph drawing text.
func (e *clusterEngine) glyphID(text string) uint32 {
g := e.glyphs
if id, ok := g.ids[text]; ok {
return id
}
id := uint32(len(g.texts))
g.texts = append(g.texts, text)
g.ids[text] = id
return id
}
// noKern reports whether a style's OpenType features turn kerning off,
// the one feature canvases have (fontKerning): the others they leave as
// the font has them.
func noKern(style Style) bool {
for _, f := range features(style.Features) {
if f.tag == [4]byte{'k', 'e', 'r', 'n'} {
return f.value == 0
}
}
return false
}
// cluster is a glyph being laid out: a grapheme cluster, or a word of a
// script whose letters join, of runes [start, end).
type cluster struct {
start, end int
font *Font
x, advance float32
level bidi.Level
text string
}
// complexScript reports whether a rune is of a script whose letters
// change with their neighbors, or reorder: its words are drawn whole.
func complexScript(r rune) bool {
return unicode.In(r, unicode.Arabic, unicode.Syriac, unicode.Nko, unicode.Mongolian, unicode.Devanagari,
unicode.Bengali, unicode.Gurmukhi, unicode.Gujarati, unicode.Oriya, unicode.Tamil, unicode.Telugu,
unicode.Kannada, unicode.Malayalam, unicode.Sinhala, unicode.Thai, unicode.Lao, unicode.Tibetan,
unicode.Myanmar, unicode.Khmer, unicode.Javanese, unicode.Balinese)
}
func (e *clusterEngine) shape(text []rune, style Style, spans []Span, width float32, rtl, wholeWords bool) []shapedLine {
if len(text) == 0 {
return nil
}
// The style of each rune: spans', then the text's.
styles := make([]Style, 0, len(spans)+1)
fontAt := make([]uint8, len(text))
{
start := 0
for _, sp := range spans {
end := min(sp.End, len(text))
if end <= start {
continue
}
for i := start; i < end; i++ {
fontAt[i] = uint8(len(styles))
}
styles = append(styles, sp.style(style))
start = end
if len(styles) == 255 {
break
}
}
for i := start; i < len(text); i++ {
fontAt[i] = uint8(len(styles))
}
styles = append(styles, style)
}
fonts := make([]*Font, len(styles))
for i, s := range styles {
fonts[i] = e.host.font(s)
}
// The direction of each rune.
levels := make([]bidi.Level, len(text))
mixed := rtl
for _, r := range text {
if r >= 0x0590 {
mixed = true
break
}
}
if mixed {
dir := bidi.LeftToRight
if rtl {
dir = bidi.RightToLeft
}
runs := e.para.Segment(text, dir)
for i := range runs.NumRuns() {
r := runs.Run(i)
for k := r.Start; k < min(r.End, len(text)); k++ {
levels[k] = r.Level
}
}
}
// Where lines may break, and the clusters between.
e.seg.Init(text)
var breaks []int
for it := e.seg.LineIterator(); it.Next(); {
l := it.Line()
breaks = append(breaks, l.Offset+len(l.Text))
}
if width > 0 && keepsAnyWords(style.Lang, spans) {
// Korean breaks between words (keepWordsWhole).
at := make([]bool, len(text)+1)
for _, b := range breaks {
at[b] = true
}
if keepWordsWhole(at, text, style.Lang, spans) {
breaks = breaks[:0]
for i, ok := range at {
if ok {
breaks = append(breaks, i)
}
}
}
}
var bounds []int
for it := e.seg.GraphemeIterator(); it.Next(); {
g := it.Grapheme()
bounds = append(bounds, g.Offset)
}
bounds = append(bounds, len(text))
// The clusters of each piece of text between breaks, of one style and
// direction, measured as a word.
var clusters []cluster
b := 0 // the cluster boundary
start := 0
for _, end := range breaks {
for start < end {
// The piece: same style, level and script complexity.
pe := start + 1
for pe < end && fontAt[pe] == fontAt[start] && levels[pe] == levels[start] {
pe++
}
// Whole clusters only.
for b < len(bounds)-1 && bounds[b] < start {
b++
}
ce := b
for ce < len(bounds)-1 && bounds[ce+1] <= pe {
ce++
}
if ce == b {
ce = b + 1
}
pe = bounds[ce]
st := styles[fontAt[start]]
f := fonts[fontAt[start]]
clusters = e.measureWord(clusters, text, bounds[b:ce+1], f, st.LetterSpacing, noKern(st), levels[start])
b, start = ce, pe
}
}
// Inline objects take their width, whatever the canvas measured of
// their character.
{
start := 0
for _, sp := range spans {
end := min(sp.End, len(text))
if sp.ObjectWidth > 0 {
for k := range clusters {
if c := &clusters[k]; c.start >= start && c.start < end {
c.advance = sp.ObjectWidth
}
}
}
start = max(start, end)
}
}
// Tabs advance to the next of the stops of the style, from the start
// of their line, where it sets them; the text stack measures them as
// spaces otherwise.
tabbed := style.tabStop > 0 && slices.Contains(text, '\t')
tabs := func(cs []cluster, x float32) {
for k := range cs {
if c := &cs[k]; c.end-c.start == 1 && text[c.start] == '\t' {
c.advance = tabAdvance(x, style.tabStop)
}
x += cs[k].advance
}
}
// Lines: whole pieces between breaks that fit, or clusters of those
// longer than a line unless wholeWords.
var lines [][2]int // clusters [i, j)
if width <= 0 {
if tabbed {
tabs(clusters, 0)
}
lines = append(lines, [2]int{0, len(clusters)})
} else {
lineStart, lineW := 0, float32(0)
ci := 0
for _, end := range breaks {
cj := ci
for cj < len(clusters) && clusters[cj].start < end {
cj++
}
// The piece's width, less the whitespace ending it.
measure := func() (w, trail float32) {
if tabbed {
tabs(clusters[ci:cj], lineW)
}
for k := ci; k < cj; k++ {
w += clusters[k].advance
}
for k := cj - 1; k >= ci && isSpace(text, clusters[k]); k-- {
trail += clusters[k].advance
}
return w, trail
}
w, trail := measure()
if lineW+w-trail > width+1e-3 && ci > lineStart {
lines = append(lines, [2]int{lineStart, ci})
lineStart, lineW = ci, 0
if tabbed {
w, trail = measure()
}
}
if w-trail > width+1e-3 && !wholeWords {
// Break the piece within itself.
for k := ci; k < cj; k++ {
a := clusters[k].advance
if lineW+a > width+1e-3 && k > lineStart && !isSpace(text, clusters[k]) {
lines = append(lines, [2]int{lineStart, k})
lineStart, lineW = k, 0
}
lineW += a
}
} else {
lineW += w
}
ci = cj
}
lines = append(lines, [2]int{lineStart, len(clusters)})
}
out := make([]shapedLine, 0, len(lines))
for _, ln := range lines {
cs := clusters[ln[0]:ln[1]]
if len(cs) == 0 {
continue
}
sl := shapedLine{start: cs[0].start, end: cs[len(cs)-1].end}
visual := reorder(cs, rtl)
x := float32(0)
for k := 0; k < len(visual); {
c := visual[k]
r := shapedRun{font: c.font, start: c.start, end: c.end}
for k < len(visual) && visual[k].font == c.font && visual[k].level%2 == c.level%2 {
v := visual[k]
r.start, r.end = min(r.start, v.start), max(r.end, v.end)
r.glyphs = append(r.glyphs, Glyph{Font: v.font, ID: e.glyphID(v.text), X: x, Advance: v.advance, Cluster: v.start, RTL: v.level%2 == 1})
x += v.advance
k++
}
sl.runs = append(sl.runs, r)
}
out = append(out, sl)
}
return out
}
// tabAdvance returns the advance of a tab x DIPs from the start of its
// line to the next stop of those every stop DIPs.
func tabAdvance(x, stop float32) float32 {
next := (float32(math.Floor(float64(x/stop+1e-4))) + 1) * stop
return next - x
}
func isSpace(text []rune, c cluster) bool {
return c.end-c.start == 1 && hangs(text[c.start])
}
// measureWord appends the clusters of a word of runes [bounds[0],
// bounds[len-1]) in f, at level, their boundaries bounds, positioned as
// the browser lays the word out. Clusters of scripts whose letters join
// make one, which the browser shapes whole.
func (e *clusterEngine) measureWord(out []cluster, text []rune, bounds []int, f *Font, spacing float32, noKern bool, level bidi.Level) []cluster {
for k := 0; k < len(bounds)-1; {
j := k + 1
joins := complexScript(text[bounds[k]])
for j < len(bounds)-1 && complexScript(text[bounds[j]]) == joins {
j++
}
if joins {
word := string(text[bounds[k]:bounds[j]])
w := e.host.measure(f, word, noKern)
out = append(out, cluster{start: bounds[k], end: bounds[j], font: f, advance: w + spacing*float32(j-k), level: level, text: word})
} else {
out = e.measureClusters(out, text, bounds[k:j+1], f, spacing, noKern, level)
}
k = j
}
return out
}
// measureClusters appends clusters of runes [bounds[0], bounds[len-1]),
// each drawn alone, at the positions the browser gives them in the whole.
func (e *clusterEngine) measureClusters(out []cluster, text []rune, bounds []int, f *Font, spacing float32, noKern bool, level bidi.Level) []cluster {
start, end := bounds[0], bounds[len(bounds)-1]
key := wordKey{f, string(text[start:end]), noKern}
pens, ok := e.words[key]
if !ok {
pens = e.host.pens(f, text[start:end], rebase(bounds, start), noKern)
}
if !ok && pens == nil {
pens = make([]float32, len(bounds))
if len(bounds) > 33 {
// Long words: each cluster alone.
for k := 1; k < len(bounds); k++ {
pens[k] = pens[k-1] + e.host.measure(f, string(text[bounds[k-1]:bounds[k]]), noKern)
}
} else {
// A cluster ends where the text through it ends, and starts
// its own width before: kerning with the cluster before it
// moves it, as the browser draws the word, not the next one.
n := len(bounds) - 1
pens[n] = e.host.measure(f, string(text[start:end]), noKern)
for k := 1; k < n; k++ {
through := e.host.measure(f, string(text[start:bounds[k+1]]), noKern)
alone := e.host.measure(f, string(text[bounds[k]:bounds[k+1]]), noKern)
pens[k] = max(through-alone, pens[k-1])
}
}
}
if !ok {
if len(e.words) > 1<<14 {
clear(e.words)
}
e.words[key] = pens
}
for k := 1; k < len(bounds); k++ {
c := cluster{
start: bounds[k-1], end: bounds[k], font: f,
advance: max(pens[k]-pens[k-1], 0) + spacing, level: level,
text: string(text[bounds[k-1]:bounds[k]]),
}
if isEmoji(text[bounds[k-1]:bounds[k]]) {
c.font = e.emojiFont(f)
}
out = append(out, c)
}
return out
}
// isEmoji reports whether a cluster is an emoji: a pictograph, a flag, or
// a character with the emoji presentation selector.
func isEmoji(cluster []rune) bool {
r := cluster[0]
if r >= 0x1F000 && r <= 0x1FAFF || r >= 0x2600 && r <= 0x27BF {
return true
}
for _, r := range cluster[1:] {
if r == 0xFE0F {
return true
}
}
return false
}
// emojiFont returns f's twin for emoji.
func (e *clusterEngine) emojiFont(f *Font) *Font {
if t, ok := e.emoji[f]; ok {
return t
}
if e.emoji == nil {
e.emoji = map[*Font]*Font{}
}
t := *f
t.shaded, t.thickens = false, false
e.emoji[f] = &t
return &t
}
// reorder returns the clusters of a line in visual order (UAX #9's L2):
// from the highest level down to the lowest odd one, runs at that level or
// higher reverse.
func reorder(cs []cluster, rtl bool) []cluster {
var hi bidi.Level
lo := bidi.Level(127)
for _, c := range cs {
hi = max(hi, c.level)
if c.level%2 == 1 {
lo = min(lo, c.level)
}
}
if hi == 0 {
return cs
}
v := append([]cluster(nil), cs...)
// Whitespace ending the line takes the paragraph's level (L1).
base := bidi.Level(0)
if rtl {
base = 1
}
for k := len(v) - 1; k >= 0 && v[k].end-v[k].start == 1 && v[k].text == " "; k-- {
v[k].level = base
}
for l := hi; l >= lo && l > 0; l-- {
for i := 0; i < len(v); {
if v[i].level < l {
i++
continue
}
j := i
for j < len(v) && v[j].level >= l {
j++
}
for a, b := i, j-1; a < b; a, b = a+1, b-1 {
v[a], v[b] = v[b], v[a]
}
i = j
}
}
return v
}
// positions are a quarter of a pixel apart, the nearest to the pen, as
// Skia, which draws the text of Chrome's canvases, places glyphs.
func (e *clusterEngine) positions(*Font, float32, bool) (int, bool) { return 4, true }
func (e *clusterEngine) baseline(y float32) float32 { return float32(math.Round(float64(y))) }
// join: browsers' canvases blend each glyph of a run in turn (Skia).
func (e *clusterEngine) join() bool { return false }
// decorate places underlines and strikethroughs along the advances of the
// runs, at the positions of their fonts, whole pixels from the baseline.
func (e *clusterEngine) decorate(r decoRange) []Stroke {
s := r.scale
base := e.baseline(r.baseline() * s)
var out []Stroke
r.runs(func(f *Font, i, j int) {
x0, x1 := r.span(i, j)
top, thick := f.strikeTop, f.strikeThick
if r.d == Underline {
top, thick = f.underlineTop, f.underlineThick
}
t := float32(math.Round(float64(base - top*s)))
st := Stroke{X0: (r.x + x0) * s, X1: (r.x + x1) * s, Top: t, Bottom: t + max(float32(math.Round(float64(thick*s))), 1)}
if n := len(out); n > 0 && out[n-1].Top == st.Top && out[n-1].Bottom == st.Bottom {
out[n-1].X1 = max(out[n-1].X1, st.X1)
return
}
out = append(out, st)
})
return out
}
// rebase returns bounds less start.
func rebase(bounds []int, start int) []int {
out := make([]int, len(bounds))
for i, b := range bounds {
out[i] = b - start
}
return out
}
File diff suppressed because it is too large. Load diff
+558
View File
@@ -0,0 +1,558 @@
//go:build darwin && !ios
package text
import (
"bytes"
"math"
"math/rand/v2"
"os"
"slices"
"strconv"
"strings"
"testing"
)
func TestCoreTextSyntheticItalic(t *testing.T) {
for _, tc := range []struct{ family, text string }{
{"PingFang SC", "口中文斜体"}, {"system-ui", "口中文斜体"}, {"Helvetica, PingFang SC", "口中文斜体"}, {"PingFang SC", "gy"},
} {
t.Run(tc.family+tc.text, func(t *testing.T) {
s := newSystem()
e := s.engine().(*coreText)
style := Style{Family: tc.family, Size: 64}
plain := s.Layout(Params{Text: tc.text, Style: style})
style.Italic = true
italic := s.Layout(Params{Text: tc.text, Style: style})
if len(plain.Lines[0].Glyphs) != len(italic.Lines[0].Glyphs) {
t.Fatal("italic changed glyph count")
}
for i, g := range italic.Lines[0].Glyphs {
p := plain.Lines[0].Glyphs[i]
if p.Font == g.Font || ct.fontGetMatrix(g.Font.native).c != obliqueSkew {
t.Fatalf("glyph %d did not get a separate synthetic font", i)
}
if tc.text == "gy" {
id := uint16(g.ID)
var bounds cgRect
ct.fontGetBoundingRects(g.Font.native, ctFontOrientationDefault, &id, &bounds, 1)
if bounds.y >= 0 {
t.Fatal("descender case has no negative-y ink")
}
}
a := e.glyph(p.Font, p.ID, 2, 0, Flat, false)
b := e.glyph(g.Font, g.ID, 2, 0, Flat, false)
if bytes.Equal(a.pix, b.pix) {
t.Fatal("upright and italic pixels are identical")
}
for y := range b.h {
for x := range b.w {
if (x == 0 || x == b.w-1 || y == 0 || y == b.h-1) && b.pix[y*b.w+x] != 0 {
t.Fatal("synthetic ink touches bitmap boundary")
}
}
}
// Exercise the atlas cache in both orders as well, small enough
// for every glyph to fit the test system's 256×256 atlas.
pi := s.Glyph(p.Font, p.ID, 0.5, 0, Flat, false)
ii := s.Glyph(g.Font, g.ID, 0.5, 0, Flat, false)
if !pi.OK || !ii.OK || (pi.X == ii.X && pi.Y == ii.Y) {
t.Fatalf("upright and italic share an atlas entry: %+v %+v", pi, ii)
}
if again := s.Glyph(p.Font, p.ID, 0.5, 0, Flat, false); again != pi {
t.Fatal("italic replaced upright cache entry")
}
if i == 0 && tc.text != "gy" {
// 口 has matching vertical sides, so compare their
// centroids near the top and bottom of the ink.
top, bottom := inkCentroid(b, 0.2), inkCentroid(b, 0.8)
if math.IsNaN(top) || math.IsNaN(bottom) || top-bottom < 10 {
t.Fatalf("glyph top is not tilted right: top %v bottom %v", top, bottom)
}
}
}
})
}
}
func inkCentroid(b bitmap, fraction float64) float64 {
lo, hi := b.h, 0
for y := range b.h {
for x := range b.w {
if b.pix[y*b.w+x] > 128 {
lo, hi = min(lo, y), max(hi, y)
}
}
}
y := lo + int(float64(hi-lo)*fraction)
var sum, weight float64
for x := range b.w {
v := float64(b.pix[y*b.w+x])
sum += float64(x+b.left) * v
weight += v
}
if weight == 0 {
return math.NaN()
}
return sum / weight
}
func TestCoreTextTrueItalic(t *testing.T) {
s := newSystem()
l := s.Layout(Params{Text: "italic", Style: Style{Family: "system-ui", Size: 48, Italic: true}})
identity := cgAffineTransform{a: 1, d: 1}
for _, g := range l.Lines[0].Glyphs {
if ct.fontGetSymbolicTraits(g.Font.native)&ctFontItalicTrait == 0 {
t.Fatal("system Latin italic did not select a true italic face")
}
if m := ct.fontGetMatrix(g.Font.native); m != identity {
t.Fatalf("true italic was transformed: %+v", m)
}
}
}
func TestCoreTextItalicFallbackSpans(t *testing.T) {
s := newSystem()
// In PingFang SC, both spans are in one font, which Core Text would
// shape as one run.
for _, family := range []string{"Helvetica", "PingFang SC"} {
for _, text := range []string{"中文中文", "😀文中文"} {
l := s.Layout(Params{Text: text, Style: Style{Family: family, Size: 32},
Spans: EncodeSpans([]Span{{End: 2}, {End: 4, Italic: true}})})
for _, g := range l.Lines[0].Glyphs {
want := float64(0)
if g.Cluster >= 2 {
want = obliqueSkew
}
if got := ct.fontGetMatrix(g.Font.native).c; got != want {
t.Fatalf("%s %q cluster %d: skew %v, want %v", family, text, g.Cluster, got, want)
}
}
}
}
}
// Core Text draws color glyphs upright whatever the font's matrix, so
// emoji in italic text keep the upright font, as in WebKit.
func TestCoreTextItalicColorGlyphs(t *testing.T) {
s := newSystem()
for _, family := range []string{"PingFang SC", "Helvetica"} {
l := s.Layout(Params{Text: "中😀", Style: Style{Family: family, Size: 32, Italic: true}})
for _, g := range l.Lines[0].Glyphs {
want := obliqueSkew
if g.Cluster == 1 {
want = 0
}
if got := ct.fontGetMatrix(g.Font.native).c; got != want {
t.Fatalf("%s cluster %d: skew %v, want %v", family, g.Cluster, got, want)
}
}
}
}
// TestCoreTextLanguage holds the glyphs of Han characters to the language
// of the text: 直 and 骨 are drawn apart in Japanese and in Chinese, by
// the fonts Core Text falls back to and by a font's own forms for the
// language. A language that writes no Han characters leaves them as text
// without a language has them, and Latin letters keep their glyphs.
func TestCoreTextLanguage(t *testing.T) {
s := newSystem()
ids := func(family, lang string, spans []Span) []uint32 {
l := s.Layout(Params{Text: "直骨 Ag", Style: Style{Family: family, Size: 32, Lang: lang}, Spans: EncodeSpans(spans)})
var out []uint32
for _, g := range l.Lines[0].Glyphs {
out = append(out, g.ID)
}
return out
}
for _, family := range []string{"system-ui", "Helvetica"} {
none, en, ja, hans := ids(family, "", nil), ids(family, "en", nil), ids(family, "ja", nil), ids(family, "zh-Hans", nil)
if !slices.Equal(none, en) {
t.Errorf("%s: English %v, without a language %v", family, en, none)
}
if slices.Equal(ja[:2], hans[:2]) {
t.Errorf("%s: Japanese and Chinese Han glyphs are the same: %v", family, ja)
}
if !slices.Equal(ja[2:], hans[2:]) || !slices.Equal(ja[2:], none[2:]) {
t.Errorf("%s: Latin glyphs changed with the language: %v %v %v", family, none, ja, hans)
}
// A span in Japanese in a Chinese text, and the other way round.
if got := ids(family, "zh-Hans", []Span{{End: 2, Lang: "ja"}}); !slices.Equal(got, ja) {
t.Errorf("%s: a Japanese span in Chinese text: %v, want %v", family, got, ja)
}
if got := ids(family, "ja", []Span{{End: 1}, {End: 2, Lang: "zh-Hans"}}); got[0] != ja[0] || got[1] != hans[1] {
t.Errorf("%s: a Chinese span in Japanese text: %v", family, got)
}
}
// The system's language for text without one.
s.SetLanguage("ja")
if got := ids("system-ui", "", nil); !slices.Equal(got, ids("system-ui", "ja", nil)) {
t.Errorf("text without a language in a Japanese system: %v", got)
}
}
// TestCoreTextLanguageSpacing checks that the room Core Text leaves
// between Han and Latin letters in Chinese and Japanese text counts in the
// width of a line, so that text laid out as wide as it measured stays on
// one line.
func TestCoreTextLanguageSpacing(t *testing.T) {
s := newSystem()
for _, lang := range []string{"", "zh-Hans", "ja"} {
p := Params{Text: "2026年1月5日星期一", Style: Style{Size: 13, Lang: lang}}
l := s.Layout(p)
gs := l.Lines[0].Glyphs
last := gs[len(gs)-1]
if end := last.X + last.Advance - gs[0].X; end > l.Width+1e-3 {
t.Errorf("%q: the pen ends at %v, past the line's width %v", lang, end, l.Width)
}
p.Width = l.Width
if n := len(s.Layout(p).Lines); n != 1 {
t.Errorf("%q: laid out as wide as it measured, the text takes %d lines", lang, n)
}
}
}
// A text wrapped again at another width takes its typesetter from before,
// and lays out as the same text does when shaped anew, in every script and
// direction and with what a style gives its attributes.
func TestCoreTextKeptTypesetter(t *testing.T) {
texts := []string{
"The quick brown fox jumps over the lazy dog, and then some more words follow to wrap the paragraph.",
"你好世界,这段中文会换行。The fonts fall back within a line 日本語のテキストも含む。",
"مرحبا بالعالم، هذا نص طويل يلتف على عدة أسطر من اليمين إلى اليسار في الفقرة",
"Emoji 😀🎉👩‍👩‍👧‍👦 and a verylongwordthatdoesnotfitalineandmustbreakorhang somewhere",
}
styles := []Style{{Size: 14}, {Size: 14, Italic: true}, {Size: 14, Weight: 700}, {Size: 14, LetterSpacing: 2}, {Size: 14, Features: "kern=0"}, {Size: 14, Lang: "ja"}}
widths := []float32{300, 120, 450, 120, 77}
kept := newSystem()
for _, text := range texts {
for _, style := range styles {
for _, width := range widths {
p := Params{Text: text, Width: width, Style: style}
// Without the layouts' cache, which would answer the second
// time a width comes.
kept.mu.Lock()
got := &kept.layout(p).layout
kept.mu.Unlock()
fresh := newSystem()
fresh.mu.Lock()
want := &fresh.layout(p).layout
fresh.mu.Unlock()
if len(got.Lines) != len(want.Lines) || got.Width != want.Width || got.Height != want.Height {
t.Fatalf("%q in %+v at %v: %d lines, %v×%v, shaped anew %d lines, %v×%v", text, style, width, len(got.Lines), got.Width, got.Height, len(want.Lines), want.Width, want.Height)
}
for i := range got.Lines {
a, b := got.Lines[i].Glyphs, want.Lines[i].Glyphs
if len(a) != len(b) {
t.Fatalf("%q in %+v at %v: line %d has %d glyphs, shaped anew %d", text, style, width, i, len(a), len(b))
}
for k := range a {
if a[k].ID != b[k].ID || a[k].X != b[k].X || a[k].Y != b[k].Y || a[k].Advance != b[k].Advance || a[k].Cluster != b[k].Cluster {
t.Fatalf("%q in %+v at %v: line %d glyph %d is %+v, shaped anew %+v", text, style, width, i, k, a[k], b[k])
}
}
}
}
}
}
e := kept.engine().(*coreText)
// The first text is all ASCII: in Japanese, it shapes as in no language.
if want := len(texts)*len(styles) - 1; len(e.typesetters) != want {
t.Errorf("%d typesetters kept, want one for each of the %d shapings", len(e.typesetters), want)
}
}
// Typesetters go once their text stopped wrapping again, and all of them as
// windows go idle, and what does not wrap keeps none.
func TestCoreTextTypesettersGo(t *testing.T) {
s := newSystem()
e := s.engine().(*coreText)
wrapped := Params{Text: "A paragraph that wraps", Width: 60, Style: Style{Size: 14}}
s.Layout(wrapped)
s.Layout(Params{Text: "A label on one line", Style: Style{Size: 14}})
if len(e.typesetters) != 1 {
t.Fatalf("%d typesetters kept, want that of the text that wraps", len(e.typesetters))
}
for range keptTypesetterFrames {
s.EndFrame()
}
if len(e.typesetters) != 1 {
t.Fatalf("gone after %d frames, which another window's may be", keptTypesetterFrames)
}
s.EndFrame()
if len(e.typesetters) != 0 {
t.Fatalf("%d typesetters kept after their text stopped wrapping", len(e.typesetters))
}
s.Layout(Params{Text: wrapped.Text, Width: 70, Style: wrapped.Style})
s.ReleaseShaping()
if len(e.typesetters) != 0 {
t.Fatalf("%d typesetters kept once idle", len(e.typesetters))
}
}
// Text whose language the engine is not told, for it changes nothing
// (languageShapes), lays out as it does when the engine is told, in the fonts
// of the system, so that leaving it out costs no one a glyph or a line break.
func TestCoreTextLanguageLeftOut(t *testing.T) {
cases := []struct {
text string
langs []string
}{
{"The quick brown fox -- jumps/over the lazy dog's back, e.g. at 10:30 (or 22:30); fi fl ffi 1,234.50 well-known \"quotes\" and a verylongwordthatoverflowsitsline.", []string{"en", "en-GB", "zh-Hans", "zh-Hant", "ja", "ko", "de", "fr", "ru", "ar", "fi", "sv"}},
{"Über die Straße, déjà vu à la crème: señor, naïve, fjörd, Ærø, garçon, ¿qué? ¡sí! 50 % × 2 ÷ 4 ± 1 °C", []string{"en", "de", "fr", "es", "pt", "it", "sv", "fi", "da", "nb"}},
}
for _, c := range cases {
text := []rune(c.text)
for _, lang := range c.langs {
if languageShapes(text, lang) {
t.Errorf("%q in %s tells the engine", c.text, lang)
continue
}
for _, width := range []float32{0, 90, 233, 400} {
told := shapedWithLanguage(t, text, lang, width)
s := newSystem()
s.mu.Lock()
left := s.engine().shape(text, Style{Size: 14, Lang: lang}, nil, width, false, false)
if !sameShape(told, left) {
t.Errorf("%q in %s at %v shapes apart from when the engine is told", c.text, lang, width)
}
s.mu.Unlock()
}
}
}
for text, lang := range map[string]string{"直骨": "ja", "“quoted”": "zh-Hans", "kind fi": "tr", "ijs": "nl", "Привет": "ru", "شكرا": "ar"} {
if !languageShapes([]rune(text), lang) {
t.Errorf("%q in %s does not tell the engine", text, lang)
}
}
}
// shapedWithLanguage shapes text with the language in its attributes, as
// shape does for a text whose language changes it.
func shapedWithLanguage(t *testing.T, text []rune, lang string, width float32) []shapedLine {
t.Helper()
s := newSystem()
s.mu.Lock()
defer s.mu.Unlock()
e := s.engine().(*coreText)
style := Style{Size: 14, Lang: lang}
font := e.ctFont(style)
e.u16, e.index = appendUTF16(e.u16[:0], e.index[:0], text)
u16, index := e.u16, e.index
typesetter := e.newTypesetter(font, u16, text, style, nil, false, lang)
if typesetter == 0 {
t.Fatal("no typesetter")
}
defer ct.release(typesetter)
var out []shapedLine
n := len(u16)
for start := 0; start < n; {
count := n - start
if width > 0 {
count = max(ct.suggestLineBreak(typesetter, start, float64(width)+1.0/1024), 1)
}
line := ct.typesetterCreateLine(typesetter, cfRange{start, count})
out = append(out, cloneLine(e.line(line, index, n, false)))
ct.release(line)
start += count
}
return out
}
// cloneLine copies a line out of the engine's scratch.
func cloneLine(l shapedLine) shapedLine {
l.runs = slices.Clone(l.runs)
for i := range l.runs {
l.runs[i].glyphs = slices.Clone(l.runs[i].glyphs)
}
return l
}
func sameShape(a, b []shapedLine) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i].start != b[i].start || a[i].end != b[i].end || len(a[i].runs) != len(b[i].runs) {
return false
}
for j := range a[i].runs {
x, y := a[i].runs[j].glyphs, b[i].runs[j].glyphs
if len(x) != len(y) {
return false
}
for k := range x {
if x[k].ID != y[k].ID || x[k].X != y[k].X || x[k].Y != y[k].Y || x[k].Advance != y[k].Advance || x[k].Cluster != y[k].Cluster || x[k].Font.Ascent != y[k].Font.Ascent {
return false
}
}
}
}
return true
}
// A number put together glyph by glyph is what Core Text shapes, in every
// font and style, whatever the kerning between its characters, as each of
// them is checked here rather than only the first of a font.
func TestCoreTextNumbers(t *testing.T) {
numbers := []string{"0", "7", "11", "1,234,567.89", "-42.5%", "+3.14", "$1,000", "1.1.1.1", "$-0.50", "%%", "--", "..", "1+1-1", "00000000000000000000000000000000", "12.345", "98765.4321"}
styles := []Style{{Size: 11}, {Size: 13}, {Size: 13, Weight: 700}, {Size: 14, Italic: true}, {Size: 14, Family: "Menlo"}, {Size: 16, Family: "Helvetica Neue"}, {Size: 15, Family: "Georgia"}, {Size: 13, Lang: "zh-Hans"}, {Size: 13, Lang: "en"}}
s := newSystem()
s.mu.Lock()
defer s.mu.Unlock()
e := s.engine().(*coreText)
for _, style := range styles {
for _, number := range numbers {
text := []rune(number)
e.resetScratch()
lines := e.shapeNumber(text, style, nil, 0, false)
if lines == nil {
t.Fatalf("%q in %+v was not put together", number, style)
}
if !sameNumber(lines, e.shapeText(text, style, nil, 0, false, false)) {
t.Errorf("%q in %+v put together is not what Core Text shapes", number, style)
}
}
}
for _, f := range e.numbers {
if f.disagreed {
t.Error("a font disagreed with Core Text")
}
}
}
// What is not a number, wraps, or takes more than its characters' glyphs is
// left to Core Text, and a font it disagrees with stays with it.
func TestCoreTextNumbersLeftOut(t *testing.T) {
s := newSystem()
s.mu.Lock()
defer s.mu.Unlock()
e := s.engine().(*coreText)
style := Style{Size: 13}
for _, c := range []struct {
text string
style Style
spans []Span
width float32
rtl bool
}{
{text: "12a", style: style},
{text: "12:30", style: style},
{text: "١٢٣", style: style},
{text: "123", style: style, rtl: true},
{text: "123", style: style, spans: []Span{{End: 1, Weight: 700}}},
{text: "123", style: Style{Size: 13, LetterSpacing: 1}},
{text: "123", style: Style{Size: 13, Features: "tnum"}},
{text: "123", style: Style{Size: 13, Lang: "tr"}},
{text: "123456", style: style, width: 5},
{text: strings.Repeat("1", maxNumber+1), style: style},
} {
e.resetScratch()
if e.shapeNumber([]rune(c.text), c.style, c.spans, c.width, c.rtl) != nil {
t.Errorf("%q in %+v (width %v, RTL %v) was put together", c.text, c.style, c.width, c.rtl)
}
}
text := []rune("42")
e.resetScratch()
want := e.shapeText(text, style, nil, 0, false, false)
wantX := want[0].runs[0].glyphs[1].X
if e.shapeNumber(text, style, nil, 0, false) == nil {
t.Fatal("42 was not put together")
}
f := e.numbers[numberKey{e.ctFont(style), false}]
f.pairs[numberSlots['4']-1][numberSlots['2']-1].advance += 5
e.resetScratch()
got := e.shapeNumber(text, style, nil, 0, false)
if !f.disagreed {
t.Error("a number wrong by 5 did not count as a disagreement")
}
if x := got[0].runs[0].glyphs[1].X; x != wantX {
t.Errorf("the second digit of a number that disagrees is at %v, Core Text puts it at %v", x, wantX)
}
e.resetScratch()
if e.shapeNumber(text, style, nil, 0, false) != nil {
t.Error("a font that disagreed still has numbers put together")
}
}
// Latin text wrapped from one line is what Core Text wraps, for any text made
// of what wrapping takes, at any width, in a font's first checks and beyond.
func TestCoreTextWrapFuzz(t *testing.T) {
iterations := 400
if n, err := strconv.Atoi(os.Getenv("MYGO_WRAP_FUZZ")); err == nil {
iterations = n
}
words := []string{"a", "I", "to", "the", "window", "layout", "AVATAR", "Type", "fi", "ffl", "office", "don't", "well-known", "e.g.", "U.S.A.", "1,234.56", "3.14", "$5", "50%", "a/b", "http://example.com/path?q=1&r=2", "(paren)", "[box]", "{curly}", "\"quoted\"", "'single'", "end.", "yes,", "stop;", "wait:", "what?", "no!", "x+y", "a=b", "#tag", "@me", "under_score", "<tag>", "~", "*star*", "pipe|", "back\\slash", "café", "Über", "señor", "naïve", "Ærø", "garçon", "verylongwordthatdoesnotfitalineandhastobrokenbycoretext", "--", "-", "...", "A-1", "1-2", "T.", "V,", "Y.", "L'", "f)", "ß"}
seps := []string{" ", " ", " ", " ", " ", " ", "", "-", "/"}
styles := []Style{{Size: 13}, {Size: 14, Weight: 700}, {Size: 13, Italic: true}, {Size: 15, Family: "Georgia"}, {Size: 12, Family: "Helvetica Neue"}, {Size: 13, Family: "Menlo"}, {Size: 16, Family: "Times New Roman"}}
rng := rand.New(rand.NewPCG(1, 2))
s := newSystem()
s.mu.Lock()
defer s.mu.Unlock()
e := s.engine().(*coreText)
wrapped, leftOut := 0, 0
defer func() { t.Logf("%d wrappings compared, %d left to Core Text", wrapped, leftOut) }()
for it := range iterations {
var b strings.Builder
for range 1 + rng.IntN(80) {
b.WriteString(words[rng.IntN(len(words))])
b.WriteString(seps[rng.IntN(len(seps))])
}
text := []rune(b.String())
style := styles[it%len(styles)]
e.resetScratch()
font := e.ctFont(style)
e.u16, e.index = appendUTF16(e.u16[:0], e.index[:0], text)
typesetter := e.newTypesetter(font, e.u16, text, style, nil, false, "")
kept := &keptTypesetter{typesetter: typesetter, font: font}
for _, width := range []float32{float32(20 + rng.IntN(100)), float32(100 + rng.IntN(400)), float32(300+rng.IntN(500)) + rng.Float32()} {
e.resetScratch()
// Every wrapping checked by the test, not only some.
f := e.wrapFonts[font]
if f != nil {
f.checked = wrapCheckedFirst
f.lines = 1
}
got := e.wrapKept(kept, text, style, width)
if got == nil {
// What does not shape as a glyph for each rune stays with
// Core Text.
leftOut++
continue
}
wrapped++
e.u16, e.index = appendUTF16(e.u16[:0], e.index[:0], text)
want := e.typesetLines(typesetter, len(e.u16), width, nil, false, false, e.index, style.Italic)
if !sameLines(got, want) {
report(t, text, style, width, got, want)
return
}
}
ct.release(typesetter)
}
}
// report tells the first line where wrapped text differs from Core Text's.
func report(t *testing.T, text []rune, style Style, width float32, got, want []shapedLine) {
t.Helper()
for i := range min(len(got), len(want)) {
if got[i].start != want[i].start || got[i].end != want[i].end {
t.Fatalf("in %+v at %v, line %d is %q, Core Text's %q", style, width, i, string(text[got[i].start:got[i].end]), string(text[want[i].start:want[i].end]))
}
if !sameLines(got[i:i+1], want[i:i+1]) {
x, y := got[i].runs, want[i].runs
t.Errorf("in %+v at %v, line %d %q has %d runs, Core Text's %d", style, width, i, string(text[got[i].start:got[i].end]), len(x), len(y))
if len(x) == 1 && len(y) == 1 {
for k := range min(len(x[0].glyphs), len(y[0].glyphs)) {
g, h := x[0].glyphs[k], y[0].glyphs[k]
if g.ID != h.ID || g.X != h.X || g.Advance != h.Advance {
t.Errorf(" glyph %d (%q): id %d/%d x %v/%v advance %v/%v", k, string(text[g.Cluster]), g.ID, h.ID, g.X, h.X, g.Advance, h.Advance)
}
}
}
t.FailNow()
}
}
t.Fatalf("in %+v at %v, %d lines, Core Text's %d", style, width, len(got), len(want))
}
+217
View File
@@ -0,0 +1,217 @@
package text
import (
"math"
"slices"
"unicode"
)
// Decoration is a line drawn along text.
type Decoration uint8
const (
Underline Decoration = iota
Strikethrough
// SolidUnderline is an Underline drawn through descenders, as links
// mark hover, instead of skipping the ink of glyphs as Core Text does.
SolidUnderline
)
// LineStyle is how a decoration's line is drawn where the font leaves it
// otherwise.
type LineStyle struct {
// Thick, if positive, is the line's thickness in DIPs, around its
// middle, rounded to whole pixels (at least one) and on whole pixels,
// so that it is as sharp as browsers draw text-decoration-thickness.
Thick float32
// Offset, if HasOffset, puts the top of an underline Offset DIPs below
// the baseline, or above it if negative, rounded to whole pixels, as
// CSS's text-underline-offset does: an underline skipping ink skips
// the glyphs where it is then. Strikethroughs stay where they are.
Offset float32
HasOffset bool
}
// A Stroke is a stretch of a decoration's line, in device pixels: from X0
// to X1 and from Top to Bottom, which renderers antialias where they fall
// within pixels.
type Stroke struct{ X0, X1, Top, Bottom float32 }
// decoRange is what an engine decorates: glyphs [i, j) of a line of a
// layout whose origin is at (x, y) DIPs, runes of one style whose font is
// font, shift DIPs above the line's baseline (Span.BaselineShift), at
// scale pixels per DIP, with decoration d.
type decoRange struct {
l *Layout
line *Line
i, j int
font *Font
x, y float32
shift float32
scale float32
d Decoration
// solid keeps an underline whole, through the ink of glyphs.
solid bool
// offset, if hasOffset, is how far below the baseline the top of an
// underline is, in DIPs (LineStyle.Offset).
offset float32
hasOffset bool
}
// Decorate returns the strokes the system's text stack draws for
// decoration d of glyphs [i, j) of line li of l, runes of one style, with
// the layout's origin at (x, y) DIPs, at scale pixels per DIP: placed as
// AppKit, Direct2D or GTK place underlines and strikethroughs, with their
// thickness, but for what ls sets.
func (s *System) Decorate(l *Layout, li, i, j int, x, y, scale float32, d Decoration, ls LineStyle) []Stroke {
s.mu.Lock()
defer s.mu.Unlock()
solid := d == SolidUnderline
if solid {
d = Underline
}
if l == nil || li < 0 || li >= len(l.Lines) {
return nil
}
line := &l.Lines[li]
i, j = max(i, 0), min(j, len(line.Glyphs))
if i >= j {
return nil
}
style := l.Params.Style
var shift float32
if l.Params.Spans != "" {
r := line.Glyphs[i].Cluster
for _, sp := range DecodeSpans(l.Params.Spans) {
if r < sp.End {
style, shift = sp.style(style), sp.BaselineShift
break
}
}
}
f := s.font(style)
if f == nil {
return nil
}
r := decoRange{l: l, line: line, i: i, j: j, font: f, x: x, y: y, shift: shift, scale: scale, d: d, solid: solid,
offset: ls.Offset, hasOffset: ls.HasOffset && d == Underline}
strokes := s.engine().decorate(r)
if ls.Thick > 0 {
h := max(float32(math.Round(float64(ls.Thick*scale))), 1)
for k := range strokes {
st := &strokes[k]
st.Top = float32(math.Round(float64(st.Top+st.Bottom-h) / 2))
st.Bottom = st.Top + h
}
}
if r.hasOffset {
// From the baseline the engine draws the glyphs on, a whole pixel.
top := s.engine().baseline(r.baseline()*scale) + float32(math.Round(float64(ls.Offset*scale)))
for k := range strokes {
st := &strokes[k]
st.Top, st.Bottom = top, top+st.Bottom-st.Top
}
}
return strokes
}
// runs calls fn for each run of glyphs of one font among [i, j).
func (r *decoRange) runs(fn func(f *Font, i, j int)) {
gs := r.line.Glyphs
for i := r.i; i < r.j; {
j := i + 1
for j < r.j && gs[j].Font == gs[i].Font {
j++
}
if gs[i].Font != nil {
fn(gs[i].Font, i, j)
}
i = j
}
}
// span returns the left and right of the advances of glyphs [i, j), in
// DIPs from the layout's origin.
func (r *decoRange) span(i, j int) (x0, x1 float32) {
x0, x1 = float32(math.MaxFloat32), float32(-math.MaxFloat32)
for _, g := range r.line.Glyphs[i:j] {
x0, x1 = min(x0, g.X), max(x1, g.X+g.Advance)
}
return x0, x1
}
// rune returns the rune glyph k starts, or 0.
func (r *decoRange) rune(k int) rune {
if c := r.line.Glyphs[k].Cluster; c >= 0 && c < len(r.l.Runes) {
return r.l.Runes[c]
}
return 0
}
// baseline returns the baseline of the range's glyphs, in DIPs from the
// top, as laid out: the line's, unless their span shifts them.
func (r *decoRange) baseline() float32 { return r.y + r.line.Baseline - r.shift }
// cut returns [x0, x1] less the intervals of cuts, leaving out pieces no
// longer than min.
func cut(x0, x1 float32, cuts [][2]float32, minLen float32) [][2]float32 {
slices.SortFunc(cuts, func(a, b [2]float32) int {
switch {
case a[0] < b[0]:
return -1
case a[0] > b[0]:
return 1
}
return 0
})
var out [][2]float32
at := x0
for _, c := range cuts {
if c[0] > at {
if end := min(c[0], x1); end-at > minLen {
out = append(out, [2]float32{at, end})
}
}
at = max(at, c[1])
if at >= x1 {
break
}
}
if x1-at > minLen {
out = append(out, [2]float32{at, x1})
}
return out
}
// skipsInk reports whether a rune's glyph cuts the underlines skipping
// ink: Han, Kana and Hangul do not, as in AppKit.
func skipsInk(r rune) bool {
return !unicode.IsSpace(r) && !unicode.In(r, unicode.Han, unicode.Hiragana, unicode.Katakana, unicode.Hangul)
}
// bandX returns the left and right of the parts of segments (x0, y0, x1,
// y1 each) within lo ≤ y ≤ hi.
func bandX(segments [][4]float64, lo, hi float64) (a, b float64, ok bool) {
a, b = math.Inf(1), math.Inf(-1)
for _, s := range segments {
px, py, qx, qy := s[0], s[1], s[2], s[3]
t0, t1 := 0.0, 1.0
if dy := qy - py; dy == 0 {
if py < lo || py > hi {
continue
}
} else {
ta, tb := (lo-py)/dy, (hi-py)/dy
if ta > tb {
ta, tb = tb, ta
}
t0, t1 = max(t0, ta), min(t1, tb)
if t0 > t1 {
continue
}
}
xa, xb := px+(qx-px)*t0, px+(qx-px)*t1
a, b = min(a, xa, xb), max(b, xa, xb)
}
return a, b, a <= b
}
+161
View File
@@ -0,0 +1,161 @@
//go:build windows && (amd64 || arm64)
package text
import (
"runtime"
"slices"
"sync"
"syscall"
"unsafe"
)
// The inline objects of a text layout are IDWriteInlineObjects, COM
// objects of Go whose methods are created once (callbacks are never
// freed): each tells DirectWrite the size of its box, which stands on the
// baseline and draws nothing, where the run of an object's rune would be.
var iidIDWriteInlineObject = guid{0x8339fde3, 0x106f, 0x47ab, [8]byte{0x83, 0x73, 0x1c, 0x62, 0x95, 0xeb, 0x10, 0xb3}}
// dwObject is an IDWriteInlineObject of a box w DIPs wide, h above the
// baseline and d below it.
type dwObject struct {
vtbl *[7]uintptr
w, h, d float32
}
var (
objectOnce sync.Once
objectVtbl [7]uintptr
)
func inlineObjectVtbl() *[7]uintptr {
objectOnce.Do(func() {
objectVtbl = [7]uintptr{
syscall.NewCallback(objectQueryInterface),
syscall.NewCallback(rendererAddRef), // AddRef
syscall.NewCallback(rendererAddRef), // Release
syscall.NewCallback(objectDraw),
syscall.NewCallback(objectGetMetrics),
syscall.NewCallback(objectGetOverhangMetrics),
syscall.NewCallback(objectGetBreakConditions),
}
})
return &objectVtbl
}
func objectQueryInterface(this, iid, out uintptr) uintptr {
switch *(*guid)(ptr(iid)) {
case iidIUnknown, iidIDWriteInlineObject:
*(*uintptr)(ptr(out)) = this
return 0
}
*(*uintptr)(ptr(out)) = 0
return errNoInterface
}
// objectDraw draws nothing: the object's box is the caller's.
func objectDraw(this, context, renderer, x, y, sideways, rtl, effect uintptr) uintptr { return 0 }
// objectGetMetrics writes DWRITE_INLINE_OBJECT_METRICS: width, height,
// baseline, supportsSideways.
func objectGetMetrics(this, out uintptr) uintptr {
o := (*dwObject)(ptr(this))
m := (*struct {
width, height, baseline float32
sideways int32
})(ptr(out))
m.width, m.height, m.baseline, m.sideways = o.w, o.h+o.d, o.h, 0
return 0
}
// objectGetOverhangMetrics writes DWRITE_OVERHANG_METRICS: none.
func objectGetOverhangMetrics(this, out uintptr) uintptr {
*(*[4]float32)(ptr(out)) = [4]float32{}
return 0
}
// objectGetBreakConditions lets lines break around the object as around
// what is next to it (DWRITE_BREAK_CONDITION_NEUTRAL).
func objectGetBreakConditions(this, before, after uintptr) uintptr {
*(*int32)(ptr(before)) = 0
*(*int32)(ptr(after)) = 0
return 0
}
// layoutObjects keeps the objects of the layout being made alive and in
// place until the next.
var layoutObjects struct {
objects []dwObject
pinner runtime.Pinner
}
// setObjects makes each rune of the spans with an ObjectWidth an inline
// object of the layout; units are the code units of the runes.
func setObjects(layout uintptr, spans []Span, units []uint32) {
n := 0
from := 0
for _, sp := range spans {
to := max(from, min(sp.End, len(units)-1))
if sp.ObjectWidth > 0 {
n += to - from
}
from = to
}
lo := &layoutObjects
lo.pinner.Unpin()
if n == 0 {
lo.objects = nil
return
}
lo.objects = make([]dwObject, n)
lo.pinner.Pin(&lo.objects[0])
vtbl := inlineObjectVtbl()
k := 0
from = 0
for _, sp := range spans {
to := max(from, min(sp.End, len(units)-1))
if sp.ObjectWidth > 0 {
for i := from; i < to; i++ {
o := &lo.objects[k]
*o = dwObject{vtbl: vtbl, w: sp.ObjectWidth, h: sp.ObjectHeight, d: sp.ObjectDescent}
k++
r := uintptr(units[i]) | uintptr(units[i+1]-units[i])<<32
call(layout, layoutSetInlineObject, uintptr(unsafe.Pointer(o)), r)
}
}
from = to
}
}
// objectRuns returns a run of a glyph for each inline object of the text,
// which DirectWrite draws through DrawInlineObject, whose position Go
// cannot read: hit testing gives where it starts. ends are the code units
// ending the lines; index the rune of each code unit.
func objectRuns(layout uintptr, lines []shapedLine, ends []uint32, spans []Span, units []uint32, index []int) {
from := 0
for _, sp := range spans {
to := max(from, min(sp.End, len(units)-1))
if sp.ObjectWidth > 0 {
for i := from; i < to; i++ {
pos := units[i]
li := 0
for li < len(ends)-1 && ends[li] <= pos {
li++
}
var x, y float32
var hit dwHitTestMetrics
call(layout, layoutHitTestTextPosition, uintptr(pos), 0, uintptr(unsafe.Pointer(&x)), uintptr(unsafe.Pointer(&y)), uintptr(unsafe.Pointer(&hit)))
g := Glyph{X: hit.left, Advance: sp.ObjectWidth, Cluster: index[pos], RTL: hit.bidiLevel&1 != 0}
// Runs are in visual order, their glyphs too (shape).
runs := lines[li].runs
at := 0
for at < len(runs) && (len(runs[at].glyphs) == 0 || runs[at].glyphs[0].X < g.X) {
at++
}
lines[li].runs = slices.Insert(runs, at, shapedRun{start: i, end: i + 1, glyphs: []Glyph{g}})
}
}
from = to
}
}
File diff suppressed because it is too large. Load diff
+420
View File
@@ -0,0 +1,420 @@
package text
import (
"slices"
"strings"
"unicode"
"github.com/go-text/typesetting/segmenter"
)
// Rect is a rectangle in DIPs relative to the layout.
type Rect struct{ X, Y, W, H float32 }
// lineCarets returns the x of every caret position of a line, from Start
// to End: inside a cluster of several runes (a ligature) the positions
// split the cluster evenly. It caches them in the line, so a layout's
// caret methods must be used from one goroutine at a time.
func (line *Line) lineCarets() []float32 {
if line.carets != nil {
return line.carets
}
type cluster struct {
x0, x1 float32
start, runes int
rtl bool
}
var clusters []cluster
for g := 0; g < len(line.Glyphs); {
first := line.Glyphs[g]
c := cluster{first.X, first.X + first.Advance, first.Cluster, first.Runes, first.RTL}
g++
for g < len(line.Glyphs) && line.Glyphs[g].Cluster == first.Cluster && line.Glyphs[g].Runes == first.Runes {
c.x0 = min(c.x0, line.Glyphs[g].X)
c.x1 = max(c.x1, line.Glyphs[g].X+line.Glyphs[g].Advance)
g++
}
if c.runes > 0 {
clusters = append(clusters, c)
}
}
pos := func(c cluster, k int) float32 {
f := float32(k) / float32(c.runes)
if c.rtl {
return c.x1 - (c.x1-c.x0)*f
}
return c.x0 + (c.x1-c.x0)*f
}
n := line.End - line.Start + 1
carets := make([]float32, n)
set := make([]bool, n)
// A cluster's start takes precedence over the end of the cluster
// before it, which differ in bidirectional text.
for _, c := range clusters {
for k := 0; k < c.runes; k++ {
if i := c.start + k - line.Start; i >= 0 && i < n {
carets[i], set[i] = pos(c, k), true
}
}
}
for _, c := range clusters {
if i := c.start + c.runes - line.Start; i >= 0 && i < n && !set[i] {
carets[i], set[i] = pos(c, c.runes), true
}
}
end := line.X + line.Width
if line.RTL {
end = line.X
}
for i := n - 1; i >= 0; i-- {
if !set[i] {
carets[i] = end
if i+1 < n && set[i+1] {
// A trimmed space before the next cluster.
carets[i] = carets[i+1]
}
set[i] = true
}
}
line.carets = carets
return carets
}
// LineAt returns the index of the line holding rune index, the start of
// the next line at a soft line break.
func (l *Layout) LineAt(index int) int {
for i := range l.Lines {
line := &l.Lines[i]
if index < line.End || (index == line.End && (i == len(l.Lines)-1 || l.Lines[i+1].Start > index)) {
return i
}
}
return len(l.Lines) - 1
}
// Caret returns the position of the caret before rune index: its x, the
// top of its line and the line's height.
func (l *Layout) Caret(index int) (x, y, h float32) {
if len(l.Lines) == 0 {
return 0, 0, 0
}
index = max(0, min(index, len(l.Runes)))
line := &l.Lines[l.LineAt(index)]
carets := line.lineCarets()
i := max(0, min(index-line.Start, len(carets)-1))
return carets[i], line.Y, line.Height
}
// IndexAt returns the rune index of the caret position closest to (x, y),
// between graphemes: never inside a cluster of runes.
func (l *Layout) IndexAt(x, y float32) int { return l.PositionAt(x, y).Index }
// Selection returns the rectangles covering the runes from start to end.
func (l *Layout) Selection(start, end int) []Rect { return l.SelectionOn(start, end, false) }
// SelectionOn is Selection for a layout of a paragraph of a longer text,
// whose selection goes on past the newline after the paragraph when on
// is set: the newline shows, as between the lines of a layout.
func (l *Layout) SelectionOn(start, end int, on bool) []Rect {
return l.SelectionVisual(start, end, on)
}
// SelectionVisual returns separate rectangles for selected visual runs. At
// bidi boundaries a logical range may cover disjoint areas on a line; taking
// the minimum and maximum caret would highlight intervening unselected text.
// on includes the paragraph's following newline, as SelectionOn does.
func (l *Layout) SelectionVisual(start, end int, on bool) []Rect {
return l.AppendSelection(nil, start, end, on)
}
// AppendSelection appends the rectangles of SelectionVisual to dst, for
// callers that keep them frame after frame.
func (l *Layout) AppendSelection(dst []Rect, start, end int, on bool) []Rect {
if start > end {
start, end = end, start
}
if on {
end = len(l.Runes) + 1
}
out := dst
var buf [16]Rect
for li := range l.Lines {
line := &l.Lines[li]
// A range can include the newline at End, so keep that boundary's
// line even when none of its glyphs are selected.
if line.End < start || line.Start >= end {
continue
}
pieces := buf[:0]
for i := 0; i < len(line.Glyphs); {
first := line.Glyphs[i]
x0, x1 := first.X, first.X+first.Advance
i++
for i < len(line.Glyphs) && line.Glyphs[i].Cluster == first.Cluster && line.Glyphs[i].Runes == first.Runes {
x0, x1 = min(x0, line.Glyphs[i].X), max(x1, line.Glyphs[i].X+line.Glyphs[i].Advance)
i++
}
a, z := max(start, first.Cluster), min(end, first.Cluster+first.Runes)
if a >= z || first.Runes <= 0 {
continue
}
width := x1 - x0
left, right := float32(a-first.Cluster)/float32(first.Runes), float32(z-first.Cluster)/float32(first.Runes)
if first.RTL {
left, right = 1-right, 1-left
}
r := Rect{x0 + left*width, line.Y, (right - left) * width, line.Height}
// Clusters following each other join as they come, as most do.
if n := len(pieces); n > 0 && pieces[n-1].X+pieces[n-1].W >= r.X-0.01 && pieces[n-1].X <= r.X+0.01 {
pieces[n-1].W = max(pieces[n-1].X+pieces[n-1].W, r.X+r.W) - pieces[n-1].X
continue
}
pieces = append(pieces, r)
}
if start <= line.End && end > line.End && (li < len(l.Lines)-1 && l.Lines[li+1].Start > line.End || li == len(l.Lines)-1 && on) {
x, width := line.X+line.Width, l.Params.Style.FontSize()/3
if line.RTL {
x = line.X - width
}
pieces = append(pieces, Rect{x, line.Y, width, line.Height})
}
// By x, insertion sorted: pieces are mostly in order already.
for i := 1; i < len(pieces); i++ {
for j := i; j > 0 && pieces[j-1].X > pieces[j].X; j-- {
pieces[j-1], pieces[j] = pieces[j], pieces[j-1]
}
}
for _, r := range pieces {
if r.W <= 0 {
continue
}
if n := len(out); n > len(dst) && out[n-1].Y == r.Y && out[n-1].X+out[n-1].W >= r.X-0.01 {
out[n-1].W = max(out[n-1].X+out[n-1].W, r.X+r.W) - out[n-1].X
} else {
out = append(out, r)
}
}
}
return out
}
// IsCombiningMark reports whether Backspace after r takes r alone, as
// systems do for combining marks, not the whole grapheme. Variation
// selectors are left out, so emoji sequences go whole and a selector never
// goes unseen. Sara am, a letter the segmenter joins to its consonant, goes
// alone too.
func IsCombiningMark(r rune) bool {
if unicode.Is(unicode.Variation_Selector, r) {
return false
}
return unicode.Is(unicode.Mn, r) || unicode.Is(unicode.Mc, r) || r == 0x0e33 || r == 0x0eb3
}
// Boundaries finds grapheme and word boundaries in text.
type Boundaries struct {
seg segmenter.Segmenter
runes []rune
// graphemes holds the start of every grapheme, then len(runes).
graphemes []int
}
// Reset prepares b for runes.
func (b *Boundaries) Reset(runes []rune) {
b.runes = runes
b.graphemes = b.graphemes[:0]
b.seg.Init(runes)
it := b.seg.GraphemeIterator()
for it.Next() {
b.graphemes = append(b.graphemes, it.Grapheme().Offset)
}
b.graphemes = append(b.graphemes, len(runes))
}
// GraphemeOffsets returns a copy of the grapheme starts and text's end for
// a retained shaped-text layout.
func (b *Boundaries) GraphemeOffsets() []int { return slices.Clone(b.graphemes) }
// NextGrapheme returns the end of the grapheme starting at or containing i.
func (b *Boundaries) NextGrapheme(i int) int {
for _, g := range b.graphemes {
if g > i {
return g
}
}
return len(b.runes)
}
// PrevGrapheme returns the start of the grapheme before i.
func (b *Boundaries) PrevGrapheme(i int) int {
prev := 0
for _, g := range b.graphemes {
if g >= i {
return prev
}
prev = g
}
return prev
}
// NextWord returns the end of the word after i, skipping what is between.
// Each ideograph and kana is a word (see WordBoundary).
func (b *Boundaries) NextWord(i int) int {
n := len(b.runes)
for i < n && !IsWordRune(b.runes[i]) {
i++
}
if i < n {
i++
for i < n && !WordBoundary(b.runes[i-1], b.runes[i]) {
i++
}
}
return i
}
// PrevWord returns the start of the word before i.
func (b *Boundaries) PrevWord(i int) int {
for i > 0 && !IsWordRune(b.runes[i-1]) {
i--
}
if i > 0 {
i--
for i > 0 && !WordBoundary(b.runes[i-1], b.runes[i]) {
i--
}
}
return i
}
// WordAt returns the word, or the run of other runes, around i, within
// its line: an ideograph or a kana is a word alone.
func (b *Boundaries) WordAt(i int) (start, end int) {
n := len(b.runes)
if n == 0 {
return 0, 0
}
i = min(i, n-1)
start, end = i, i
for start > 0 && b.runes[start-1] != '\n' && !WordBoundary(b.runes[start-1], b.runes[start]) {
start--
}
if b.runes[i] != '\n' {
end = i + 1
for end < n && b.runes[end] != '\n' && !WordBoundary(b.runes[end-1], b.runes[end]) {
end++
}
}
return start, end
}
// lineBreaks reports, for each rune of text and for its end, whether a
// line may break before it, in breaks, with seg; both are reused.
func lineBreaks(seg *segmenter.Segmenter, breaks []bool, text []rune) []bool {
breaks = slices.Grow(breaks[:0], len(text)+1)[:len(text)+1]
clear(breaks)
seg.Init(text)
it := seg.LineIterator()
for it.Next() {
l := it.Line()
breaks[l.Offset+len(l.Text)] = true
}
return breaks
}
// Korean is written with spaces between words, and its lines break at
// them: a word of Hangul syllables is not broken across lines, as CSS's
// word-break: keep-all has it. Unicode's line breaking algorithm, which
// the text engines follow, allows a break between any two syllables, as
// between Han characters. So in the languages that keep their words whole
// (keepsWords), the engines take the breaks between two letters or digits
// out of those it allows (keepWordsWhole), and break lines at the others,
// as at spaces and after punctuation; a word longer than a line still
// breaks where the engine breaks it, as CSS's overflow-wrap does, unless
// the text keeps words whole anyway (Params.NoBreakWords).
// keepsWords reports whether the lines of text in language lang, a BCP 47
// tag, break between words only: Korean's.
func keepsWords(lang string) bool {
base, _, _ := strings.Cut(lang, "-")
base, _, _ = strings.Cut(base, "_")
return strings.EqualFold(base, "ko")
}
// keepsAnyWords reports whether a text of language lang, with spans of
// their own languages, has runes in a language that keeps words whole.
func keepsAnyWords(lang string, spans []Span) bool {
if keepsWords(lang) {
return true
}
for _, sp := range spans {
if sp.Lang != "" && keepsWords(sp.Lang) {
return true
}
}
return false
}
// keepWordsWhole takes out of breaks, where lines of text may break
// (lineBreaks), the breaks between two letters or digits of the runes in a
// language that keeps words whole: lang, the text's, or a span's. It
// reports whether it took any out.
func keepWordsWhole(breaks []bool, text []rune, lang string, spans []Span) bool {
taken := false
// The span of the rune last asked, and where it starts.
span, from := 0, 0
keeps := func(i int) bool {
for span < len(spans) && max(spans[span].End, from) <= i {
from = max(spans[span].End, from)
span++
}
if span < len(spans) && spans[span].Lang != "" {
return keepsWords(spans[span].Lang)
}
return keepsWords(lang)
}
for i := 1; i < len(text) && i < len(breaks); i++ {
if !breaks[i] || !wordInside(text[i]) {
continue
}
// A mark goes with the letter it is on.
j := i - 1
for j > 0 && unicode.Is(unicode.M, text[j]) {
j--
}
if wordInside(text[j]) && keeps(j) && keeps(i) {
breaks[i] = false
taken = true
}
}
return taken
}
// breakAt reports whether a line may break before UTF-16 unit u, 0 < u < n,
// of a text, given breaks of its runes and the rune of each unit, index: not
// within a surrogate pair.
func breakAt(breaks []bool, index []int, u int) bool {
return index[u] != index[u-1] && breaks[index[u]]
}
// wordInside reports whether r is a letter or digit that a word keeping
// whole holds, as Chromium takes them for keep-all: but those of the
// scripts written without spaces between words, as Thai, whose breaks
// come from a dictionary.
func wordInside(r rune) bool {
if !unicode.IsLetter(r) && !unicode.IsNumber(r) {
return false
}
switch {
case r < 0x0E00:
return true
case r <= 0x0EFF, // Thai, Lao
r >= 0x1000 && r <= 0x109F, // Myanmar
r >= 0x1780 && r <= 0x17FF, // Khmer
r >= 0x1950 && r <= 0x1AAF, // Tai Le, New Tai Lue, Khmer's symbols, Tai Tham
r >= 0xA9E0 && r <= 0xA9FF, // Myanmar Extended-B
r >= 0xAA60 && r <= 0xAADF, // Myanmar Extended-A, Tai Viet
r >= 0x11700 && r <= 0x1174F: // Ahom
return false
}
return true
}
+340
View File
@@ -0,0 +1,340 @@
// Package text lays out text and rasterizes glyphs with the system's own
// text stack: DirectWrite on Windows, Core Text on macOS and Pango with
// cairo on Linux. They find the fonts, fall back to other fonts for what
// one lacks, shape and break lines; the package assembles their lines into
// layouts, with carets, selection and truncation of its own, and keeps the
// glyphs in the atlases scenes draw from. All methods of System are safe
// from any goroutine; the ui package uses them from the main thread.
package text
import (
"runtime"
"strconv"
"strings"
"sync"
"unicode/utf16"
"unicode/utf8"
"github.com/egoist/mygo/internal/scene"
)
// An engine is the system's own text stack: DirectWrite on Windows, Core
// Text on macOS and Pango on Linux. It finds fonts, falling back to the
// system's choices for what a font lacks, shapes and breaks paragraphs
// into lines, and rasterizes glyphs. The System calls it with its lock
// held, so engines need no locking of their own.
type engine interface {
// font returns the font a style asks for, at its size, which sets the
// default line height: the first family of the style the system has,
// or its user interface font.
font(style Style) *Font
// shape breaks text, a paragraph without newlines, into lines of at
// most width DIPs, or into one line when width is 0, and shapes them.
// rtl sets the paragraph's direction; wholeWords lets a word longer
// than a line overflow it instead of breaking it. spans style runs of
// the text apart from style, with their ends relative to it. The runs
// of a line and the glyphs of a run are in visual order, from the
// left, a right-to-left run's too.
shape(text []rune, style Style, spans []Span, width float32, rtl, wholeWords bool) []shapedLine
// glyph rasterizes glyph id of f at scale pixels per DIP, its origin
// dx pixels (0 ≤ dx < 1) right of the left edge of a pixel, for text
// of a shade when f is shaded or the shade is Thick, with subpixel
// antialiasing if subpixel.
glyph(f *Font, id uint32, scale, dx float32, shade Shade, subpixel bool) bitmap
// positions returns how many horizontal positions within a pixel
// glyphs of f at scale pixels per DIP are drawn at, with subpixel
// antialiasing if subpixel, and whether a pen goes to the nearest
// (round) or to the one left of it.
positions(f *Font, scale float32, subpixel bool) (n int, round bool)
// baseline returns the whole pixel a baseline y device pixels from the
// top is drawn at.
baseline(y float32) float32
// decorate returns the strokes of a decoration (see System.Decorate).
decorate(r decoRange) []Stroke
// join reports whether the engine's text stack adds the coverage of
// the glyphs of a run whose edges share pixels before blending it.
join() bool
// textParams returns how renderers correct the coverage of glyphs,
// and whether glyphs take subpixel antialiasing, as the system's
// settings say.
textParams() (p scene.TextParams, subpixel bool)
// register adds the fonts of a font file under family, or under their
// own family names when family is "".
register(data []byte, family string) error
// appFamilies lists the families of the app's fonts, in no order,
// under the names it registered them with, or their own when it gave
// none.
appFamilies() []FontFamily
// systemFamilies returns a function listing the system's families, in
// no order and without the app's, which runs without the System's lock
// on any goroutine, or nil when the engine knows none.
systemFamilies() func() []FontFamily
// resetScratch frees the room shape took from the engine's scratch,
// as a layout starts.
resetScratch()
}
// shapeScratch is room engines take the glyphs, runs and lines shape returns
// from, which live until the System lays out the next text: a layout
// copies them into its own lines. Engines embed it.
type shapeScratch struct {
glyphs []Glyph
runs []shapedRun
lines []shapedLine
}
// maxScratch is how many glyphs shapeScratch keeps room for between layouts:
// a long text's room goes with it.
const maxScratch = 4096
func (s *shapeScratch) resetScratch() {
if cap(s.glyphs) > maxScratch {
s.glyphs, s.runs, s.lines = nil, nil, nil
}
s.glyphs, s.runs, s.lines = s.glyphs[:0], s.runs[:0], s.lines[:0]
}
// dropScratch lets go of the room, and of the Fonts its glyphs and runs
// still refer to past their lengths, so that those can be released.
func (s *shapeScratch) dropScratch() { *s = shapeScratch{} }
// glyphRoom returns room for n glyphs until the next layout.
func (s *shapeScratch) glyphRoom(n int) []Glyph {
if cap(s.glyphs)-len(s.glyphs) < n {
// Slices taken before keep the old room.
s.glyphs = make([]Glyph, 0, max(2*cap(s.glyphs), n, 256))
}
k := len(s.glyphs)
s.glyphs = s.glyphs[:k+n]
return s.glyphs[k : k+n : k+n]
}
// addRun adds a run after those taken since mark, the length of runs
// then, and returns them.
func (s *shapeScratch) addRun(mark int, r shapedRun) []shapedRun {
s.runs = append(s.runs, r)
return s.runs[mark:len(s.runs):len(s.runs)]
}
// addLine adds a line after those taken since mark, the length of lines
// then, and returns them.
func (s *shapeScratch) addLine(mark int, l shapedLine) []shapedLine {
s.lines = append(s.lines, l)
return s.lines[mark:len(s.lines):len(s.lines)]
}
// shapedLine is a line of a paragraph as an engine laid it out.
type shapedLine struct {
// start and end are the runes of the paragraph the line holds,
// whitespace ending it included.
start, end int
runs []shapedRun
// mark is the rune of the paragraph an ellipsis stands at, whose
// glyphs have Cluster -1: the first it hides.
mark int
}
// shapedRun is a run of glyphs of one font and direction.
type shapedRun struct {
font *Font
// start and end are the runes of the paragraph the run holds.
start, end int
// glyphs are positioned relative to the start of the line's pen, Y
// down from the baseline, with Cluster the paragraph's rune that
// starts the glyph's cluster; Runes is set later. They are in visual
// order: a right-to-left run's clusters descend.
glyphs []Glyph
}
// bitmap is a rasterized glyph.
type bitmap struct {
// left, top, w and h are the image's box in pixels relative to the
// glyph's origin, y down.
left, top, w, h int
// pix holds a byte of coverage per pixel, or for color glyphs four
// bytes of premultiplied RGBA, or for subpixel ones the coverage of
// the red, green and blue subpixels and a fourth byte.
pix []byte
color, subpixel bool
}
// Font is a font of the system, or of the app, at a size. Layouts and
// glyphs refer to fonts by pointer: an engine returns the same Font for
// the same font and size. A Font draws for as long as anything refers to
// it, after the System let go of it too (nativeFonts).
type Font struct {
// Size is the em size in DIPs.
Size float32
// Ascent, Descent and LineGap are the font's vertical metrics in
// DIPs.
Ascent, Descent, LineGap float32
native uintptr // the engine's font
// data is what an engine keeps of the font in Go, which lives as long
// as the Font: the canvas engine's CSS font and its glyphs' texts.
data any
// shaded fonts' glyphs differ by the shade of the text; thin ones are
// too thin for antialiasing (GlyphImage.Thin). The engine draws the
// glyphs of fonts that thicken thicker for Thick. color ones draw
// their glyphs in color (emoji), for the engines that ask (Core Text
// and DirectWrite).
shaded, thin, thickens, color bool
// The tops of the font's underline and strikethrough, in DIPs above
// the baseline, and their thickness, for engines that decorate with
// them (DirectWrite and Pango).
underlineTop, underlineThick, strikeTop, strikeThick float32
}
// nativeFonts releases the native fonts of an engine's Fonts once nothing
// refers to them. The System lets go of an engine's Fonts when they are
// many (EndFrame), but layouts kept out of its caches, as the text a
// cross-fade fades out or the lines an editor keeps, may still draw with
// them: their native fonts go with the Fonts, not before. Engines embed
// it, own the native font of each Font they make, and release the native
// fonts of the Fonts found unreachable as the System asks
// (fontForgetter.releaseFonts), with its lock held.
type nativeFonts struct {
// dead is apart from the engine, so that the cleanups, which refer
// to it, keep neither the engine nor the Fonts its maps hold.
dead *deadFonts
}
// deadFonts are the native fonts of Fonts found unreachable, to release.
type deadFonts struct {
mu sync.Mutex
native []uintptr
}
// own has the native font of f released once f is unreachable.
func (n *nativeFonts) own(f *Font) {
if n.dead == nil {
n.dead = &deadFonts{}
}
runtime.AddCleanup(f, n.dead.add, f.native)
}
// add runs on the runtime's cleanup goroutine: the native font waits for
// releaseDead, as engines run with the System's lock held.
func (d *deadFonts) add(native uintptr) {
d.mu.Lock()
d.native = append(d.native, native)
d.mu.Unlock()
}
// releaseDead releases the native fonts of the Fonts found unreachable
// since it last ran.
func (n *nativeFonts) releaseDead(release func(native uintptr)) {
if n.dead == nil {
return
}
n.dead.mu.Lock()
dead := n.dead.native
n.dead.native = nil
n.dead.mu.Unlock()
for _, native := range dead {
release(native)
}
}
// generic names the families "system-ui", "sans-serif", "serif" and
// "monospace" stand for, and their aliases: "" when family is none.
func generic(family string) string {
switch strings.ToLower(family) {
case "", "system-ui", "ui-sans-serif", "-apple-system", "blinkmacsystemfont":
return "system-ui"
case "sans-serif":
return "sans-serif"
case "serif", "ui-serif":
return "serif"
case "monospace", "ui-monospace":
return "monospace"
}
return ""
}
// feature is an OpenType feature of Style.Features: its tag and value, 0
// to turn it off, 1 on, or the alternate to pick.
type feature struct {
tag [4]byte
value uint32
}
// features parses Style.Features, leaving out what is not a tag of four
// printable characters with an optional =value.
func features(list string) []feature {
if list == "" {
return nil
}
var out []feature
for _, item := range strings.Split(list, ",") {
tag, value, set := strings.Cut(strings.TrimSpace(item), "=")
tag = strings.TrimSpace(tag)
f := feature{value: 1}
if set {
v, err := strconv.ParseUint(strings.TrimSpace(value), 10, 32)
if err != nil {
continue
}
f.value = uint32(v)
}
if len(tag) != 4 || strings.ContainsFunc(tag, func(r rune) bool { return r < 0x20 || r > 0x7e }) {
continue
}
copy(f.tag[:], tag)
out = append(out, f)
}
return out
}
// familyList splits a comma-separated list of families, without quotes.
func familyList(family string) []string {
var out []string
for _, f := range strings.Split(family, ",") {
if f = strings.Trim(strings.TrimSpace(f), `"'`); f != "" {
out = append(out, f)
}
}
return out
}
// utf16Text encodes runes as UTF-16, with the rune index of every code
// unit and of the end.
func utf16Text(runes []rune) (text []uint16, index []int) {
return appendUTF16(make([]uint16, 0, len(runes)+1), make([]int, 0, len(runes)+1), runes)
}
// appendUTF16 appends the UTF-16 encoding of runes to text, and the rune
// index of every code unit and of the end to index.
func appendUTF16(text []uint16, index []int, runes []rune) ([]uint16, []int) {
for i, r := range runes {
if r >= 0x10000 && r <= utf8.MaxRune {
a, b := utf16.EncodeRune(r)
text = append(text, uint16(a), uint16(b))
index = append(index, i, i)
continue
}
if r > 0xFFFF || (r >= 0xD800 && r < 0xE000) {
r = utf8.RuneError
}
text = append(text, uint16(r))
index = append(index, i)
}
index = append(index, len(runes))
return text, index
}
// utf8Text encodes runes as UTF-8, with the rune index of every byte and
// of the end.
func utf8Text(runes []rune) (text []byte, index []int) {
text = make([]byte, 0, len(runes)+1)
index = make([]int, 0, len(runes)+1)
for i, r := range runes {
n := len(text)
text = utf8.AppendRune(text, r)
for range len(text) - n {
index = append(index, i)
}
}
index = append(index, len(runes))
return text, index
}
+5
View File
@@ -0,0 +1,5 @@
//go:build !(windows && (amd64 || arm64)) && !darwin && !(linux && !android && (amd64 || arm64)) && !js && !android
package text
func newEngine() engine { return &stubEngine{} }
+210
View File
@@ -0,0 +1,210 @@
//go:build windows && (amd64 || arm64)
package text
import (
"maps"
"slices"
"strings"
"syscall"
"testing"
"unsafe"
)
var iidIDWriteFontFace5 = guid{0x98eff3a5, 0xb667, 0x479a, [8]byte{0xb1, 0x45, 0xe2, 0xfa, 0x5b, 0x9f, 0xdc, 0x29}}
// IDWriteFontFace3's and IDWriteFontFace5's methods the tests call.
const (
face3GetFamilyNames = 40
face5GetFontAxisValueCount = 53
face5GetFontAxisValues = 54
)
// faceFamily returns the English name of a font face's family.
func faceFamily(face uintptr) string {
f3 := queryInterface(face, &iidIDWriteFontFace3)
if f3 == 0 {
return ""
}
defer release(f3)
var strs uintptr
if failed(call(f3, face3GetFamilyNames, uintptr(unsafe.Pointer(&strs)))) {
return ""
}
defer release(strs)
return englishName(strs)
}
// faceWeightAxis returns the value of a font face's weight axis
// (IDWriteFontFace5, Windows 10 1803 and later).
func faceWeightAxis(face uintptr) (float32, bool) {
f5 := queryInterface(face, &iidIDWriteFontFace5)
if f5 == 0 {
return 0, false
}
defer release(f5)
n := uint32(call(f5, face5GetFontAxisValueCount))
if n == 0 {
return 0, false
}
// DWRITE_FONT_AXIS_VALUE
values := make([]struct {
tag uint32
value float32
}, n)
if failed(call(f5, face5GetFontAxisValues, uintptr(unsafe.Pointer(&values[0])), uintptr(n))) {
return 0, false
}
for _, v := range values {
if v.tag == 'w'|'g'<<8|'h'<<16|'t'<<24 {
return v.value, true
}
}
return 0, false
}
// Chinese text in no language that writes Han characters, as an English
// app's, takes the first of the user's preferred languages that does: one
// font, that of Chinese text, rather than the English fallback's mix of a
// Japanese font where it has the characters and a Chinese one where it
// lacks them, which draws one label in two weights (#1454).
func TestDWriteUserHanLanguage(t *testing.T) {
s := newSystem()
s.mu.Lock()
defer s.mu.Unlock()
e := s.engine().(*dwrite)
saved, savedRead := e.han, e.hanRead
defer func() { e.han, e.hanRead = saved, savedRead }()
e.hanRead = true // e.han as set below, not as the user's settings say
texts := []string{"我们的音乐播放器正在播放周杰伦的歌曲", "这是一个中文标签,看看字重是否一致。", "Hello 世界 说话 东西"}
// hanFamilies returns the families of the runs of Han characters of
// text in a style and spans.
hanFamilies := func(text string, style Style, spans []Span) map[string]bool {
r := []rune(text)
e.resetScratch()
fams := map[string]bool{}
for _, line := range e.shapeText(r, style, spans, 0, false, false) {
for _, run := range line.runs {
if slices.ContainsFunc(r[run.start:run.end], isCJK) {
fams[faceFamily(run.font.native)] = true
}
}
}
return fams
}
// The fallback of the user's locale alone, the runner's en-US.
e.han = nil
for _, text := range texts {
t.Logf("%q in the locale %s: %v", text, syscall.UTF16ToString(e.locale), slices.Sorted(maps.Keys(hanFamilies(text, Style{Size: 13}, nil))))
}
// A user of English Windows who reads Chinese (userHanLanguage).
e.han = utf16z("zh-Hans-CN")
for _, style := range []Style{{Size: 13}, {Size: 13, Lang: "en"}, {Size: 13, Weight: 700}, {Size: 13, Weight: 300}, {Size: 13, Lang: "en-US", Weight: 600}} {
chinese := style
chinese.Lang = "zh-Hans-CN"
for _, text := range texts {
got := hanFamilies(text, style, nil)
if len(got) != 1 {
t.Errorf("%q in %+v is drawn in %v, not one font", text, style, slices.Sorted(maps.Keys(got)))
}
if want := hanFamilies(text, chinese, nil); !maps.Equal(got, want) {
t.Errorf("%q in %+v is drawn in %v, Chinese text in %v", text, style, slices.Sorted(maps.Keys(got)), slices.Sorted(maps.Keys(want)))
}
}
}
// Text in a language that writes Han characters keeps its own.
for _, text := range texts {
e.han = nil
want := hanFamilies(text, Style{Size: 13, Lang: "ja"}, nil)
wantSpan := hanFamilies(text, Style{Size: 13, Lang: "en"}, []Span{{End: 100, Lang: "ja"}})
e.han = utf16z("zh-Hans-CN")
if got := hanFamilies(text, Style{Size: 13, Lang: "ja"}, nil); !maps.Equal(got, want) {
t.Errorf("Japanese %q is drawn in %v, %v without the user's Chinese", text, slices.Sorted(maps.Keys(got)), slices.Sorted(maps.Keys(want)))
}
if got := hanFamilies(text, Style{Size: 13, Lang: "en"}, []Span{{End: 100, Lang: "ja"}}); !maps.Equal(got, wantSpan) {
t.Errorf("a Japanese span %q is drawn in %v, %v without the user's Chinese", text, slices.Sorted(maps.Keys(got)), slices.Sorted(maps.Keys(wantSpan)))
}
}
}
// The user's language for Han characters is read the first time a text
// has Han characters in no language that writes them, never for others'
// (#1479), and the languages of the user's profile read as Windows lists
// them.
func TestDWriteUserHanLazy(t *testing.T) {
s := newSystem()
s.mu.Lock()
defer s.mu.Unlock()
e := s.engine().(*dwrite)
for _, p := range []struct {
text string
style Style
}{{"Hello, world", Style{Size: 13}}, {"日本語", Style{Size: 13, Lang: "ja"}}, {"中文", Style{Size: 13, Lang: "zh-Hans"}}} {
e.resetScratch()
e.shapeText([]rune(p.text), p.style, nil, 0, false, false)
if e.hanRead {
t.Fatalf("%q in %+v read the user's language for Han characters", p.text, p.style)
}
}
e.resetScratch()
e.shapeText([]rune("Hello 世界"), Style{Size: 13, Lang: "en"}, nil, 0, false, false)
if !e.hanRead {
t.Errorf("Han characters in English did not read the user's language for them")
}
profile := userProfileLanguages()
t.Logf("locale %s, display languages %q, profile languages %q: Han characters in %q", syscall.UTF16ToString(e.locale), preferredLanguages(), profile, syscall.UTF16ToString(e.han))
for _, lang := range profile {
if lang == "" || strings.ContainsRune(lang, 0) {
t.Errorf("profile languages %q have %q", profile, lang)
}
}
}
// A variable font's glyphs are rasterized at the instance DirectWrite
// picked for the weight, as fallback picks them too: the face of the glyph
// run, which carries the instance's axis values, is the one rasterized,
// and a heavier weight covers more pixels. Windows has variable fonts of
// its own (Bahnschrift from Windows 10, Segoe UI Variable from Windows 11).
func TestDWriteVariableWeight(t *testing.T) {
s := newSystem()
s.mu.Lock()
defer s.mu.Unlock()
e := s.engine().(*dwrite)
tested := false
for _, family := range []string{"Bahnschrift", "Segoe UI Variable Text"} {
if !e.hasSystem(family) {
continue
}
last := 0
for _, weight := range []int{300, 400, 700} {
e.resetScratch()
lines := e.shapeText([]rune("H"), Style{Size: 40, Family: family, Weight: weight}, nil, 0, false, false)
if len(lines) != 1 || len(lines[0].runs) != 1 {
t.Fatalf("H in %s %d shaped into %+v", family, weight, lines)
}
run := lines[0].runs[0]
wght, ok := faceWeightAxis(run.font.native)
if !ok {
t.Logf("%s's face has no axis values here", family)
break
}
tested = true
if int(wght) != weight {
t.Errorf("%s %d's run is of the instance of weight %v", family, weight, wght)
}
coverage := 0
for _, p := range e.glyph(run.font, run.glyphs[0].ID, 1, 0, 0, false).pix {
coverage += int(p)
}
if coverage <= last {
t.Errorf("H in %s %d covers %d, no more than a lighter weight's %d", family, weight, coverage, last)
}
last = coverage
}
}
if !tested {
t.Skip("no variable font with axis values")
}
}
+169
View File
@@ -0,0 +1,169 @@
package text
import (
"image"
"math"
"strconv"
"strings"
)
// JoinsGlyphs reports whether glyphs of a run whose edges share pixels
// look as the system's text stack draws them only joined (GlyphRun), with
// their coverage added before blending (cairo, GTK), rather than blended
// each in turn as renderers do (Core Graphics, Direct2D).
func (s *System) JoinsGlyphs() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.engine().join()
}
// Shares reports whether glyphs a and b, their bitmaps' top-left corners
// at (ax, ay) and (bx, by) device pixels, both cover a pixel.
func (s *System) Shares(a GlyphImage, ax, ay float32, b GlyphImage, bx, by float32) bool {
if !a.OK || !b.OK || a.Colored || b.Colored || a.Subpixel != b.Subpixel {
return false
}
ra := image.Rect(int(ax), int(ay), int(ax)+int(a.W), int(ay)+int(a.H))
rb := image.Rect(int(bx), int(by), int(bx)+int(b.W), int(by)+int(b.H))
r := ra.Intersect(rb)
if r.Empty() {
return false
}
s.mu.Lock()
defer s.mu.Unlock()
at := s.MaskAtlas
if a.Subpixel {
at = s.ColorAtlas
}
covers := func(g GlyphImage, x, y int) bool {
i := (int(g.Y)+y)*at.W + int(g.X) + x
if at.BPP == 1 {
return at.Pix[i] != 0
}
p := at.Pix[4*i:]
return p[0]|p[1]|p[2] != 0
}
for y := r.Min.Y; y < r.Max.Y; y++ {
for x := r.Min.X; x < r.Max.X; x++ {
if covers(a, x-ra.Min.X, y-ra.Min.Y) && covers(b, x-rb.Min.X, y-rb.Min.Y) {
return true
}
}
}
return false
}
// GlyphRun returns glyphs ids of a font, their pens at xs device pixels
// from the left, joined as the system's text stack draws a run whose
// antialiased edges share pixels (JoinsGlyphs): their coverage added and
// clamped. The glyphs are for text of a shade, on an opaque background or
// not, as for Glyph. Left is relative to the pixel the first pen is in.
func (s *System) GlyphRun(f *Font, ids []uint32, xs []float32, scale float32, shade Shade, opaque bool) GlyphImage {
if len(ids) == 0 || len(ids) != len(xs) {
return GlyphImage{}
}
// The glyphs, as placed alone, which the key names.
gs := make([]GlyphImage, len(ids))
for i, id := range ids {
gs[i] = s.Glyph(f, id, scale, xs[i], shade, opaque)
}
s.mu.Lock()
defer s.mu.Unlock()
shade = f.shadeFor(shade)
subpixel := opaque && s.subpixel
origin := math.Floor(float64(xs[0]))
var key strings.Builder
key.WriteString(strconv.FormatUint(uint64(uint32(scale*256+0.5)), 10))
key.WriteByte(byte('0' + shade))
if subpixel {
key.WriteByte('s')
}
for i, id := range ids {
q, _, carry := s.place(f, scale, subpixel, xs[i])
key.WriteByte(' ')
key.WriteString(strconv.FormatUint(uint64(id), 10))
key.WriteByte('@')
key.WriteString(strconv.Itoa(int(math.Floor(float64(xs[i])) - origin + float64(carry))))
key.WriteByte('+')
key.WriteString(strconv.Itoa(q))
}
rk := runKey{f, key.String()}
if e, ok := s.runs[rk]; ok {
e.used = s.frame
return e.GlyphImage
}
if _, out := s.outRuns[rk]; out {
return GlyphImage{}
}
b := s.addGlyphs(gs, xs, origin)
if b.w <= 0 || b.h <= 0 || b.w > 4096 || b.h > 2048 {
return GlyphImage{}
}
inColor := b.subpixel
x, y, ok := s.alloc(inColor, b.w, b.h)
if !ok {
if s.outRuns == nil {
s.outRuns = map[runKey]struct{}{}
}
s.outRuns[rk] = struct{}{}
return GlyphImage{}
}
if inColor {
s.ColorAtlas.Put(x, y, b.w, b.h, b.pix, 4*b.w)
} else {
s.MaskAtlas.Put(x, y, b.w, b.h, b.pix, b.w)
}
g := GlyphImage{OK: true, Subpixel: b.subpixel, Thin: f.thin,
X: uint16(x), Y: uint16(y), W: uint16(b.w), H: uint16(b.h), Left: float32(b.left), Top: float32(b.top)}
s.runs[rk] = &atlasEntry{g, s.frame}
return g
}
type runKey struct {
font *Font
key string
}
// addGlyphs adds the coverage of glyphs placed alone, their pens at xs,
// clamped, as cairo composites the glyphs of a run, into a bitmap placed
// from the pixel origin.
func (s *System) addGlyphs(gs []GlyphImage, xs []float32, origin float64) bitmap {
var box image.Rectangle
rects := make([]image.Rectangle, len(gs))
for i, g := range gs {
if !g.OK {
continue
}
x := int(math.Floor(float64(xs[i]))-origin) + int(g.Left)
rects[i] = image.Rect(x, int(g.Top), x+int(g.W), int(g.Top)+int(g.H))
box = box.Union(rects[i])
}
if box.Empty() {
return bitmap{}
}
subpixel := gs[0].Subpixel
at, bpp := s.MaskAtlas, 1
if subpixel {
at, bpp = s.ColorAtlas, 4
}
w, h := box.Dx(), box.Dy()
sum := make([]uint16, w*h*bpp)
for i, g := range gs {
if !g.OK {
continue
}
r := rects[i]
for y := range int(g.H) {
src := at.Pix[((int(g.Y)+y)*at.W+int(g.X))*bpp:]
dst := sum[((r.Min.Y-box.Min.Y+y)*w+r.Min.X-box.Min.X)*bpp:]
for k := range int(g.W) * bpp {
dst[k] += uint16(src[k])
}
}
}
pix := make([]byte, len(sum))
for i, v := range sum {
pix[i] = uint8(min(v, 255))
}
return bitmap{left: box.Min.X, top: box.Min.Y, w: w, h: h, pix: pix, subpixel: subpixel}
}
+164
View File
@@ -0,0 +1,164 @@
package text
import (
"slices"
"strings"
"testing"
"github.com/go-text/typesetting/segmenter"
)
// keptBreaks returns where the lines of text may break in language lang
// with spans, but at its end.
func keptBreaks(text []rune, lang string, spans []Span) []int {
var seg segmenter.Segmenter
breaks := lineBreaks(&seg, nil, text)
keepWordsWhole(breaks, text, lang, spans)
var at []int
for i, ok := range breaks[:len(text)] {
if ok {
at = append(at, i)
}
}
return at
}
func TestKeepWordsWholeBreaksKoreanAtSpaces(t *testing.T) {
text := []rune("안녕하세요 반갑습니다, Stacia2 앱")
var seg segmenter.Segmenter
breaks := lineBreaks(&seg, nil, text)
if !breaks[2] {
t.Fatal("UAX #14 should allow a break between Hangul syllables")
}
if !keepWordsWhole(breaks, text, "ko", nil) {
t.Fatal("no break taken out")
}
var at []int
for i, ok := range breaks {
if ok {
at = append(at, i)
}
}
if want := []int{6, 13, 21, len(text)}; !slices.Equal(at, want) {
t.Fatalf("breaks at %v, want %v", at, want)
}
for _, lang := range []string{"ko", "ko-KR", "KO", "ko_KR", "ko-Kore-KR"} {
if !keepsWords(lang) {
t.Errorf("keepsWords(%q) = false", lang)
}
}
for _, lang := range []string{"", "ja", "zh-Hans", "kok", "en-KO"} {
if keepsWords(lang) {
t.Errorf("keepsWords(%q) = true", lang)
}
}
}
func TestKeepWordsWhole(t *testing.T) {
for _, c := range []struct {
text, lang string
spans []Span
want []int
}{
// A break after punctuation stays, with or without a space.
{"가나,다라 마바", "ko", nil, []int{3, 6}},
{"(가나)다라", "ko", nil, []int{4}},
// Han characters and kana are letters of a word too.
{"大韓民國 만세", "ko", nil, []int{5}},
// Jamo, compatibility jamo, and a syllable with a combining mark.
{"ㅋㅋㅋ ᄀᄀ", "ko", nil, []int{4}},
{"가́나 다", "ko", nil, []int{4}},
// An emoji is no letter: lines break around it.
{"가😀나", "ko", nil, []int{1, 2}},
// After a hyphen, as in English.
{"가-나", "ko", nil, []int{2}},
// Thai, which breaks by a dictionary, is left to it.
{"가สวัสดี", "ko", nil, []int{1}},
// Other languages are left as they are.
{"가나 다", "ja", nil, []int{1, 3}},
{"가나 다", "", nil, []int{1, 3}},
// The language of spans.
{"가나 다라", "en", []Span{{End: 3, Lang: "ko"}}, []int{3, 4}},
{"가나 다라", "ko", []Span{{End: 3}, {End: 5, Lang: "ja"}}, []int{3, 4}},
{"가나다", "en", []Span{{End: 1}, {End: 3, Lang: "ko"}}, []int{1}},
} {
if got := keptBreaks([]rune(c.text), c.lang, c.spans); !slices.Equal(got, c.want) {
t.Errorf("%q in %q with %v breaks at %v, want %v", c.text, c.lang, c.spans, got, c.want)
}
}
}
// keepAllText is Korean, of words up to five syllables long.
const keepAllText = "안녕하세요 반갑습니다 오늘은 날씨가 정말 좋네요 우리 함께 산책하러 갈까요"
// Korean text breaks its lines at spaces, with every engine, and other
// languages' text between syllables (#1403). A word longer than a line
// still breaks, unless words are kept whole anyway.
func TestKeepAllLayout(t *testing.T) {
s := Shared()
style := Style{Size: 16, Lang: "ko"}
width := s.Layout(Params{Text: "가나다라마", Style: style}).Width + 0.5
text := []rune(keepAllText)
breaksAt := func(l *Layout) (atSpace, inWord int) {
for i, line := range l.Lines[:len(l.Lines)-1] {
if line.End != l.Lines[i+1].Start {
t.Errorf("line %d ends at %d, the next starts at %d", i, line.End, l.Lines[i+1].Start)
}
if text[line.End-1] == ' ' {
atSpace++
} else {
inWord++
}
}
return atSpace, inWord
}
ko := s.Layout(Params{Text: keepAllText, Style: style, Width: width})
if atSpace, inWord := breaksAt(ko); inWord > 0 || atSpace < 4 {
t.Errorf("in Korean, %d lines break at spaces, %d within words", atSpace, inWord)
for _, line := range ko.Lines {
t.Logf("%q", string(text[line.Start:line.End]))
}
}
for _, line := range ko.Lines {
if line.Width > width+0.5 {
t.Errorf("a line of Korean is %v wide, wider than %v", line.Width, width)
}
}
en := s.Layout(Params{Text: keepAllText, Style: Style{Size: 16, Lang: "en"}, Width: width})
if _, inWord := breaksAt(en); inWord == 0 {
t.Error("in English, no line breaks within a Korean word")
}
// A word longer than the line breaks within itself, not the line
// before it.
long := "가나 " + strings.Repeat("다라마바사", 3) + " 아자"
text = []rune(long)
l := s.Layout(Params{Text: long, Style: style, Width: width})
if len(l.Lines) < 4 || l.Lines[0].End != 3 {
t.Errorf("a long word took lines %v", lineRanges(l))
}
for _, line := range l.Lines {
if line.Width > width+0.5 {
t.Errorf("a line of the long word is %v wide, wider than %v", line.Width, width)
}
}
// Kept whole anyway, it overflows its own line.
l = s.Layout(Params{Text: long, Style: style, Width: width, NoBreakWords: true})
if got, want := lineRanges(l), [][2]int{{0, 3}, {3, 19}, {19, 21}}; !slices.Equal(got, want) {
t.Errorf("with words kept whole, lines %v, want %v", got, want)
}
// Spaces kept, the lines of Korean break where they did.
l = s.Layout(Params{Text: keepAllText, Style: style, Width: width, KeepSpaces: true})
text = []rune(keepAllText)
if _, inWord := breaksAt(l); inWord > 0 {
t.Errorf("with spaces kept, %d lines break within words", inWord)
}
}
func lineRanges(l *Layout) [][2]int {
var out [][2]int
for _, line := range l.Lines {
out = append(out, [2]int{line.Start, line.End})
}
return out
}
+223
View File
@@ -0,0 +1,223 @@
package text
import (
"slices"
"strings"
"unicode"
"unicode/utf16"
)
// The language of a text decides the glyphs of the scripts it writes,
// which some fonts draw apart by language, as the Han characters Chinese
// and Japanese share, and the fonts the system falls back to for them.
// Han characters in a text of a language that does not write them, as a
// Chinese name in an English sentence, keep the glyphs the system picks
// for them by the user's settings, as they had without a language: the
// language says nothing of them, and an English app shown to a reader of
// Japanese should not draw a Japanese name with Chinese glyphs. Browsers
// do the same (Chromium's LayoutLocale::LocaleForHan). Core Text does it
// by itself; DirectWrite and Pango are told (cjkRuns).
//
// On Windows the user's settings are more than the locale of their
// regional formats, which DirectWrite falls back by. DirectWrite's fallback
// for English draws Chinese text in Yu Gothic UI, a Japanese font, where it
// has the characters, and in Microsoft JhengHei UI, a Traditional Chinese
// one, where it lacks them, strokes of two weights in one label (#1454):
// a user of English Windows who reads Chinese lists it among their
// preferred languages. Han characters in no language that writes them take
// the first of those that does (userHanLanguage), as Chromium takes the
// first of its accepted languages. Windows keeps two such lists: the
// display languages (GetUserPreferredUILanguages), only those whose
// language pack is installed, and the languages of Settings > Time &
// language > Language & region, which may list Chinese below English
// without its pack (#1479). The first is read first, the second where it
// has none (resolveUserHanLanguage), and both only once a text has Han
// characters in no language that writes them, which most apps' never do.
// writesHan reports whether a language writes Han characters: Chinese,
// with its languages of other codes, Japanese and Korean.
func writesHan(lang string) bool {
base, _, _ := strings.Cut(strings.ToLower(lang), "-")
base, _, _ = strings.Cut(base, "_")
switch base {
case "zh", "ja", "ko", "yue", "cmn", "wuu", "hak", "nan", "gan", "hsn", "lzh", "cjy", "cpx", "czh", "czo", "mnp", "cdo":
return true
}
return false
}
// isCJK reports whether r is a Han character, or a mark of punctuation
// or a full-width form that the languages writing Han draw apart.
func isCJK(r rune) bool {
switch {
case r < 0x2E80:
return false
case r >= 0x3000 && r <= 0x303F, r >= 0xFF00 && r <= 0xFFEF:
return true
}
return unicode.Is(unicode.Han, r)
}
// languageShapes reports whether a language can change how a text is drawn
// or broken, and so whether the text engine must be told it, which costs Core
// Text a new break iterator for each line it breaks. Latin letters look the
// same in the languages but those whose fonts draw some of them apart (the
// Turkic languages' i and fi, Dutch's ij, Polish's ó, Catalan's l·l), and in
// the languages writing Han, the marks beyond ASCII may come from a font of
// that language rather than the text's.
func languageShapes(text []rune, lang string) bool {
if lang == "" {
return false
}
base, _, _ := strings.Cut(strings.ToLower(lang), "-")
base, _, _ = strings.Cut(base, "_")
switch base {
case "tr", "az", "crh", "tt", "kk", "ba", "nl", "pl", "ca":
return true
}
limit := rune(0xFF)
if writesHan(lang) {
limit = 0x7F
}
for _, r := range text {
if r > limit {
return true
}
}
return false
}
// langRun is a run of runes of a text, from start to end, in one language
// as the text engine is to be told it.
type langRun struct {
start, end int
lang string
}
// langRuns returns the runs of a text whose language the engine must be
// told apart from base, the language of its style, given the language of
// the spans. A run of "" is in the engine's own language, as Han
// characters are in a language that does not write them. It returns nil
// when every rune is in base.
func langRuns(text []rune, base string, spans []Span) []langRun {
if (base == "" || writesHan(base)) && !spansHaveLang(spans) {
return nil
}
var out []langRun
eachLang(text, base, spans, func(i int, lang string) {
if lang != base {
out = addLangRun(out, i, lang)
}
})
return out
}
// userHanRuns returns the runs of Han characters of a text, and their
// punctuation, in no language that writes them: those langRuns leaves in
// the engine's own language, in which the system picks their glyphs for
// the user.
func userHanRuns(text []rune, base string, spans []Span) []langRun {
if writesHan(base) && !spansHaveLang(spans) || !slices.ContainsFunc(text, isCJK) {
return nil
}
var out []langRun
eachLang(text, base, spans, func(i int, lang string) {
if lang == "" && isCJK(text[i]) {
out = addLangRun(out, i, "")
}
})
return out
}
// eachLang calls fn with the index of each rune of a text and its language
// as the engine is to be told it: the base's, its span's, or "" for a Han
// character in a language that does not write it.
func eachLang(text []rune, base string, spans []Span, fn func(i int, lang string)) {
span, from := 0, 0
for i, r := range text {
lang := base
for span < len(spans) && max(spans[span].End, from) <= i {
from = max(spans[span].End, from)
span++
}
if span < len(spans) && spans[span].Lang != "" {
lang = spans[span].Lang
}
if lang != "" && isCJK(r) && !writesHan(lang) {
lang = ""
}
fn(i, lang)
}
}
// addLangRun adds rune i, in a language, to runs, extending the last.
func addLangRun(runs []langRun, i int, lang string) []langRun {
if n := len(runs); n > 0 && runs[n-1].end == i && runs[n-1].lang == lang {
runs[n-1].end = i + 1
return runs
}
return append(runs, langRun{i, i + 1, lang})
}
// userHanLanguage returns the language in which Han characters in no
// language that writes them are drawn, given the locale of the user's
// regional formats and the languages they prefer, in order: "" when the
// locale writes them, which the engine draws them in already, else the
// first preferred language that writes them, else "" for the system's own
// choice.
func userHanLanguage(locale string, preferred []string) string {
if writesHan(locale) {
return ""
}
for _, lang := range preferred {
if writesHan(lang) {
return lang
}
}
return ""
}
// resolveUserHanLanguage returns userHanLanguage of the user's locale and
// the first of the lists of their preferred languages that has one that
// writes Han characters, reading each list only when those before it have
// none, and reading none when the locale writes them.
func resolveUserHanLanguage(locale string, lists ...func() []string) string {
if writesHan(locale) {
return ""
}
for _, list := range lists {
if lang := userHanLanguage(locale, list()); lang != "" {
return lang
}
}
return ""
}
// splitMultiString returns the strings of a list in UTF-16, each ending
// in a NUL and the list in another (REG_MULTI_SZ, and the MUI's lists of
// languages), skipping empty ones; a last string without its NUL counts.
func splitMultiString(buf []uint16) []string {
var out []string
start := 0
for i, c := range buf {
if c == 0 {
if i > start {
out = append(out, string(utf16.Decode(buf[start:i])))
}
start = i + 1
}
}
if start < len(buf) {
out = append(out, string(utf16.Decode(buf[start:])))
}
return out
}
func spansHaveLang(spans []Span) bool {
for _, sp := range spans {
if sp.Lang != "" {
return true
}
}
return false
}
File diff suppressed because it is too large. Load diff
+315
View File
@@ -0,0 +1,315 @@
package text
import (
"fmt"
"runtime"
"strings"
"testing"
"unsafe"
"weak"
)
// Scrolling must not retain hundreds of frames of glyph arrays that
// cannot expire once the window stops drawing.
func TestLayoutCacheBoundsScrollingMemory(t *testing.T) {
s := newSystem()
s.eng = &stubEngine{}
const rows = 40
for frame := range 300 {
for row := range rows {
s.Layout(Params{Text: fmt.Sprintf("line %d: %s", frame*rows+row, strings.Repeat("code ", 20))})
}
s.EndFrame()
if s.layoutBytes > maxLayoutBytes || len(s.layouts) > maxLayouts {
t.Fatalf("frame %d retained %d bytes in %d layouts", frame, s.layoutBytes, len(s.layouts))
}
}
}
func TestLayoutCacheReusesDisplayedText(t *testing.T) {
s := newSystem()
s.eng = &stubEngine{}
p := Params{Text: "unchanged visible text"}
l := s.Layout(p)
for range 10 {
s.EndFrame()
if got := s.Layout(p); got != l {
t.Fatal("a new frame reshaped unchanged visible text")
}
if got := s.Layout(p); got != l {
t.Fatal("repeated measurement in one frame reshaped the text")
}
}
if n := s.LayoutsMade(); n != 1 {
t.Fatalf("made %d layouts for unchanged text", n)
}
}
func TestLayoutCacheReleasesEvictedText(t *testing.T) {
s := newSystem()
s.eng = &stubEngine{}
old := weak.Make(s.Layout(Params{Text: "the first viewport"}))
for i := range maxLayouts + 1 {
s.Layout(Params{Text: fmt.Sprint(i)})
}
runtime.GC()
if old.Value() != nil {
t.Fatal("evicted text is retained while the window is idle")
}
runtime.KeepAlive(s)
}
func TestLayoutCacheKeepsFrequentlyUsedText(t *testing.T) {
s := newSystem()
s.eng = &stubEngine{}
p := Params{Text: "a frequently used label"}
l := s.Layout(p)
for i := range maxLayouts + 1 {
s.Layout(Params{Text: fmt.Sprint(i)})
if got := s.Layout(p); got != l {
t.Fatal("cache pressure evicted a frequently used label")
}
}
}
func TestLayoutCacheSkipsOversizedParagraph(t *testing.T) {
s := newSystem()
s.eng = &stubEngine{}
p := Params{Text: "a small label"}
l := s.Layout(p)
large := s.Layout(Params{Text: strings.Repeat("x", maxLayoutBytes/32)})
if len(large.Runes) != maxLayoutBytes/32 || len(large.Lines) == 0 {
t.Fatal("oversized text did not lay out")
}
if len(s.layouts) != 1 || s.Layout(p) != l {
t.Fatal("an oversized paragraph displaced the ordinary labels")
}
}
func TestRetainedLayoutDoesNotRetainClearedCache(t *testing.T) {
s := newSystem()
s.eng = &stubEngine{}
kept := s.Layout(Params{Text: "kept by an element"})
other := weak.Make(s.Layout(Params{Text: "no longer used"}))
s.clearLayouts()
runtime.GC()
if other.Value() != nil || s.layoutBytes != 0 {
t.Fatal("a retained layout keeps the cleared cache alive")
}
runtime.KeepAlive(kept)
runtime.KeepAlive(s)
}
func cacheDocumentExcerpt(s *System) weak.Pointer[byte] {
document := strings.Repeat("x", 1<<20)
old := weak.Make(unsafe.StringData(document))
s.Layout(Params{Text: document[100:110]})
return old
}
func TestLayoutCacheDoesNotRetainExcerptSource(t *testing.T) {
s := newSystem()
s.eng = &stubEngine{}
old := cacheDocumentExcerpt(s)
runtime.GC()
if old.Value() != nil {
t.Fatal("a cached ten-character excerpt retains its entire source document")
}
if s.Layout(Params{Text: strings.Repeat("x", 10)}).Params.Text != strings.Repeat("x", 10) {
t.Fatal("the cache changed the excerpt's text")
}
runtime.KeepAlive(s)
}
// documentRow is a paragraph of a long document, and document the
// paragraphs whose layouts take a little more than the cache's budget,
// however large the layouts of this engine are.
func documentRow(i int) Params {
return Params{Text: fmt.Sprintf("paragraph %04d: %s", i, strings.Repeat("word ", 60))}
}
func document(s *System) []Params {
s.Layout(documentRow(0))
ps := make([]Params, maxLayoutBytes*9/8/s.layoutBytes+1)
for i := range ps {
ps[i] = documentRow(i)
}
return ps
}
// A window drawing a document a little over the budget must not evict
// each paragraph just before its next frame lays it out again.
func TestLayoutCacheKeepsDisplayedDocument(t *testing.T) {
s := newSystem()
s.eng = &stubEngine{}
ps := document(s)
for _, p := range ps {
s.Layout(p)
}
if s.layoutBytes <= maxLayoutBytes {
t.Fatalf("the document takes %d bytes, within the budget", s.layoutBytes)
}
s.EndFrame()
made := s.LayoutsMade()
for range 20 {
for _, p := range ps {
s.Layout(p)
}
s.EndFrame()
}
if n := s.LayoutsMade() - made; n != 0 {
t.Fatalf("made %d layouts for the unchanged document", n)
}
}
// Once no frame draws the document, the cache goes back to its budget,
// whichever window's frames go by, and later forgets the rest.
func TestLayoutCacheTrimsUnusedDocument(t *testing.T) {
s := newSystem()
s.eng = &stubEngine{}
for _, p := range document(s) {
s.Layout(p)
}
for range liveLayoutFrames - 1 {
s.EndFrame()
if s.layoutBytes <= maxLayoutBytes {
t.Fatal("the document was trimmed while still recent")
}
}
s.Layout(Params{Text: "another window"})
s.EndFrame()
if s.layoutBytes > maxLayoutBytes {
t.Fatalf("kept %d bytes of unused layouts", s.layoutBytes)
}
for range 241 {
s.EndFrame()
}
if len(s.layouts) != 0 || s.layoutBytes != 0 {
t.Fatal("old layouts survived expiry")
}
}
// Windows take turns: another window's frames between two of the
// document's keep its layouts.
func TestLayoutCacheKeepsDocumentAcrossWindows(t *testing.T) {
s := newSystem()
s.eng = &stubEngine{}
ps := document(s)
first := s.Layout(ps[0])
for _, p := range ps[1:] {
s.Layout(p)
}
s.EndFrame()
for range liveLayoutFrames - 2 {
s.Layout(Params{Text: "another window"})
s.EndFrame()
}
if s.Layout(ps[0]) != first {
t.Fatal("another window's frames evicted the document")
}
}
// Recent layouts still stay within a hard limit.
func TestLayoutCacheCapsRecentBytes(t *testing.T) {
s := newSystem()
s.eng = &stubEngine{}
first := s.Layout(Params{Text: "first"})
for i := range 100 {
s.Layout(Params{Text: fmt.Sprintf("%d: %s", i, strings.Repeat("word ", 2000))})
if s.layoutBytes > maxLiveLayoutBytes {
t.Fatalf("kept %d bytes", s.layoutBytes)
}
}
if s.Layout(Params{Text: "first"}) == first {
t.Fatal("the hard limit did not evict the oldest layout")
}
}
// largeParagraph is a paragraph whose layout takes more than
// maxLayoutBytes and at most maxLargeLayoutBytes, and its size.
func largeParagraph(t *testing.T, s *System) (Params, int) {
p := Params{Text: strings.Repeat("mixed 中文。 ", 10000), Width: 700}
n := layoutBytes(s.layout(p))
if n <= maxLayoutBytes || n > maxLargeLayoutBytes {
t.Fatalf("the paragraph's layout takes %d bytes", n)
}
return p, n
}
// sectionRow is a layout of a few MiB, within maxLayoutBytes.
func sectionRow(i int) Params {
return Params{Text: fmt.Sprintf("%d: %s", i, strings.Repeat("x", 30000))}
}
// An unchanged paragraph above the ordinary budget is not laid out again
// while frames draw it, and is let go once they stop.
func TestOversizedParagraphWarmReuse(t *testing.T) {
s := newSystem()
s.eng = &stubEngine{}
p, _ := largeParagraph(t, s)
label := Params{Text: "a small label"}
first, l := s.Layout(p), s.Layout(label)
for range 5 {
s.EndFrame()
if s.Layout(p) != first {
t.Fatal("unchanged oversized paragraph was reshaped")
}
if s.Layout(label) != l {
t.Fatal("an oversized paragraph displaced the ordinary labels")
}
}
for range liveLayoutFrames {
s.Layout(label)
s.EndFrame()
}
if s.layoutBytes > maxLayoutBytes || s.Layout(label) != l {
t.Fatalf("kept %d bytes once no frame drew the paragraph", s.layoutBytes)
}
}
// A large paragraph that would evict layouts recent frames drew is laid
// out without caching it, and leaves them cached.
func TestOversizedParagraphKeepsLiveLayouts(t *testing.T) {
s := newSystem()
s.eng = &stubEngine{}
big, n := largeParagraph(t, s)
var ps []Params
for s.layoutBytes+n <= maxLiveLayoutBytes {
ps = append(ps, sectionRow(len(ps)))
s.Layout(ps[len(ps)-1])
}
made := s.LayoutsMade()
for range 3 {
for _, p := range ps {
s.Layout(p)
}
s.Layout(big)
s.EndFrame()
}
if n := s.LayoutsMade() - made; n != 3 {
t.Fatalf("made %d layouts in 3 frames, want the paragraph's 3", n)
}
}
// Making room for a large paragraph evicts the layouts no recent frame
// used, whether for their bytes or their count.
func TestOversizedParagraphEvictsUnusedLayouts(t *testing.T) {
s := newSystem()
s.eng = &stubEngine{}
big, _ := largeParagraph(t, s)
unused := s.Layout(Params{Text: "label 0"})
for i := 1; i < maxLayouts; i++ {
s.Layout(Params{Text: fmt.Sprint("label ", i)})
}
for range liveLayoutFrames {
s.EndFrame()
}
l := s.Layout(big)
s.EndFrame()
if s.Layout(big) != l {
t.Fatal("the paragraph was not cached in place of unused layouts")
}
if s.Layout(Params{Text: "label 0"}) == unused {
t.Fatal("the unused layouts survived")
}
}
+223
View File
@@ -0,0 +1,223 @@
package text
import "math"
// A table of prices or a dashboard shows new numbers in every frame, each a
// text the system's text engine has never shaped. But a number in one font is
// its characters side by side, each with its glyph and advance, its advance
// changed by the kerning with the next: an engine measures those once for
// each font, by having the system shape each character and each pair, and
// puts numbers together from them (numberFont). GPUI Fast does the same.
// Core Text (numbers_darwin.go) and DirectWrite (numbers_windows.go) do.
//
// That holds while only neighbours affect each other. So the characters are
// few, a pair the system shapes as anything but its two glyphs is left to it,
// and the first numbers of a font, and one in every few hundred after them,
// are shaped by the system too: a font where the two differ is left to it
// from then on.
// numberCharacters are what numbers are written with.
const numberCharacters = "0123456789.,+-%$"
const (
numberCount = len(numberCharacters)
// maxNumber is the longest text put together: longer ones are rarely
// numbers.
maxNumber = 32
// numbersCheckedFirst is how many numbers of a font are checked before
// it is trusted, and numbersCheckedEvery how often after that.
numbersCheckedFirst = 32
numbersCheckedEvery = 256
// numberTolerance is how far a position may be from the system's, which
// may add advances up in double precision and hand them over rounded.
numberTolerance = 1e-3
)
// numberSlots gives a character's place in numberCharacters, plus one.
var numberSlots = func() (slots [128]uint8) {
for i := range numberCount {
slots[numberCharacters[i]] = uint8(i + 1)
}
return slots
}()
// numberGlyph is what is known of a character alone. usable tells that it is
// one glyph standing on the pen.
type numberGlyph struct {
font *Font
id uint32
advance float32
known bool
usable bool
}
// numberPair is what is known of the first of two characters side by side,
// whose advance has their kerning in it. usable tells that they are their two
// glyphs alone.
type numberPair struct {
advance float32
known bool
usable bool
}
// numberFont is what a font shapes numbers into, measured as they come.
type numberFont struct {
glyphs [numberCount]numberGlyph
pairs [numberCount][numberCount]numberPair
// lines is how many numbers were put together, checked how many of them
// the system agreed with, and disagreed that it did not with one.
lines, checked uint64
disagreed bool
}
// shapeOne has the system shape text of a style into one line, unwrapped,
// left to right: what a numberFont measures and checks against.
type shapeOne func(text []rune, style Style) []shapedLine
// mayBeNumber reports whether text, of a style and spans, laid out in a
// direction, is one an engine may put together, before its font is known.
func mayBeNumber(text []rune, style Style, spans []Span, rtl bool) bool {
n := len(text)
if n == 0 || n > maxNumber || rtl || len(spans) > 0 || style.LetterSpacing != 0 || style.Features != "" || style.tabStop > 0 {
return false
}
for _, r := range text {
if r >= 128 || numberSlots[r] == 0 {
return false
}
}
return !languageShapes(text, style.Lang)
}
// measure returns the font a number's glyphs all come from, and whether it
// can be put together and fits width (0 for no limit). Text passed
// mayBeNumber.
func (f *numberFont) measure(text []rune, style Style, width float32, shape shapeOne) (*Font, bool) {
if f.disagreed {
return nil, false
}
n := len(text)
var one *Font
pen := 0.0
for i, r := range text {
a := numberSlots[r] - 1
g := f.glyph(a, style, shape)
if !g.usable || one != nil && g.font != one {
return nil, false
}
one = g.font
advance := g.advance
if i+1 < n {
p := f.pair(a, numberSlots[text[i+1]]-1, style, shape)
if !p.usable {
return nil, false
}
advance = p.advance
}
pen += float64(advance)
}
if width > 0 && pen > float64(width)+1.0/1024 {
return nil, false // it wraps
}
return one, true
}
// put fills glyphs, as long as text, with the number text, which measure
// took.
func (f *numberFont) put(text []rune, glyphs []Glyph) {
n := len(text)
x := 0.0
for i, r := range text {
a := numberSlots[r] - 1
g := &f.glyphs[a]
advance := g.advance
if i+1 < n {
advance = f.pairs[a][numberSlots[text[i+1]]-1].advance
}
glyphs[i] = Glyph{Font: g.font, ID: g.id, X: float32(x), Advance: advance, Cluster: i}
x += float64(advance)
}
}
// check counts a number put together into lines, and has the system shape it
// when it is one of those checked: it returns what the system shaped when the
// two differ, and the font is left to the system from then on, or nil.
func (f *numberFont) check(lines []shapedLine, text []rune, style Style, width float32, shape func() []shapedLine) []shapedLine {
f.lines++
if f.checked >= numbersCheckedFirst && f.lines%numbersCheckedEvery != 0 {
return nil
}
shaped := shape()
if !sameNumber(lines, shaped) {
f.disagreed = true
return shaped
}
f.checked++
return nil
}
// glyph returns the measure of a character alone.
func (f *numberFont) glyph(a uint8, style Style, shape shapeOne) *numberGlyph {
g := &f.glyphs[a]
if g.known {
return g
}
g.known = true
shaped := shape([]rune{rune(numberCharacters[a])}, style)
if run := oneRun(shaped); run != nil && len(run.glyphs) == 1 {
if s := run.glyphs[0]; s.X == 0 && s.Y == 0 && s.Cluster == 0 && s.Font != nil {
*g = numberGlyph{font: s.Font, id: s.ID, advance: s.Advance, known: true, usable: true}
}
}
return g
}
// pair returns the measure of the first of two characters side by side,
// whose glyphs must be theirs alone with the second placed by the first's
// advance.
func (f *numberFont) pair(a, b uint8, style Style, shape shapeOne) *numberPair {
p := &f.pairs[a][b]
if p.known {
return p
}
p.known = true
first, second := f.glyph(a, style, shape), f.glyph(b, style, shape)
if !first.usable || !second.usable {
return p
}
run := oneRun(shape([]rune{rune(numberCharacters[a]), rune(numberCharacters[b])}, style))
if run == nil || len(run.glyphs) != 2 {
return p
}
x, y := run.glyphs[0], run.glyphs[1]
if x.ID == first.id && y.ID == second.id && x.Font == first.font && y.Font == second.font && x.X == 0 && x.Y == 0 && y.Y == 0 &&
x.Cluster == 0 && y.Cluster == 1 && math.Abs(float64(y.X-x.Advance)) <= numberTolerance {
*p = numberPair{advance: x.Advance, known: true, usable: true}
}
return p
}
// oneRun returns the run of lines that are one line of one run, or nil.
func oneRun(lines []shapedLine) *shapedRun {
if len(lines) != 1 || len(lines[0].runs) != 1 {
return nil
}
return &lines[0].runs[0]
}
// sameNumber reports whether a number put together is what the system
// shaped.
func sameNumber(a, b []shapedLine) bool {
x, y := oneRun(a), oneRun(b)
if x == nil || y == nil || x.font != y.font || x.start != y.start || x.end != y.end || len(x.glyphs) != len(y.glyphs) {
return false
}
for i := range x.glyphs {
g, h := &x.glyphs[i], &y.glyphs[i]
if g.ID != h.ID || g.Font != h.Font || g.Cluster != h.Cluster || g.RTL != h.RTL || g.Y != h.Y ||
math.Abs(float64(g.X-h.X)) > numberTolerance || math.Abs(float64(g.Advance-h.Advance)) > numberTolerance {
return false
}
}
return true
}
+48
View File
@@ -0,0 +1,48 @@
package text
// Core Text's numbers, put together from their characters (numbers.go).
// numberKey is a font of numbers: italic takes another Font of one CTFont.
type numberKey struct {
font uintptr
italic bool
}
// shapeNumber puts text together if it is a number, or returns nil for Core
// Text to shape it.
func (e *coreText) shapeNumber(text []rune, style Style, spans []Span, width float32, rtl bool) []shapedLine {
if !mayBeNumber(text, style, spans, rtl) {
return nil
}
font := e.ctFont(style)
if font == 0 {
return nil
}
key := numberKey{font, style.Italic}
f := e.numbers[key]
if f == nil {
f = &numberFont{}
e.numbers[key] = f
}
// All that is needed, before taking room for the result.
one, ok := f.measure(text, style, width, e.shapeOne)
if !ok {
return nil
}
n := len(text)
glyphs := e.glyphRoom(n)
f.put(text, glyphs)
line := shapedLine{end: n, runs: e.addRun(len(e.shapeScratch.runs), shapedRun{font: one, end: n, glyphs: glyphs})}
lines := e.addLine(len(e.shapeScratch.lines), line)
if shaped := f.check(lines, text, style, width, func() []shapedLine {
return e.shapeText(text, style, nil, width, false, false)
}); shaped != nil {
return shaped
}
return lines
}
// shapeOne has Core Text shape text into one line.
func (e *coreText) shapeOne(text []rune, style Style) []shapedLine {
return e.shapeText(text, style, nil, 0, false, false)
}
+44
View File
@@ -0,0 +1,44 @@
//go:build windows && (amd64 || arm64)
package text
// DirectWrite's numbers, put together from their characters (numbers.go).
// shapeNumber puts text together if it is a number, or returns nil for
// DirectWrite to shape it.
func (e *dwrite) shapeNumber(text []rune, style Style, spans []Span, width float32, rtl bool) []shapedLine {
if !mayBeNumber(text, style, spans, rtl) {
return nil
}
// The text format's key is what DirectWrite shapes with: the family
// list, whose others its fallback tries, the family, weight, style,
// size and language.
family, custom := e.family(style.Family)
key := formatKey{style.Family, family, custom, style.weight(), style.Italic, style.FontSize(), style.Lang}
f := e.numbers[key]
if f == nil {
f = &numberFont{}
e.numbers[key] = f
}
// All that is needed, before taking room for the result.
one, ok := f.measure(text, style, width, e.shapeOne)
if !ok {
return nil
}
n := len(text)
glyphs := e.glyphRoom(n)
f.put(text, glyphs)
line := shapedLine{end: n, runs: e.addRun(len(e.shapeScratch.runs), shapedRun{font: one, end: n, glyphs: glyphs})}
lines := e.addLine(len(e.shapeScratch.lines), line)
if shaped := f.check(lines, text, style, width, func() []shapedLine {
return e.shapeText(text, style, nil, width, false, false)
}); shaped != nil {
return shaped
}
return lines
}
// shapeOne has DirectWrite shape text into one line.
func (e *dwrite) shapeOne(text []rune, style Style) []shapedLine {
return e.shapeText(text, style, nil, 0, false, false)
}
+92
View File
@@ -0,0 +1,92 @@
//go:build windows && (amd64 || arm64)
package text
import (
"strings"
"testing"
)
// Numbers put together are what DirectWrite shapes, in the system's fonts.
func TestDWriteNumbers(t *testing.T) {
numbers := []string{"0", "7", "11", "1,234,567.89", "-42.5%", "+3.14", "$1,000", "1.1.1.1", "$-0.50", "%%", "--", "..", "1+1-1", "00000000000000000000000000000000", "12.345", "98765.4321"}
styles := []Style{{Size: 11}, {Size: 13}, {Size: 13, Weight: 700}, {Size: 14, Italic: true}, {Size: 14, Family: "Consolas"}, {Size: 16, Family: "Arial"}, {Size: 15, Family: "Georgia"}, {Size: 13, Family: "Times New Roman"}, {Size: 13, Lang: "zh-Hans"}, {Size: 13, Lang: "en"}}
s := newSystem()
s.mu.Lock()
defer s.mu.Unlock()
e := s.engine().(*dwrite)
for _, style := range styles {
for _, number := range numbers {
text := []rune(number)
e.resetScratch()
lines := e.shapeNumber(text, style, nil, 0, false)
if lines == nil {
t.Fatalf("%q in %+v was not put together", number, style)
}
if !sameNumber(lines, e.shapeText(text, style, nil, 0, false, false)) {
t.Errorf("%q in %+v put together is not what DirectWrite shapes", number, style)
}
}
}
for _, f := range e.numbers {
if f.disagreed {
t.Error("a font disagreed with DirectWrite")
}
}
}
// What is not a number, wraps, or takes more than its characters' glyphs is
// left to DirectWrite, and a font it disagrees with stays with it.
func TestDWriteNumbersLeftOut(t *testing.T) {
s := newSystem()
s.mu.Lock()
defer s.mu.Unlock()
e := s.engine().(*dwrite)
style := Style{Size: 13}
for _, c := range []struct {
text string
style Style
spans []Span
width float32
rtl bool
}{
{text: "12a", style: style},
{text: "12:30", style: style},
{text: "١٢٣", style: style},
{text: "123", style: style, rtl: true},
{text: "123", style: style, spans: []Span{{End: 1, Weight: 700}}},
{text: "123", style: Style{Size: 13, LetterSpacing: 1}},
{text: "123", style: Style{Size: 13, Features: "tnum"}},
{text: "123", style: Style{Size: 13, Lang: "tr"}},
{text: "123456", style: style, width: 5},
{text: strings.Repeat("1", maxNumber+1), style: style},
} {
e.resetScratch()
if e.shapeNumber([]rune(c.text), c.style, c.spans, c.width, c.rtl) != nil {
t.Errorf("%q in %+v (width %v, RTL %v) was put together", c.text, c.style, c.width, c.rtl)
}
}
text := []rune("42")
e.resetScratch()
want := e.shapeText(text, style, nil, 0, false, false)
wantX := want[0].runs[0].glyphs[1].X
if e.shapeNumber(text, style, nil, 0, false) == nil {
t.Fatal("42 was not put together")
}
family, custom := e.family(style.Family)
f := e.numbers[formatKey{style.Family, family, custom, style.weight(), style.Italic, style.FontSize(), style.Lang}]
f.pairs[numberSlots['4']-1][numberSlots['2']-1].advance += 5
e.resetScratch()
got := e.shapeNumber(text, style, nil, 0, false)
if !f.disagreed {
t.Error("a number wrong by 5 did not count as a disagreement")
}
if x := got[0].runs[0].glyphs[1].X; x != wantX {
t.Errorf("the second digit of a number that disagrees is at %v, DirectWrite puts it at %v", x, wantX)
}
e.resetScratch()
if e.shapeNumber(text, style, nil, 0, false) != nil {
t.Error("a font that disagreed still has numbers put together")
}
}
+163
View File
@@ -0,0 +1,163 @@
package text
import (
"unicode/utf16"
"github.com/egoist/mygo/internal/mobile"
"github.com/egoist/mygo/internal/scene"
)
func newEngine() engine {
e := &paintEngine{fonts: map[paintSpec]*Font{}}
e.clusterEngine.init(e)
return e
}
// paintEngine lays out and draws text with Android's Paint, through the
// host: Minikin finds the fonts, falls back for what one lacks and lays
// words out, Skia draws them, as for a TextView. Its glyphs are grapheme
// clusters (clusterEngine), measured within their words.
type paintEngine struct {
clusterEngine
fonts map[paintSpec]*Font
names []string // the families the app registered fonts under
}
// paintFont is what the engine keeps of a Font (Font.data): the font as the
// host takes it, and the texts of its glyphs, which a layout kept after the
// System let go of the Font still draws.
type paintFont struct {
spec paintSpec
glyphs *glyphTexts
}
// paintSpec is a font as the host takes it.
type paintSpec struct {
family string
size float32
weight int
italic bool
}
func (e *paintEngine) font(style Style) *Font {
key := paintSpec{style.Family, style.FontSize(), style.weight(), style.Italic}
if f, ok := e.fonts[key]; ok {
return f
}
f := &Font{Size: key.size, data: &paintFont{key, e.glyphs}}
m, ok := mobile.TextMetrics(key.family, float64(key.size), key.weight, key.italic)
if ok && m.Ascent > 0 {
f.Ascent, f.Descent = float32(m.Ascent), float32(m.Descent)
f.underlineTop, f.underlineThick = -float32(m.UnderlinePosition), max(float32(m.UnderlineThickness), 0.5)
f.strikeTop, f.strikeThick = float32(m.StrikePosition), f.underlineThick
} else {
f.Ascent, f.Descent = key.size*0.93, key.size*0.24
f.underlineTop, f.underlineThick = -key.size/10, max(key.size/14, 1)
f.strikeTop, f.strikeThick = key.size*0.3, f.underlineThick
}
e.fonts[key] = f
return f
}
func (e *paintEngine) spec(f *Font) paintSpec { return f.data.(*paintFont).spec }
func (e *paintEngine) measure(f *Font, text string, noKern bool) float32 {
s := e.spec(f)
if w := mobile.MeasureText(s.family, float64(s.size), s.weight, s.italic, noKern, []string{text}); len(w) == 1 {
return float32(w[0])
}
return 0
}
// pens lays the word out whole and sums the advances of its clusters'
// UTF-16 units, as Minikin gives them: kerning between clusters goes to
// the one before.
func (e *paintEngine) pens(f *Font, text []rune, bounds []int, noKern bool) []float32 {
s := e.spec(f)
adv := mobile.TextAdvances(s.family, float64(s.size), s.weight, s.italic, noKern, string(text), false)
if len(adv) == 0 {
return nil
}
// The advance of each rune, of its one or two units.
runeAdv := make([]float32, len(text))
u := 0
for i, r := range text {
n := utf16.RuneLen(r)
if n < 1 {
n = 1
}
for k := 0; k < n && u < len(adv); k++ {
runeAdv[i] += float32(adv[u])
u++
}
}
pens := make([]float32, len(bounds))
r := 0
var x float32
for k := 1; k < len(bounds); k++ {
for ; r < bounds[k] && r < len(runeAdv); r++ {
x += runeAdv[r]
}
pens[k] = x
}
return pens
}
func (e *paintEngine) glyph(f *Font, id uint32, scale, dx float32, _ Shade, _ bool) bitmap {
// The texts of the glyphs of f's time: the engine's may be newer.
pf := f.data.(*paintFont)
if int(id) >= len(pf.glyphs.texts) || id == 0 {
return bitmap{}
}
s := pf.spec
r := mobile.DrawText(s.family, float64(s.size), s.weight, s.italic, pf.glyphs.texts[id], float64(scale), float64(dx))
if r.Width <= 0 || r.Height <= 0 {
return bitmap{}
}
return bitmap{left: r.Left, top: r.Top, w: r.Width, h: r.Height, pix: r.Pixels, color: r.Color}
}
// textParams leaves coverage as Skia drew it, without subpixel
// antialiasing, which Android's text has none of.
func (e *paintEngine) textParams() (scene.TextParams, bool) { return scene.TextParams{}, false }
// maxTexts is how many glyphs, texts, the engine keeps before it has the
// System let go of its fonts with them.
const maxPaintTexts = 1 << 16
func (e *paintEngine) fontCount() int {
if len(e.glyphs.texts) > maxPaintTexts {
return maxFonts + 1
}
return len(e.fonts)
}
func (e *paintEngine) forgetFonts() {
clear(e.fonts)
e.forgetGlyphs()
}
// releaseFonts has nothing to release: the host keeps its fonts.
func (e *paintEngine) releaseFonts() {}
func (e *paintEngine) appFamilies() []FontFamily {
out := make([]FontFamily, len(e.names))
for i, n := range e.names {
out[i] = FontFamily{Name: n}
}
return out
}
// systemFamilies lists none: Android tells no families by name, only the
// generic ones.
func (e *paintEngine) systemFamilies() func() []FontFamily { return nil }
func (e *paintEngine) register(data []byte, family string) error {
name, err := mobile.RegisterFont(data, family)
if err != nil {
return err
}
e.names = append(e.names, name)
clear(e.words)
return nil
}
File diff suppressed because it is too large. Load diff
+323
View File
@@ -0,0 +1,323 @@
//go:build linux && !android && (amd64 || arm64) && !android
package text
import (
"bytes"
"fmt"
"os"
"path/filepath"
"reflect"
"sync"
"testing"
)
// Punctuation and full-width forms in a language that writes Han get the
// family the language picks before the generic families (#595), and
// nothing else does.
func TestHanPunctRuns(t *testing.T) {
for _, c := range []struct {
text string
style Style
spans []Span
want []hanRun
}{
{"macOS、Windows、Linux", Style{Lang: "zh-Hans"}, nil, []hanRun{{5, 6, "zh-Hans", ""}, {13, 14, "zh-Hans", ""}}},
{"a(b)c", Style{Lang: "ja", Family: "Inter"}, nil, []hanRun{{1, 2, "ja", "Inter"}, {3, 4, "ja", "Inter"}}},
{"文件、。编辑", Style{Lang: "zh"}, nil, []hanRun{{2, 4, "zh", ""}}},
{"macOS、Windows", Style{Lang: "en"}, nil, nil},
{"macOS、Windows", Style{}, nil, nil},
{"a、b、c", Style{Lang: "en"}, []Span{{End: 2, Lang: "zh-Hant"}, {End: 5}}, []hanRun{{1, 2, "zh-Hant", ""}}},
{"a、、b", Style{Lang: "zh-Hans"}, []Span{{End: 2, Family: "serif"}, {End: 4}}, []hanRun{{1, 2, "zh-Hans", "serif"}, {2, 3, "zh-Hans", ""}}},
} {
if got := hanPunctRuns([]rune(c.text), c.style, c.spans); !reflect.DeepEqual(got, c.want) {
t.Errorf("hanPunctRuns(%q, %+v, %+v) = %v, want %v", c.text, c.style, c.spans, got, c.want)
}
}
}
func TestPangoFamilyBeforeGeneric(t *testing.T) {
before := func(generic string) string { return "CJK " + generic }
for _, c := range []struct{ list, want string }{
{"", "CJK system-ui,UI,system-ui,sans-serif"},
{"sans-serif", "CJK sans-serif,sans-serif"},
{"Inter, monospace, serif", "Inter,CJK monospace,monospace,serif"},
{"Inter", "Inter,CJK system-ui"},
} {
if got := pangoFamily(c.list, "UI", before); got != c.want {
t.Errorf("pangoFamily(%q) = %q, want %q", c.list, got, c.want)
}
if got, want := pangoFamily(c.list, "UI", func(string) string { return "" }), pangoFamily(c.list, "UI", nil); got != want {
t.Errorf("pangoFamily(%q) without a family = %q, want %q", c.list, got, want)
}
}
}
func TestFcHanLang(t *testing.T) {
for tag, want := range map[string]string{
"zh": "zh-cn", "zh-Hans": "zh-cn", "zh-CN": "zh-cn", "zh_CN": "zh-cn", "zh-Hans-SG": "zh-sg", "zh-SG": "zh-sg",
"zh-Hant": "zh-tw", "zh-TW": "zh-tw", "zh-Hant-HK": "zh-hk", "zh-HK": "zh-hk", "zh-MO": "zh-mo", "zh-Hans-HK": "zh-cn",
"yue": "zh-hk", "yue-Hans": "zh-cn", "cmn-Hant-TW": "zh-tw", "ja": "ja", "ja-JP": "ja", "ko-KR": "ko",
} {
if got := fcHanLang(tag); got != want {
t.Errorf("fcHanLang(%q) = %q, want %q", tag, got, want)
}
}
}
// With the system's fonts, an ideographic comma between Latin words in
// Chinese is drawn with the font fontconfig picks for Chinese (#595).
func TestPangoHanPunctBetweenLatin(t *testing.T) {
e, err := newPango()
if err != nil {
t.Skip(err)
}
han := e.hanFamily("zh-Hans", "sans-serif")
if han == "" {
t.Skip("no font for Chinese")
}
want := e.shape([]rune("、"), Style{Family: han, Size: 12, Lang: "zh-Hans"}, nil, 0, false, false)[0].runs[0].font
text := []rune("macOS、Windows")
for _, r := range e.shape(text, Style{Family: "sans-serif", Size: 12, Lang: "zh-Hans"}, nil, 0, false, false)[0].runs {
if r.start <= 5 && 5 < r.end && r.font != want {
t.Errorf("、 drawn with another font than %s's", han)
}
}
}
// A flex item may give text exactly the width of its unconstrained
// layout. Kerning in strings such as "11" must not make Pango wrap it.
func TestPangoLayoutAtMeasuredWidth(t *testing.T) {
s := newSystem()
for _, family := range []string{"sans-serif", "serif", "monospace"} {
for _, size := range []float32{10, 12, 14, 16} {
for _, value := range []string{"11", "10", "12", "1911", "2011", "2111", "2211", "2001", "2002", "2012", "2021", "2011-04-17", "2011-06-17", "11:30", "2.11.1", "AV", "office"} {
t.Run(fmt.Sprintf("%s/%g/%s", family, size, value), func(t *testing.T) {
p := Params{Text: value, Style: Style{Family: family, Size: size}}
p.Width = s.Layout(p).Width
for _, maxLines := range []int{0, 1} {
p.MaxLines = maxLines
l := s.Layout(p)
if len(l.Lines) != 1 || l.Truncated || l.Lines[0].End != len(l.Runes) {
t.Errorf("at measured width %g, MaxLines %d: %d lines, truncated %v, end %d of %d", p.Width, maxLines, len(l.Lines), l.Truncated, l.Lines[0].End, len(l.Runes))
}
}
})
}
}
}
}
// Letter spacing makes a text's measured width fractional, so a flex
// item may lay it out at a width a thousandth of a dip short of its own
// measurement. Truncating the scaled width must not wrap it.
func TestPangoLayoutAtMeasuredWidthWithLetterSpacing(t *testing.T) {
s := newSystem()
for _, spacing := range []float32{0.1, 0.25, 0.5, 1, 1.5} {
for _, value := range []string{"System", "Settings", "Favorites", "Home", "Now Playing"} {
t.Run(fmt.Sprintf("%g/%s", spacing, value), func(t *testing.T) {
p := Params{Text: value, Style: Style{Family: "sans-serif", Size: 14, LetterSpacing: spacing}}
p.Width = s.Layout(p).Width
for _, maxLines := range []int{0, 1} {
p.MaxLines = maxLines
l := s.Layout(p)
if len(l.Lines) != 1 || l.Truncated || l.Lines[0].End != len(l.Runes) {
t.Errorf("at measured width %g, MaxLines %d: %d lines, truncated %v, end %d of %d", p.Width, maxLines, len(l.Lines), l.Truncated, l.Lines[0].End, len(l.Runes))
}
}
})
}
}
}
// Goroutines that write the same font to the cache at once each find the
// whole font there afterwards (#682).
func TestWriteCacheFileConcurrent(t *testing.T) {
data := make([]byte, 1<<20)
for i := range data {
data[i] = byte(i * 7)
}
for round := range 20 {
dir := t.TempDir()
path := filepath.Join(dir, "font.font")
var wg sync.WaitGroup
errs := make([]error, 16)
for i := range errs {
wg.Add(1)
go func() {
defer wg.Done()
if err := writeCacheFile(dir, path, data); err != nil {
errs[i] = err
return
}
got, err := os.ReadFile(path)
if err == nil && !bytes.Equal(got, data) {
err = fmt.Errorf("read %d bytes, not the font's %d", len(got), len(data))
}
errs[i] = err
}()
}
wg.Wait()
for i, err := range errs {
if err != nil {
t.Fatalf("round %d, writer %d: %v", round, i, err)
}
}
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
if len(entries) != 1 {
t.Fatalf("round %d: %d files in the cache, want only the font", round, len(entries))
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if mode := info.Mode().Perm(); mode != 0o644 {
t.Fatalf("round %d: font's mode %v, want 0644", round, mode)
}
}
}
// lcdFilterRule gives subpixel glyphs FreeType's LCD filter where
// fontconfig names no filter, as cairo 1.17 and later do by default, and
// keeps a filter fontconfig names (#1025).
func TestLCDFilterRule(t *testing.T) {
if _, err := newPango(); err != nil {
t.Skip(err)
}
l := &pangoLib
if l.cairoVersion() < 11700 || l.fcConfigParseFromMemory == nil {
t.Skip("needs cairo 1.17 or later, whose default filter is FreeType's")
}
draw := func() []byte {
e, err := newPango()
if err != nil {
t.Fatal(err)
}
e.setFontRendering("subpixel", "slight", "rgb")
var out []byte
for _, r := range e.shape([]rune("Illumination 测试"), Style{Family: "sans-serif", Size: 13}, nil, 0, false, false)[0].runs {
for _, g := range r.glyphs {
if b := e.draw(r.font, g.ID, 1, 0, true); b.pix != nil {
if !b.subpixel {
t.Fatal("glyph not drawn with subpixel antialiasing")
}
out = append(out, b.pix...)
}
}
}
return out
}
// Rules loaded later apply later, as the user's after the system's.
rule := func(xml string) {
t.Helper()
if l.fcConfigParseFromMemory(l.fcConfigGetCurrent(), xml, int32(gTrue)) == 0 {
t.Fatalf("fontconfig refused %s", xml)
}
}
set := func(edit string) string {
return `<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "fonts.dtd"><fontconfig><match target="font">` + edit + `</match></fontconfig>`
}
rule(set(`<edit name="lcdfilter" mode="assign"><const>lcdlegacy</const></edit>`))
legacy := draw()
rule(lcdFilterRule)
if !bytes.Equal(draw(), legacy) {
t.Error("lcdFilterRule replaced the legacy filter fontconfig names")
}
rule(set(`<edit name="lcdfilter" mode="delete"/>`))
unnamed := draw()
if bytes.Equal(unnamed, legacy) {
t.Fatal("cairo draws subpixel glyphs with the legacy filter by default")
}
rule(lcdFilterRule)
if !bytes.Equal(draw(), unnamed) {
t.Error("where fontconfig names no filter, lcdFilterRule draws otherwise than cairo's default")
}
rule(set(`<edit name="lcdfilter" mode="assign"><const>lcddefault</const></edit>`))
if !bytes.Equal(draw(), unnamed) {
t.Error("cairo's default filter is not FreeType's")
}
}
// Where the desktop's settings leave antialiasing to fontconfig (no
// XSETTINGS value) and fontconfig gives fonts subpixel antialiasing
// (rgba), glyphs are drawn in grayscale, not in the colors of their
// subpixels, which made them color glyphs, white whatever the text's
// color (#1426).
func TestGrayGlyphsWhereFontconfigAsksForSubpixels(t *testing.T) {
if _, err := newPango(); err != nil {
t.Skip(err)
}
l := &pangoLib
if l.fcConfigParseFromMemory == nil {
t.Skip("no FcConfigParseAndLoadFromMemory")
}
rgba := `<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "fonts.dtd"><fontconfig><match target="font">` +
`<edit name="rgba" mode="assign"><const>rgb</const></edit></match></fontconfig>`
if l.fcConfigParseFromMemory(l.fcConfigGetCurrent(), rgba, int32(gTrue)) == 0 {
t.Fatalf("fontconfig refused %s", rgba)
}
for _, r := range [][3]string{{"", "", ""}, {"gray", "slight", ""}, {"subpixel", "slight", "rgb"}, {"none", "full", "rgb"}} {
e, err := newPango()
if err != nil {
t.Fatal(err)
}
e.setFontRendering(r[0], r[1], r[2])
_, subpixel := e.textParams()
drawn := 0
for _, run := range e.shape([]rune("Candle 显示右侧边栏"), Style{Family: "sans-serif", Size: 13}, nil, 0, false, false)[0].runs {
for _, g := range run.glyphs {
b := e.glyph(run.font, g.ID, 1, 0, 0, subpixel)
if b.pix == nil {
continue
}
drawn++
if b.color {
t.Errorf("settings %q: glyph %d drawn as a color glyph", r, g.ID)
}
if b.subpixel != subpixel {
t.Errorf("settings %q: glyph %d drawn with subpixels %v, want %v", r, g.ID, b.subpixel, subpixel)
}
}
}
if drawn == 0 {
t.Skip("no glyphs drawn")
}
}
}
func TestGrayscaleFontPreservesColorGlyphs(t *testing.T) {
e, err := newPango()
if err != nil {
t.Skip(err)
}
found := false
for _, f := range e.fontMapFamilies() {
if f.Name == "Noto Color Emoji" {
found = true
break
}
}
if !found {
t.Skip("needs Noto Color Emoji")
}
e.setFontRendering("gray", "slight", "rgb")
drawn := 0
for _, run := range e.shape([]rune("😀"), Style{Family: "Noto Color Emoji", Size: 20}, nil, 0, false, false)[0].runs {
for _, g := range run.glyphs {
b := e.glyph(run.font, g.ID, 1, 0, 0, false)
if b.pix == nil {
continue
}
drawn++
if !b.color || b.subpixel {
t.Errorf("emoji glyph %d: color=%v, subpixel=%v", g.ID, b.color, b.subpixel)
}
}
}
if drawn == 0 {
t.Fatal("no emoji glyphs drawn")
}
}
+509
View File
@@ -0,0 +1,509 @@
package text
import (
"math"
"slices"
"unicode"
"github.com/go-text/typesetting/segmenter"
)
// softHyphen is a break opportunity that shows as a hyphen where a line
// breaks at it, and as nothing elsewhere.
const softHyphen = '\u00AD'
// breakLines breaks text, a paragraph without newlines, into lines of at
// most width DIPs (one line when 0), the first indent narrower, and shapes
// them with the engine, which breaks at one width. A line that breaks at
// a soft hyphen ends with a hyphen, for which only Pango leaves room: one
// that does not fit with it is broken again, narrower by the hyphen.
// So is a line that does not fit with the padding of its spans' pieces
// (Span.PaddingX), which engines know nothing of: narrower by it.
// What follows the indented line, or a line that broke elsewhere then, is
// broken anew: a paragraph without either is shaped once. hy is nil for a
// text without soft hyphens.
func (s *System) breakLines(text []rune, style Style, spans []Span, width, indent float32, rtl, wholeWords bool, hy *hyphens) []shapedLine {
e := s.engine()
if width <= 0 {
return e.shape(text, style, spans, 0, rtl, wholeWords)
}
pads := padded(spans)
if indent <= 0 && hy == nil && !pads {
return e.shape(text, style, spans, width, rtl, wholeWords)
}
var out []shapedLine
for pos := 0; pos < len(text); {
limit, first := width, len(out) == 0 && indent > 0
if first {
limit = max(width-indent, 1)
}
lines := e.shape(text[pos:], style, spansIn(spans, pos, len(text)), limit, rtl, wholeWords)
if len(lines) == 0 {
break
}
if first {
// The lines after the first are for the width.
lines = lines[:1]
}
offsetLines(lines, pos)
for _, l := range lines {
if c := softBreak(l, text); c >= 0 && hy != nil && hy.lineWidth(l, text, c) > limit+1e-3 {
narrow := e.shape(text[l.start:l.end], style, spansIn(spans, l.start, l.end), max(limit-hy.width(c), 1), rtl, wholeWords)
if len(narrow) > 0 && narrow[0].end != l.end && hy.opportunity(text, l.start+narrow[0].end) {
offsetLines(narrow[:1], l.start)
out = append(out, narrow[0])
break
}
// Nothing before fits but a part of a word: the hyphen
// overflows, as a word too long for a line does.
}
if pads {
if w, pad := paddedWidth(l, text, spans); w+pad > limit+1e-3 {
narrow := e.shape(text[l.start:l.end], style, spansIn(spans, l.start, l.end), max(limit-pad, 1), rtl, wholeWords)
if len(narrow) > 0 && narrow[0].end > 0 && narrow[0].end != l.end-l.start {
offsetLines(narrow[:1], l.start)
out = append(out, narrow[0])
break
}
// Its one word overflows with its padding, as without.
}
}
out = append(out, l)
}
end := out[len(out)-1].end
if end <= pos {
break
}
pos = end
}
return out
}
// padded reports whether a span pads its pieces of lines (Span.PaddingX,
// Span.PaddingStart).
func padded(spans []Span) bool {
for _, sp := range spans {
if sp.PaddingX > 0 || sp.PaddingStart > 0 {
return true
}
}
return false
}
// padEnd returns the padding of span k at the logical end of its pieces
// of lines, 0 past the spans.
func padEnd(spans []Span, k int) float32 {
if k < 0 || k >= len(spans) {
return 0
}
return max(spans[k].PaddingX, 0)
}
// padBegin returns the padding of span k at the logical start of its
// pieces of lines, PaddingStart with PaddingX, 0 past the spans. Where only
// the width counts, a piece takes padBegin and padEnd whatever its
// direction.
func padBegin(spans []Span, k int) float32 {
if k < 0 || k >= len(spans) {
return 0
}
return max(spans[k].PaddingX, 0) + max(spans[k].PaddingStart, 0)
}
// padSide returns the padding of span k at the visual left (left true) or
// right of a piece of it whose glyphs run right to left when rtl: the
// start, which has PaddingStart, is the left of a left-to-right piece and
// the right of a right-to-left one.
func padSide(spans []Span, k int, left, rtl bool) float32 {
if left != rtl {
return padBegin(spans, k)
}
return padEnd(spans, k)
}
// paddedWidth returns the width of the glyphs of a shaped line of a
// paragraph text, the whitespace ending it left out, and the padding of
// its spans' pieces.
func paddedWidth(l shapedLine, text []rune, spans []Span) (w, pad float32) {
trim := l.end
for trim > l.start && hangs(text[trim-1]) {
trim--
}
k := -1
for _, r := range l.runs {
for _, g := range r.glyphs {
if g.Cluster >= trim && g.Cluster < l.end {
continue
}
w += g.Advance
if g.Cluster < 0 {
continue // the ellipsis, with the glyphs before it
}
if j := spanIndex(spans, g.Cluster); j != k {
pad += padEnd(spans, k) + padBegin(spans, j)
k = j
}
}
}
return w, pad + padEnd(spans, k)
}
// padLine moves the glyphs of a line, in visual order, apart by the
// padding of its spans' pieces, at both ends of each, as CSS pads each
// line's fragment of an inline box with box-decoration-break: clone, and
// widens the line by it. A piece's PaddingStart goes on the side its
// direction starts at. The line's runes start at rune offset of the
// spans' text.
func padLine(line *Line, spans []Span, offset int) {
dx, k, rtl := float32(0), -1, false
for i := range line.Glyphs {
g := &line.Glyphs[i]
// The ellipsis goes with the glyphs before it.
if g.Runes > 0 {
if j := spanIndex(spans, g.Cluster-offset); j != k {
dx += padSide(spans, k, false, rtl) + padSide(spans, j, true, g.RTL)
k, rtl = j, g.RTL
}
}
g.X += dx
}
dx += padSide(spans, k, false, rtl)
line.Width += dx
line.padding = dx
}
// offsetLines moves lines an engine shaped from rune offset of a
// paragraph to their places in it.
func offsetLines(lines []shapedLine, offset int) {
if offset == 0 {
return
}
for i := range lines {
l := &lines[i]
l.start += offset
l.end += offset
for j := range l.runs {
r := &l.runs[j]
r.start += offset
r.end += offset
for k := range r.glyphs {
if r.glyphs[k].Cluster >= 0 {
r.glyphs[k].Cluster += offset
}
}
}
}
}
// softBreak returns the soft hyphen a line of a paragraph text breaks
// after, or -1 when it ends otherwise.
func softBreak(l shapedLine, text []rune) int {
if l.end > l.start && l.end < len(text) && text[l.end-1] == softHyphen {
return l.end - 1
}
return -1
}
// hyphens shapes the hyphens that soft hyphens show as where lines break,
// in the style of each, once a paragraph.
type hyphens struct {
e engine
style Style
spans []Span
// glyphs holds the hyphen of each span, by its index, len(spans) for
// the text's style.
glyphs map[int][]Glyph
// opps tells where the paragraph's lines may break, once asked.
opps []bool
}
// opportunity reports whether a line of the paragraph text may break
// before rune i, as Unicode's line breaking algorithm says.
func (h *hyphens) opportunity(text []rune, i int) bool {
if h.opps == nil {
var seg segmenter.Segmenter
h.opps = lineBreaks(&seg, nil, text)
}
return i >= 0 && i < len(h.opps) && h.opps[i]
}
// at returns the glyphs of the hyphen of rune i, from a pen at 0.
func (h *hyphens) at(i int) []Glyph {
k := spanIndex(h.spans, i)
if g, ok := h.glyphs[k]; ok {
return g
}
style := h.style
if k < len(h.spans) {
style = h.spans[k].style(style)
}
// U+2010 HYPHEN would be the better glyph, but fonts lack it more
// often than U+002D, which every one has.
var out []Glyph
for _, l := range h.e.shape([]rune{'-'}, style, nil, 0, false, false) {
for _, r := range l.runs {
out = append(out, r.glyphs...)
}
}
if h.glyphs == nil {
h.glyphs = map[int][]Glyph{}
}
h.glyphs[k] = out
return out
}
// width returns the advance of the hyphen of rune i.
func (h *hyphens) width(i int) float32 {
var w float32
for _, g := range h.at(i) {
w += g.Advance
}
return w
}
// lineWidth returns the width of a line of the paragraph text ending
// with the soft hyphen c, once its hyphen shows and its other soft
// hyphens take no room.
func (h *hyphens) lineWidth(l shapedLine, text []rune, c int) float32 {
w := h.width(c)
for _, r := range l.runs {
for _, g := range r.glyphs {
if g.Cluster < 0 || g.Cluster >= len(text) || text[g.Cluster] != softHyphen {
w += g.Advance
}
}
}
return w
}
// place makes the soft hyphens of a shaped line of a paragraph text show
// as Unicode says, whatever the engine made of them: a hyphen for the one
// the line breaks after, when broken, and nothing, taking no room, for
// the others. The glyphs after one move by the room it takes or gives.
// rtl is the paragraph's direction, whose end a hyphen goes to when the
// engine gave its soft hyphen no glyph.
func (h *hyphens) place(l shapedLine, text []rune, broken, rtl bool) shapedLine {
placed := false
for ri := range l.runs {
gs := l.runs[ri].glyphs
for j := 0; j < len(gs); j++ {
c := gs[j].Cluster
if c < 0 || c >= len(text) || text[c] != softHyphen {
continue
}
// Its cluster's glyphs, as the empty glyph and the hyphen Pango
// gives one it breaks at.
k := j + 1
for k < len(gs) && gs[k].Cluster == c {
k++
}
left, was := gs[j].X, float32(0)
for _, g := range gs[j:k] {
left = min(left, g.X)
was += g.Advance
}
glyphRTL := gs[j].RTL
var now float32
var with []Glyph
if broken && c == l.end-1 {
with, now = h.glyphsAt(c, left, glyphRTL), h.width(c)
placed = true
}
if len(with) == 0 {
// A glyph of no font draws nothing, and keeps the caret's
// place.
with = []Glyph{{X: left, Cluster: c, RTL: glyphRTL}}
}
if d := now - was; d != 0 {
for rk := range l.runs {
for gk := range l.runs[rk].glyphs {
if g := &l.runs[rk].glyphs[gk]; (rk != ri || gk < j || gk >= k) && g.X >= left+was/2 {
g.X += d
}
}
}
}
gs = slices.Concat(gs[:j], with, gs[k:])
l.runs[ri].glyphs = gs
j += len(with) - 1
}
}
if broken && !placed && len(l.runs) > 0 {
// The engine left the soft hyphen ending the line out, as a
// character nothing shows: its hyphen ends the line.
c := l.end - 1
x0, x1 := float32(math.MaxFloat32), float32(-math.MaxFloat32)
for _, r := range l.runs {
for _, g := range r.glyphs {
x0, x1 = min(x0, g.X), max(x1, g.X+g.Advance)
}
}
x := x1
if x0 > x1 {
x = 0
} else if rtl {
x = x0 - h.width(c)
}
// In the run of the soft hyphen, whose clusters end at it.
ri := len(l.runs) - 1
for i, r := range l.runs {
if r.start <= c && c < r.end {
ri = i
}
}
l.runs[ri].glyphs = slices.Concat(l.runs[ri].glyphs, h.glyphsAt(c, x, rtl))
placed = true
}
if placed {
inVisualOrder(&l, l.end-1)
}
return l
}
// inVisualOrder moves the glyphs of cluster c, a hyphen the line shows
// where the engine left its soft hyphen, among the glyphs of the line to
// where it shows, keeping them in visual order: in a right-to-left run
// or line, the hyphen, which ends it, is at its left, and the engine may
// have given its soft hyphen a run, or a place in one, of its own.
func inVisualOrder(l *shapedLine, c int) {
var hy []Glyph
for ri := range l.runs {
l.runs[ri].glyphs = slices.DeleteFunc(l.runs[ri].glyphs, func(g Glyph) bool {
if g.Cluster == c {
hy = append(hy, g)
return true
}
return false
})
}
if len(hy) == 0 {
return
}
x := hy[0].X
for _, g := range hy {
x = min(x, g.X)
}
// Before the first glyph right of it.
for ri := range l.runs {
gs := l.runs[ri].glyphs
for j, g := range gs {
if g.X > x {
l.runs[ri].glyphs = slices.Concat(gs[:j], hy, gs[j:])
return
}
}
}
last := len(l.runs) - 1
l.runs[last].glyphs = append(l.runs[last].glyphs, hy...)
}
// glyphsAt returns the glyphs of the hyphen of rune i, standing for it,
// from a pen at x.
func (h *hyphens) glyphsAt(i int, x float32, rtl bool) []Glyph {
var out []Glyph
for _, g := range h.at(i) {
g.X += x
g.Cluster, g.RTL = i, rtl
out = append(out, g)
}
return out
}
// justifyLine stretches a line of a layout of runes to width DIPs, the
// whitespace ending it left out, widening its spaces between words and
// the room after its Han characters and kana but the last, by as much
// each. It returns the left of what it stretched, relative to the line,
// which whitespace ending a right-to-left line may be left of, and
// false, leaving the line as it was, when the line has nothing to widen
// or is that wide already.
func justifyLine(line *Line, runes []rune, width float32) (left float32, ok bool) {
end := line.End
for end > line.Start && hangs(runes[end-1]) {
end--
}
// The extent of each cluster of what stretches, by its first rune,
// and the glyph of each that widens, its rightmost.
type cluster struct {
x0, x1 float32
wide int
}
clusters := make([]cluster, end-line.Start)
seen := make([]bool, end-line.Start)
// The padding of spans' pieces takes room as the glyphs do.
content := line.padding
last := -1
left = float32(1e30)
for i, g := range line.Glyphs {
c := g.Cluster - line.Start
if c < 0 || c >= len(clusters) {
continue
}
content += g.Advance
left = min(left, g.X)
last = max(last, c)
cl := &clusters[c]
if !seen[c] {
seen[c] = true
*cl = cluster{g.X, g.X + g.Advance, i}
continue
}
cl.x0 = min(cl.x0, g.X)
if g.X+g.Advance >= cl.x1 {
cl.x1, cl.wide = g.X+g.Advance, i
}
}
extra := width - content
if extra <= 1e-3 {
return 0, false
}
var opps []float32 // the middles of the clusters that widen
for c := range clusters {
if seen[c] && c != last && stretches(runes[line.Start+c]) {
opps = append(opps, (clusters[c].x0+clusters[c].x1)/2)
}
}
if len(opps) == 0 {
return 0, false
}
each := extra / float32(len(opps))
// Each glyph moves by the room the clusters left of it gain: a cluster
// right of the line's content, as whitespace ending it, moves too.
// Lines have few of them: each glyph counts those left of it, rather
// than a sort, which would grow every app.
for i := range line.Glyphs {
g := &line.Glyphs[i]
mid := g.X + g.Advance/2
if c := g.Cluster - line.Start; c >= 0 && c < len(clusters) && seen[c] {
mid = (clusters[c].x0 + clusters[c].x1) / 2
}
n := 0
for _, o := range opps {
if o < mid {
n++
}
}
g.X += each * float32(n)
}
for c := range clusters {
if seen[c] && c != last && stretches(runes[line.Start+c]) {
line.Glyphs[clusters[c].wide].Advance += each
}
}
// No cluster that widens is left of the content's leftmost: it stays.
line.Width += extra
return left, true
}
// stretches reports whether justified lines widen the room after a rune:
// a space between words, as CSS's word separators, or a Han character,
// kana or the punctuation written with them, which lines of Chinese and
// Japanese text take apart.
func stretches(r rune) bool {
switch {
case r == ' ' || r == ' ' || r == '፡' || r == ' ':
return true
case r >= 0x3001 && r <= 0x303F, r >= 0xFF01 && r <= 0xFF60:
return true
}
return unicode.In(r, unicode.Han, unicode.Hiragana, unicode.Katakana, unicode.Bopomofo)
}
+453
View File
@@ -0,0 +1,453 @@
package text
import (
"math"
"slices"
"strings"
"testing"
)
// breakEngine breaks lines greedily after spaces and soft hyphens, as the
// system's engines do, leaving no room for the hyphen of a line broken at
// a soft hyphen, as all but Pango do. Every rune is 10 DIPs wide but soft
// hyphens, which are shy wide; a space ending a line takes no room, and
// a word wider than a line breaks between its runes.
type breakEngine struct {
stubEngine
shy float32
// omit leaves soft hyphens without a glyph, as an engine may.
omit bool
// shaped counts the runes shape shaped.
shaped int
}
func (e *breakEngine) shape(text []rune, style Style, spans []Span, width float32, rtl, wholeWords bool) []shapedLine {
e.shaped += len(text)
f := e.font(style)
adv := func(r rune) float32 {
if r == softHyphen {
return e.shy
}
return 10
}
var lines []shapedLine
for start := 0; start < len(text); {
end := len(text)
if width > 0 {
w, opp, i := float32(0), -1, start
for ; i < len(text); i++ {
if text[i] != ' ' && w+adv(text[i]) > width+1e-3 {
break
}
w += adv(text[i])
if text[i] == ' ' || text[i] == softHyphen {
opp = i + 1
}
}
if i < len(text) {
end = opp
if end <= start {
end = max(i, start+1)
}
}
}
run := shapedRun{font: f, start: start, end: end}
x := float32(0)
for i := start; i < end; i++ {
if e.omit && text[i] == softHyphen {
continue
}
run.glyphs = append(run.glyphs, Glyph{Font: f, ID: uint32(text[i]), X: x, Advance: adv(text[i]), Cluster: i, RTL: rtl})
x += adv(text[i])
}
lines = append(lines, shapedLine{start: start, end: end, runs: []shapedRun{run}})
start = end
}
return lines
}
func breakSystem(shy float32) *System {
s := newSystem()
s.eng = &breakEngine{shy: shy}
s.UseJustify()
return s
}
// lineText returns the runes of a line of a layout.
func lineText(l *Layout, i int) string { return string(l.Runes[l.Lines[i].Start:l.Lines[i].End]) }
// glyphsOf returns the glyphs of rune r in a line.
func glyphsOf(line Line, r int) []Glyph {
var out []Glyph
for _, g := range line.Glyphs {
if g.Cluster == r {
out = append(out, g)
}
}
return out
}
// TestSoftHyphens breaks lines at soft hyphens, showing a hyphen there
// and nothing elsewhere, and breaks a line again where its hyphen would
// not fit, which all engines but Pango leave no room for.
func TestSoftHyphens(t *testing.T) {
for _, shy := range []float32{0, 5} {
s := breakSystem(shy)
// Whole, the soft hyphens take no room.
whole := s.Layout(Params{Text: "ab\u00ADcd", Style: Style{Size: 10}})
if whole.Width != 40 || len(whole.Lines) != 1 {
t.Fatalf("shy %v: unbroken, %d lines %v wide, want one of 40", shy, len(whole.Lines), whole.Width)
}
if g := glyphsOf(whole.Lines[0], 2); len(g) != 1 || g[0].Font != nil || g[0].Advance != 0 || g[0].X != 20 {
t.Errorf("shy %v: an unbroken soft hyphen is %+v", shy, g)
}
if g := glyphsOf(whole.Lines[0], 3); len(g) != 1 || g[0].X != 20 {
t.Errorf("shy %v: the rune after it is %+v", shy, g)
}
// "aaaa-" fits 50 with its hyphen.
l := s.Layout(Params{Text: "aaaa\u00ADbbbb cc", Style: Style{Size: 10}, Width: 50})
if len(l.Lines) != 3 || lineText(l, 0) != "aaaa\u00AD" || lineText(l, 1) != "bbbb " {
t.Fatalf("shy %v: lines %q", shy, []string{lineText(l, 0), lineText(l, 1)})
}
hy := glyphsOf(l.Lines[0], 4)
if len(hy) != 1 || hy[0].ID != '-' || hy[0].Advance != 10 || hy[0].X != 40 || l.Lines[0].Width != 50 {
t.Errorf("shy %v: the hyphen is %+v, the line %v wide", shy, hy, l.Lines[0].Width)
}
// At 45, "aa\u00ADaa-" does not fit: the line breaks at the first.
l = s.Layout(Params{Text: "aa\u00ADaa\u00ADbbbb", Style: Style{Size: 10}, Width: 45})
var got []string
for i := range l.Lines {
got = append(got, lineText(l, i))
if l.Lines[i].Width > 45 {
t.Errorf("shy %v: line %d is %v wide", shy, i, l.Lines[i].Width)
}
}
if want := []string{"aa\u00AD", "aa\u00AD", "bbbb"}; !slices.Equal(got, want) {
t.Errorf("shy %v: lines %q, want %q", shy, got, want)
}
for i := range 2 {
if hy := glyphsOf(l.Lines[i], l.Lines[i].End-1); len(hy) != 1 || hy[0].ID != '-' {
t.Errorf("shy %v: line %d ends with %+v", shy, i, hy)
}
}
// A line whose part of a word alone fits beside the hyphen keeps
// the word whole, its hyphen overflowing.
l = s.Layout(Params{Text: "aaaa\u00ADbb", Style: Style{Size: 10}, Width: 45})
if len(l.Lines) != 2 || lineText(l, 0) != "aaaa\u00AD" || l.Lines[0].Width != 50 {
t.Errorf("shy %v: %d lines, the first %q %v wide", shy, len(l.Lines), lineText(l, 0), l.Lines[0].Width)
}
// Lines whose hyphens overflow shape their own runes again, not
// the rest of the paragraph.
e := s.eng.(*breakEngine)
e.shaped = 0
l = s.Layout(Params{Text: strings.Repeat("a\u00AD", 20) + "a", Style: Style{Size: 10}, Width: 15})
if len(l.Lines) != 21 || e.shaped > 3*41 {
t.Errorf("shy %v: %d lines, shaping %d runes", shy, len(l.Lines), e.shaped)
}
// An engine that gives soft hyphens no glyph gets the hyphen too.
om := breakSystem(shy)
om.eng.(*breakEngine).omit = true
l = om.Layout(Params{Text: "aaaa\u00ADbbbb cc", Style: Style{Size: 10}, Width: 50})
if hy := glyphsOf(l.Lines[0], 4); len(hy) != 1 || hy[0].ID != '-' || hy[0].X != 40 || l.Lines[0].Width != 50 {
t.Errorf("shy %v: without a glyph, the hyphen is %+v, the line %v wide", shy, hy, l.Lines[0].Width)
}
if a := glyphsOf(l.Lines[0], 3); len(a) != 1 || a[0].Runes != 1 {
t.Errorf("shy %v: the rune before the hyphen is %+v", shy, a)
}
// Carets step over the hidden soft hyphen as over nothing.
l = s.Layout(Params{Text: "ab\u00ADcd", Style: Style{Size: 10}})
if x2, _, _ := l.Caret(2); x2 != 20 {
t.Errorf("shy %v: caret before the soft hyphen at %v", shy, x2)
}
if x3, _, _ := l.Caret(3); x3 != 20 {
t.Errorf("shy %v: caret after the soft hyphen at %v", shy, x3)
}
}
}
// TestSoftHyphensOfEngine checks the system's engine: soft hyphens show
// as hyphens where lines break at them, as nothing elsewhere, and lines
// fit their width with them.
func TestSoftHyphensOfEngine(t *testing.T) {
s := Shared()
const text = "extra\u00ADordinary\u00ADthings hap\u00ADpen"
plain := s.Layout(Params{Text: strings.ReplaceAll(text, "\u00AD", ""), Style: Style{Size: 16}})
whole := s.Layout(Params{Text: text, Style: Style{Size: 16}})
if math.Abs(float64(whole.Width-plain.Width)) > 1.5 {
t.Errorf("unbroken, the text is %v wide, %v without its soft hyphens", whole.Width, plain.Width)
}
hyphens := 0
for w := float32(60); w <= 260; w += 5 {
l := s.Layout(Params{Text: text, Style: Style{Size: 16}, Width: w})
for i, line := range l.Lines {
// A line broken at a soft hyphen with no other place to break
// may overflow, as a word too long for a line does: at 60,
// DirectWrite fits "ordinary" but not "ordinary-", and Core
// Text neither.
word := i < len(l.Lines)-1 && line.End > line.Start && l.Runes[line.End-1] == softHyphen &&
!strings.ContainsAny(string(l.Runes[line.Start:line.End-1]), " \u00AD")
if line.Width > w+0.5 && !word {
t.Errorf("at %v, line %d (%q) is %v wide", w, i, lineText(l, i), line.Width)
}
for r := line.Start; r < line.End; r++ {
if l.Runes[r] != softHyphen {
continue
}
broken := r == line.End-1 && i < len(l.Lines)-1
for _, g := range glyphsOf(line, r) {
if shows := g.Font != nil && g.Advance > 0; shows != broken {
t.Errorf("at %v, the soft hyphen ending line %d (%q) shows: %v", w, i, lineText(l, i), shows)
}
}
if broken {
hyphens++
}
}
}
}
if hyphens == 0 {
t.Error("no line broke at a soft hyphen")
}
}
// TestIndent moves the first line in by Params.Indent and wraps it that
// much narrower, on the side its paragraph starts.
func TestIndent(t *testing.T) {
s := breakSystem(0)
l := s.Layout(Params{Text: "aaa bbb ccc ddd", Style: Style{Size: 10}, Width: 80, Indent: 25})
var got []string
for i := range l.Lines {
got = append(got, lineText(l, i))
}
if want := []string{"aaa ", "bbb ccc ", "ddd"}; !slices.Equal(got, want) {
t.Fatalf("lines %q, want %q", got, want)
}
if l.Lines[0].X != 25 || l.Lines[1].X != 0 || l.Lines[2].X != 0 {
t.Errorf("lines at %v, %v and %v", l.Lines[0].X, l.Lines[1].X, l.Lines[2].X)
}
if x, _, _ := l.Caret(0); x != 25 {
t.Errorf("the caret at the start is at %v", x)
}
// Unwrapped, the indent takes room.
if l := s.Layout(Params{Text: "aaa", Style: Style{Size: 10}, Indent: 25}); l.Width != 55 || l.Lines[0].X != 25 {
t.Errorf("one line %v wide at %v", l.Width, l.Lines[0].X)
}
// Centered, the first line goes to the middle of the room beside it.
if l := s.Layout(Params{Text: "aaa", Style: Style{Size: 10}, Width: 100, Indent: 20, Align: Center}); l.Lines[0].X != 45 {
t.Errorf("centered at %v, want 45", l.Lines[0].X)
}
// Cut short, the first line ends with its ellipsis beside the indent.
if l := s.Layout(Params{Text: "aaaa bbbb cccc", Style: Style{Size: 10}, Width: 60, Indent: 20, MaxLines: 1}); !l.Truncated || l.Lines[0].Width > 40 || l.Lines[0].X != 20 {
t.Errorf("cut short, the line %v wide at %v", l.Lines[0].Width, l.Lines[0].X)
}
// Only the first paragraph's first line.
if l := s.Layout(Params{Text: "a\nb", Style: Style{Size: 10}, Indent: 20}); l.Lines[0].X != 20 || l.Lines[1].X != 0 {
t.Errorf("paragraphs at %v and %v", l.Lines[0].X, l.Lines[1].X)
}
// The system's engine, either way.
sys := Shared()
long := strings.Repeat("The quick brown fox jumps over the lazy dog. ", 3)
in := sys.Layout(Params{Text: long, Style: Style{Size: 16}, Width: 200, Indent: 40})
if first := in.Lines[0]; first.X != 40 || first.Width > 160.5 || in.Lines[1].X != 0 {
t.Errorf("the first line %v wide at %v, the second at %v", first.Width, first.X, in.Lines[1].X)
}
rtl := sys.Layout(Params{Text: strings.Repeat("שלום עולם ", 6), Style: Style{Size: 16}, Width: 200, Indent: 40})
if first := rtl.Lines[0]; !first.RTL || first.X+first.Width > 160.01 || first.X+first.Width < 159.99 || rtl.Lines[1].X+rtl.Lines[1].Width < 199.99 {
t.Errorf("right to left, the first line ends at %v, the second at %v", first.X+first.Width, rtl.Lines[1].X+rtl.Lines[1].Width)
}
}
// TestJustify stretches the lines but the last of each paragraph to the
// width by their spaces.
func TestJustify(t *testing.T) {
s := breakSystem(0)
p := Params{Text: "aaa bbb ccc ddd\naa bb", Style: Style{Size: 10}, Width: 100, Justify: true}
l := s.Layout(p)
if len(l.Lines) != 3 || lineText(l, 0) != "aaa bbb " {
t.Fatalf("%d lines, the first %q", len(l.Lines), lineText(l, 0))
}
first := l.Lines[0]
if first.X != 0 || first.Width != 100 {
t.Errorf("the first line %v wide at %v", first.Width, first.X)
}
if b := glyphsOf(first, 4); len(b) != 1 || b[0].X != 70 {
t.Errorf("the second word at %+v", b)
}
if sp := glyphsOf(first, 3); len(sp) != 1 || sp[0].Advance != 40 {
t.Errorf("the space %+v", sp)
}
if x, _, _ := l.Caret(4); x != 70 {
t.Errorf("the caret before the second word is at %v", x)
}
for i := 1; i < 3; i++ {
if line := l.Lines[i]; line.X != 0 || line.Width != 70 && line.Width != 50 {
t.Errorf("the last line %d of a paragraph %v wide at %v", i, line.Width, line.X)
}
}
// Centered, the last lines are.
p.Align = Center
if l := s.Layout(p); l.Lines[0].X != 0 || l.Lines[1].X != 15 {
t.Errorf("centered, the lines at %v and %v", l.Lines[0].X, l.Lines[1].X)
}
// Spaces kept hang past the width.
p.Align, p.KeepSpaces = Start, true
if l := s.Layout(p); l.Lines[0].Width != 110 || glyphsOf(l.Lines[0], 4)[0].X != 70 || l.Width != 110 {
t.Errorf("keeping spaces, the first line is %v wide, the text %v", l.Lines[0].Width, l.Width)
}
// The text is as wide as its lines stretched.
if l := s.Layout(Params{Text: "aaa bbb cccc", Style: Style{Size: 10}, Width: 100, Justify: true}); l.Width != 100 {
t.Errorf("justified, the text is %v wide", l.Width)
}
// Indented, the first line fills the room beside its indent.
p.KeepSpaces, p.Indent = false, 10
if l := s.Layout(p); l.Lines[0].X != 10 || l.Lines[0].Width != 90 {
t.Errorf("indented, the first line %v wide at %v", l.Lines[0].Width, l.Lines[0].X)
}
// A line without spaces stays as it is.
if l := s.Layout(Params{Text: "aaaaaaaaaaaa", Style: Style{Size: 10}, Width: 75, Justify: true}); l.Lines[0].Width != 70 {
t.Errorf("a word broken is %v wide", l.Lines[0].Width)
}
// Not linked in, Justify does nothing.
plain := newSystem()
plain.eng = &breakEngine{}
if l := plain.Layout(Params{Text: "aaa bbb ccc", Style: Style{Size: 10}, Width: 100, Justify: true}); l.Lines[0].Width != 70 {
t.Errorf("without UseJustify, the first line is %v wide", l.Lines[0].Width)
}
// The system's engine.
sys := Shared()
sys.UseJustify()
long := strings.Repeat("The quick brown fox jumps over the lazy dog. ", 4)
lj := sys.Layout(Params{Text: long, Style: Style{Size: 16}, Width: 230, Justify: true})
for i, line := range lj.Lines[:len(lj.Lines)-1] {
if right := line.X + line.Width; line.X != 0 || right < 229.99 || right > 230.01 {
t.Errorf("line %d from %v to %v", i, line.X, right)
}
}
prev := float32(-1)
for i := 0; i <= len(lj.Runes); i++ {
x, y, _ := lj.Caret(i)
if li := lj.LineAt(i); i > 0 && lj.Lines[li].Start == i {
prev = -1
}
if x < prev {
t.Fatalf("caret %d at %v, %v, after %v", i, x, y, prev)
}
prev = x
}
}
// TestJustifyCJK widens the room after Han characters and kana, but the
// last, in lines without spaces.
func TestJustifyCJK(t *testing.T) {
runes := []rune("日本語です")
line := Line{Start: 0, End: len(runes), Width: 50}
for i := range runes {
line.Glyphs = append(line.Glyphs, Glyph{X: float32(i) * 10, Advance: 10, Cluster: i, Runes: 1})
}
left, ok := justifyLine(&line, runes, 90)
if !ok || left != 0 || line.Width != 90 {
t.Fatalf("justified %v, %v wide, from %v", ok, line.Width, left)
}
for i, g := range line.Glyphs {
if g.X != float32(i)*20 {
t.Errorf("glyph %d at %v, want %v", i, g.X, i*20)
}
}
if line.Glyphs[4].Advance != 10 {
t.Errorf("the last glyph widened to %v", line.Glyphs[4].Advance)
}
}
// TestBaselineShift raises and lowers spans, which the line makes room
// for, and their decorations with them.
func TestBaselineShift(t *testing.T) {
s := Shared()
plain := s.Layout(Params{Text: "x2 H2O", Style: Style{Size: 16}})
spans := []Span{{End: 1}, {End: 2, Size: 10, BaselineShift: 7}, {End: 4}, {End: 5, Size: 10, BaselineShift: -4}}
l := s.Layout(Params{Text: "x2 H2O", Style: Style{Size: 16}, Spans: EncodeSpans(spans)})
line := l.Lines[0]
sup, sub, x := glyphsOf(line, 1)[0], glyphsOf(line, 4)[0], glyphsOf(line, 0)[0]
if x.Y != line.Baseline || sup.Y != line.Baseline-7 || sub.Y != line.Baseline+4 {
t.Errorf("baselines %v, %v and %v of the line's %v", x.Y, sup.Y, sub.Y, line.Baseline)
}
if line.Ascent < sup.Font.Ascent+7 || line.Descent < sub.Font.Descent+4 {
t.Errorf("ascent %v and descent %v for a superscript of ascent %v and a subscript of descent %v", line.Ascent, line.Descent, sup.Font.Ascent, sub.Font.Descent)
}
if l.Height <= plain.Height {
t.Errorf("shifted, the text is %v high, %v without", l.Height, plain.Height)
}
// Decorations follow the span.
under := func(l *Layout, i int) float32 {
st := s.Decorate(l, 0, i, i+1, 0, 0, 1, Underline, LineStyle{})
if len(st) == 0 {
t.Fatalf("no underline of glyph %d", i)
}
return st[0].Top
}
flat := s.Layout(Params{Text: "x2 H2O", Style: Style{Size: 16}, Spans: EncodeSpans([]Span{{End: 1}, {End: 2, Size: 10}, {End: 4}, {End: 5, Size: 10}})})
k := slices.IndexFunc(line.Glyphs, func(g Glyph) bool { return g.Cluster == 1 })
kf := slices.IndexFunc(flat.Lines[0].Glyphs, func(g Glyph) bool { return g.Cluster == 1 })
if d := (under(flat, kf) - flat.Lines[0].Baseline) - (under(l, k) - line.Baseline); d < 6 || d > 8 {
t.Errorf("the superscript's underline is %v above where it would be", d)
}
// Objects shift too.
obj := s.Layout(Params{Text: "a\uFFFC", Style: Style{Size: 16}, Spans: EncodeSpans([]Span{{End: 1}, {End: 2, ObjectWidth: 5, ObjectHeight: 30, BaselineShift: 10}})})
if obj.Lines[0].Ascent < 40 {
t.Errorf("a raised object leaves an ascent of %v", obj.Lines[0].Ascent)
}
}
// TestBalance wraps a paragraph in as many lines as it takes, at the
// narrowest width that keeps them as many, aligned within the width: no
// word alone on the last line.
func TestBalance(t *testing.T) {
s := breakSystem(0)
p := Params{Text: "aaa bbb ccc ddd e", Style: Style{Size: 10}, Width: 160}
if l := s.Layout(p); len(l.Lines) != 2 || lineText(l, 1) != "e" {
t.Fatalf("unbalanced, %d lines, the last %q", len(l.Lines), lineText(l, len(l.Lines)-1))
}
p.Balance = true
l := s.Layout(p)
if len(l.Lines) != 2 || lineText(l, 0) != "aaa bbb " || lineText(l, 1) != "ccc ddd e" {
t.Fatalf("balanced, %d lines: %q, %q", len(l.Lines), lineText(l, 0), lineText(l, len(l.Lines)-1))
}
if l.Lines[0].Width != 70 || l.Lines[1].Width != 90 || l.Width != 90 {
t.Errorf("balanced, the lines are %v and %v wide, the text %v", l.Lines[0].Width, l.Lines[1].Width, l.Width)
}
// Laid out once, and kept: a frame laying it out again finds it.
made := s.LayoutsMade()
if s.Layout(p) != l || s.LayoutsMade() != made {
t.Error("the balanced layout was made again")
}
// Aligned within the width, each paragraph balanced on its own.
p.Text, p.Align = "aaa bbb ccc ddd e\naa bb", Center
l = s.Layout(p)
if len(l.Lines) != 3 || l.Lines[0].X != 45 || l.Lines[1].X != 35 || lineText(l, 2) != "aa bb" || l.Lines[2].X != 55 {
t.Errorf("centered, %d lines at %v, %v, %v", len(l.Lines), l.Lines[0].X, l.Lines[1].X, l.Lines[len(l.Lines)-1].X)
}
// A line it fits on, it keeps.
if l := s.Layout(Params{Text: "aaa bbb", Style: Style{Size: 10}, Width: 160, Balance: true}); len(l.Lines) != 1 || l.Width != 70 {
t.Errorf("one line: %d lines, %v wide", len(l.Lines), l.Width)
}
// Three lines of about the same length, rather than two full ones
// and a short one.
p = Params{Text: "aaa bbb ccc ddd eee fff g", Style: Style{Size: 10}, Width: 120, Balance: true}
l = s.Layout(p)
if len(l.Lines) != 3 || lineText(l, 0) != "aaa bbb " || lineText(l, 1) != "ccc ddd " || lineText(l, 2) != "eee fff g" {
t.Errorf("three lines: %q", []string{lineText(l, 0), lineText(l, 1), lineText(l, len(l.Lines)-1)})
}
// MaxLines cutting the paragraph, it wraps as without Balance.
p = Params{Text: "aaa bbb ccc ddd e", Style: Style{Size: 10}, Width: 160, MaxLines: 1, Balance: true}
if l := s.Layout(p); len(l.Lines) != 1 || !l.Truncated || !strings.HasPrefix(lineText(l, 0), "aaa bbb ccc") {
t.Errorf("cut to a line: %d lines, %q", len(l.Lines), lineText(l, 0))
}
// Without a width, nothing wraps.
if l := s.Layout(Params{Text: "aaa bbb ccc ddd e", Style: Style{Size: 10}, Balance: true}); len(l.Lines) != 1 {
t.Errorf("without a width, %d lines", len(l.Lines))
}
}
+62
View File
@@ -0,0 +1,62 @@
package text
import "testing"
// TestPretty gives a paragraph's last line a word from the line before
// rather than one alone, as narrow as that leaves it, keeping the lines
// before as they are; leaves a last line of words, a paragraph whose line
// before has no word to spare, and one MaxLines cuts as they wrap.
func TestPretty(t *testing.T) {
s := breakSystem(0)
s.UsePretty()
p := Params{Text: "aaa bbb ccc ddd eee fff ggg hhh i", Style: Style{Size: 10}, Width: 160}
if l := s.Layout(p); len(l.Lines) != 3 || lineText(l, 2) != "i" {
t.Fatalf("not pretty, %d lines, the last %q", len(l.Lines), lineText(l, len(l.Lines)-1))
}
p.Pretty = true
l := s.Layout(p)
if len(l.Lines) != 3 || lineText(l, 0) != "aaa bbb ccc ddd " || lineText(l, 1) != "eee fff ggg " || lineText(l, 2) != "hhh i" {
t.Fatalf("pretty: %q", texts(l))
}
// Laid out once, and kept.
made := s.LayoutsMade()
if s.Layout(p) != l || s.LayoutsMade() != made {
t.Error("the pretty layout was made again")
}
// Each paragraph on its own, after a newline too.
p.Text = "aaa bbb ccc ddd e\naaa bbb ccc ddd eee ff"
if l := s.Layout(p); len(l.Lines) != 4 || lineText(l, 0) != "aaa bbb ccc " || lineText(l, 1) != "ddd e" || lineText(l, 3) != "eee ff" {
t.Errorf("two paragraphs: %q", texts(l))
}
// A two-line paragraph, the first indented.
p = Params{Text: "aaa bbb ccc ddd e", Style: Style{Size: 10}, Width: 160, Indent: 10, Pretty: true}
if l := s.Layout(p); len(l.Lines) != 2 || lineText(l, 1) != "ddd e" {
t.Errorf("indented: %q", texts(l))
}
for _, tc := range []struct {
name string
p Params
last string
}{
{"a last line of words", Params{Text: "aaa bbb ccc ddd ee ff", Width: 160}, "ee ff"},
{"no word to spare", Params{Text: "aaaaaaaaaaaaaaaa b", Width: 160}, "b"},
{"one line", Params{Text: "aaa b", Width: 160}, "aaa b"},
} {
tc.p.Style, tc.p.Pretty = Style{Size: 10}, true
if l := s.Layout(tc.p); lineText(l, len(l.Lines)-1) != tc.last {
t.Errorf("%s: %q", tc.name, texts(l))
}
}
p = Params{Text: "aaa bbb ccc ddd e", Style: Style{Size: 10}, Width: 160, MaxLines: 1, Pretty: true}
if l := s.Layout(p); len(l.Lines) != 1 || !l.Truncated {
t.Errorf("cut to a line: %q", texts(l))
}
}
func texts(l *Layout) []string {
var out []string
for i := range l.Lines {
out = append(out, lineText(l, i))
}
return out
}
+621
View File
@@ -0,0 +1,621 @@
package text
import (
"image"
"math"
"github.com/egoist/mygo/internal/scene"
)
// A Shade is how light the color of text is, from 0 (dark) to Shades-1
// (light). Core Text's font smoothing, which AppKit draws text with,
// emboldens glyphs more the lighter their color is, in four steps of its
// relative luminance: the glyphs of its fonts are rasterized for each.
type Shade uint8
// Shades is the number of shades of text.
const Shades = 4
// Thick is a shade beyond the others, for text drawn thicker: with Core
// Text's font smoothing at its strongest, whatever the text's color and
// the user's setting, as Ghostty's font-thicken draws it. Engines that do
// not thicken glyphs draw them as for other text.
const Thick Shade = Shades
// Flat is a shade beyond the others, for text drawn without font
// smoothing, whatever its color: thinner, as browsers draw text styled
// -webkit-font-smoothing: antialiased on macOS. Engines that do not
// smooth fonts draw it as other text.
const Flat Shade = Shades + 1
// shadeFor returns the shade that glyphs of f for text of shade are drawn
// for.
func (f *Font) shadeFor(shade Shade) Shade {
switch {
case shade == Thick && f.thickens:
return Thick
case !f.shaded:
return 0
case shade == Flat:
return Flat
}
return min(shade, Shades-1)
}
// ShadeOf returns the shade of text of an sRGB color: its relative
// luminance rounded to a quarter, as Core Text rounds it, and at most 3/4.
func ShadeOf(r, g, b uint8) Shade {
y := 0.2126*linear[r] + 0.7152*linear[g] + 0.0722*linear[b]
return Shade(min(y*Shades+0.5, Shades-1))
}
// linear maps sRGB values to linear light.
var linear = func() (t [256]float32) {
for i := range t {
v := float64(i) / 255
if v <= 0.04045 {
v /= 12.92
} else {
v = math.Pow((v+0.055)/1.055, 2.4)
}
t[i] = float32(v)
}
return t
}()
type glyphKey struct {
font *Font
id uint32
scale uint32 // pixels per DIP, in 1/256
subX uint8 // the position within a pixel, of placement.n
shade Shade
subpixel bool
// stroke is the width of a stroke of the glyph's outline in 1/16
// pixels (StrokeGlyph), 0 for the glyph itself; shadow is 1 + the
// standard deviation of the blur of its shadow in 1/16 pixels
// (ShadowGlyph), 0 for none.
stroke uint16
shadow uint16
}
// placement is how the system's text stack places glyphs of a font at a
// scale horizontally: at n positions within a pixel, the nearest to their
// pen if round, else the one left of it.
type placement struct {
n int
round bool
}
type placeKey struct {
font *Font
scale uint32
subpixel bool
}
// GlyphImage is a rasterized glyph in an atlas.
type GlyphImage struct {
// OK is false for glyphs without pixels, such as spaces.
OK bool
// Colored glyphs are in the color atlas, the others in the mask atlas
// but Subpixel ones, in the color atlas too, which hold the coverage of
// each pixel's red, green and blue subpixels.
Colored, Subpixel bool
// Thin glyphs are of a font too thin for antialiasing, which renderers
// give more contrast (scene.Glyph.Thin).
Thin bool
// X, Y, W and H are the bitmap's rectangle in its atlas.
X, Y, W, H uint16
// Left and Top place the bitmap relative to the glyph's origin on the
// baseline, in pixels: Top is usually negative.
Left, Top float32
}
// inColor reports whether the glyph is in the color atlas.
func (g GlyphImage) inColor() bool { return g.Colored || g.Subpixel }
// atlasEntry is a cached glyph or mask.
type atlasEntry struct {
GlyphImage
used uint64 // the last frame that drew it
}
// BeginFrame starts painting a frame: the masks drawn for the previous
// frame alone are forgotten.
func (s *System) BeginFrame() {
s.mu.Lock()
defer s.mu.Unlock()
s.MaskAtlas.ResetTransient()
clear(s.transient)
s.forgetLeftOut()
s.rooms = 0
}
// forgetLeftOut forgets what the atlases left out, for a new frame or as they
// have room.
func (s *System) forgetLeftOut() {
s.full, s.want = [2]bool{}, [2]int{}
s.wantSize = [2]image.Point{}
clear(s.outGlyphs)
clear(s.outRuns)
clear(s.outMasks)
}
// TransientUses returns how many times Mask returned a mask drawn for the
// frame being painted alone, since the system started: a scene drawing one
// must not be drawn again after the next frame of any window begins
// (BeginFrame), which draws over it.
func (s *System) TransientUses() uint64 {
s.mu.Lock()
defer s.mu.Unlock()
return s.transientUses
}
// Full reports whether an atlas filled up during the frame being painted
// and left out glyphs or masks it draws. MakeRoom then makes room for them.
func (s *System) Full() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.full[0] || s.full[1]
}
// MaskFull reports whether the coverage atlas left out a glyph or mask,
// as distinct from the color atlas. A painter can then release large
// path masks in favor of tiles before making room for the final retry.
func (s *System) MaskFull() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.full[0]
}
// MakeRoom makes room in the atlases that filled up: it keeps what the
// frame being painted drew, growing the atlas when that and what the frame
// still needs take much of it, or when room made for the frame before did
// not suffice, and forgets everything else. Everything kept moves, so the
// frame must be painted again.
func (s *System) MakeRoom() {
s.mu.Lock()
defer s.mu.Unlock()
s.rooms++
for i, color := range [2]bool{false, true} {
if s.full[i] {
s.makeRoom(color, s.want[i], s.wantSize[i], s.rooms > 1)
}
}
s.forgetLeftOut()
}
func (s *System) makeRoom(color bool, want int, size image.Point, grow bool) {
a := s.MaskAtlas
if color {
a = s.ColorAtlas
}
var keep []*atlasEntry
need := want
if !color {
for _, g := range s.transient {
need += (int(g.W) + 1) * (int(g.H) + 1)
}
clear(s.transient)
a.ResetTransient()
for k, e := range s.masks {
if e.used != s.frame {
delete(s.masks, k)
continue
}
keep = append(keep, e)
}
}
for k, e := range s.glyphs {
if !e.OK || e.inColor() != color {
continue // blank glyphs take no room
}
if e.used != s.frame {
delete(s.glyphs, k)
continue
}
keep = append(keep, e)
}
for k, e := range s.runs {
if e.inColor() != color {
continue
}
if e.used != s.frame {
delete(s.runs, k)
continue
}
keep = append(keep, e)
}
rects := make([]image.Rectangle, len(keep))
for i, e := range keep {
rects[i] = image.Rect(int(e.X), int(e.Y), int(e.X)+int(e.W), int(e.Y)+int(e.H))
need += (int(e.W) + 1) * (int(e.H) + 1)
}
// Shelves waste room: keep the atlas at most half full.
if grow {
a.Grow()
}
for (need*2 > a.W*a.H || size.X > a.W || size.Y > a.H) && a.Grow() {
}
pos, ok := a.Repack(rects)
if !ok {
a.Reset()
for k, e := range s.glyphs {
if e.OK && e.inColor() == color {
delete(s.glyphs, k)
}
}
for k, e := range s.runs {
if e.inColor() == color {
delete(s.runs, k)
}
}
if !color {
clear(s.masks)
}
return
}
for i, e := range keep {
e.X, e.Y = uint16(pos[i].X), uint16(pos[i].Y)
}
}
// Glyph rasterizes glyph id of a font at scale pixels per DIP whose pen
// is x device pixels from the left, for text of a shade, placed as the
// system's text stack places glyphs: at one of the positions within a
// pixel it draws them at. Left is relative to the pixel x is in. Glyphs on
// opaque backgrounds may be subpixel ones, when the system's settings
// (TextParams) ask for subpixel antialiasing.
func (s *System) Glyph(f *Font, id uint32, scale, x float32, shade Shade, opaque bool) GlyphImage {
return s.glyph(f, id, scale, x, shade, opaque, 0, 0, nil)
}
// StrokeGlyph returns the coverage mask of a stroke width device pixels
// wide along the outline of the glyph Glyph returns for the same
// arguments, centered on it and round at its corners, placed as that
// glyph is: a mask glyph, for color glyphs too, which strokes the edge of
// their pixels. Text stroked under its fill (CSS's paint-order: stroke
// fill) shows the half outside the glyph.
func (s *System) StrokeGlyph(f *Font, id uint32, scale, x float32, shade Shade, opaque bool, width float32) GlyphImage {
w := min(max(width*16+0.5, 1), 128*16) // at most 128 pixels
return s.glyph(f, id, scale, x, shade, opaque, uint16(w), 0, (*System).rasterizeStroke)
}
// ShadowGlyph returns the coverage mask of the glyph Glyph returns for the
// same arguments blurred by a Gaussian of standard deviation sigma device
// pixels, placed as that glyph is, wider by the blur: a mask glyph, for
// color glyphs too, of their pixels' alpha, which a text's shadow (CSS's
// text-shadow) paints in its color.
func (s *System) ShadowGlyph(f *Font, id uint32, scale, x float32, shade Shade, opaque bool, sigma float32) GlyphImage {
b := min(max(sigma*16+0.5, 0), 64*16) // at most 64 pixels
return s.glyph(f, id, scale, x, shade, opaque, 0, 1+uint16(b), (*System).rasterizeShadow)
}
// glyph returns the glyph of Glyph, or with stroke the mask of a stroke
// stroke/16 pixels wide along it, or with shadow the mask of it blurred
// by (shadow-1)/16 pixels, which derive rasterizes (StrokeGlyph,
// ShadowGlyph): apps that stroke and shadow no text do not link it.
func (s *System) glyph(f *Font, id uint32, scale, x float32, shade Shade, opaque bool, stroke, shadow uint16, derive func(s *System, f *Font, id uint32, scale, dx float32, shade Shade, amount float32) GlyphImage) GlyphImage {
s.mu.Lock()
defer s.mu.Unlock()
if f == nil {
return GlyphImage{}
}
shade = f.shadeFor(shade)
subpixel := opaque && s.subpixel
q, n, carry := s.place(f, scale, subpixel, x)
key := glyphKey{font: f, id: id, scale: uint32(scale*256 + 0.5), subX: uint8(q), shade: shade, subpixel: subpixel, stroke: stroke, shadow: shadow}
e, ok := s.glyphs[key]
if !ok {
if _, out := s.outGlyphs[key]; out {
return GlyphImage{}
}
failed := s.failed
var g GlyphImage
switch {
case stroke > 0:
g = derive(s, f, id, scale, float32(q)/float32(n), key.shade, float32(stroke)/16)
case shadow > 0:
g = derive(s, f, id, scale, float32(q)/float32(n), key.shade, float32(shadow-1)/16)
default:
g = s.rasterize(f, id, scale, float32(q)/float32(n), key.shade, key.subpixel)
}
e = &atlasEntry{g, s.frame}
if s.failed == failed { // not left out of a full atlas
s.glyphs[key] = e
} else {
if s.outGlyphs == nil {
s.outGlyphs = map[glyphKey]struct{}{}
}
s.outGlyphs[key] = struct{}{}
}
}
e.used = s.frame
g := e.GlyphImage
g.Left += carry
return g
}
// Origin returns where Glyph puts the origin of a glyph of f whose pen is
// x device pixels from the left: at the position within a pixel the
// system's text stack draws it at.
func (s *System) Origin(f *Font, scale, x float32, opaque bool) float32 {
s.mu.Lock()
defer s.mu.Unlock()
if f == nil {
return x
}
q, n, carry := s.place(f, scale, opaque && s.subpixel, x)
return float32(math.Floor(float64(x))) + carry + float32(q)/float32(n)
}
// place returns where the system's text stack draws a glyph of f whose pen
// is at x: at position q of the n within a pixel, carry pixels right of
// the pixel x is in.
func (s *System) place(f *Font, scale float32, subpixel bool, x float32) (q, n int, carry float32) {
pk := placeKey{f, uint32(scale*256 + 0.5), subpixel}
pl, ok := s.places[pk]
if !ok {
pl.n, pl.round = s.engine().positions(f, scale, subpixel)
pl.n = max(pl.n, 1)
s.places[pk] = pl
}
frac := float64(x) - math.Floor(float64(x))
if pl.round {
if q = int(math.Floor(frac*float64(pl.n) + 0.5)); q == pl.n {
return 0, pl.n, 1
}
return q, pl.n, 0
}
return min(int(frac*float64(pl.n)), pl.n-1), pl.n, 0
}
// Baseline returns where the system's text stack draws a baseline that is
// y device pixels from the top: on a whole pixel.
func (s *System) Baseline(y float32) float32 {
s.mu.Lock()
defer s.mu.Unlock()
return s.engine().baseline(y)
}
func (s *System) rasterize(f *Font, id uint32, scale, dx float32, shade Shade, subpixel bool) GlyphImage {
b := s.engine().glyph(f, id, scale, dx, shade, subpixel)
if b.w <= 0 || b.h <= 0 || b.w > 2048 || b.h > 2048 {
return GlyphImage{}
}
inColor := b.color || b.subpixel
x, y, ok := s.alloc(inColor, b.w, b.h)
if !ok {
return GlyphImage{}
}
if inColor {
s.ColorAtlas.Put(x, y, b.w, b.h, b.pix, 4*b.w)
} else {
s.MaskAtlas.Put(x, y, b.w, b.h, b.pix, b.w)
}
return GlyphImage{OK: true, Colored: b.color, Subpixel: b.subpixel, Thin: f.thin && !b.color,
X: uint16(x), Y: uint16(y), W: uint16(b.w), H: uint16(b.h), Left: float32(b.left), Top: float32(b.top)}
}
// rasterizeStroke puts the mask of a stroke width pixels wide along the
// outline of a glyph into the mask atlas (StrokeGlyph).
func (s *System) rasterizeStroke(f *Font, id uint32, scale, dx float32, shade Shade, width float32) GlyphImage {
b := s.engine().glyph(f, id, scale, dx, shade, false)
if b.w <= 0 || b.h <= 0 || b.w > 2048 || b.h > 2048 {
return GlyphImage{}
}
b = strokeBitmap(b, width/2)
if b.w > 2048 || b.h > 2048 {
return GlyphImage{}
}
x, y, ok := s.alloc(false, b.w, b.h)
if !ok {
return GlyphImage{}
}
s.MaskAtlas.Put(x, y, b.w, b.h, b.pix, b.w)
return GlyphImage{OK: true, X: uint16(x), Y: uint16(y), W: uint16(b.w), H: uint16(b.h), Left: float32(b.left), Top: float32(b.top)}
}
// rasterizeShadow puts the mask of a glyph blurred by sigma pixels into
// the mask atlas (ShadowGlyph).
func (s *System) rasterizeShadow(f *Font, id uint32, scale, dx float32, shade Shade, sigma float32) GlyphImage {
b := s.engine().glyph(f, id, scale, dx, shade, false)
if b.w <= 0 || b.h <= 0 || b.w > 2048 || b.h > 2048 {
return GlyphImage{}
}
b = blurBitmap(b, sigma)
if b.w > 2048 || b.h > 2048 {
return GlyphImage{}
}
x, y, ok := s.alloc(false, b.w, b.h)
if !ok {
return GlyphImage{}
}
s.MaskAtlas.Put(x, y, b.w, b.h, b.pix, b.w)
return GlyphImage{OK: true, X: uint16(x), Y: uint16(y), W: uint16(b.w), H: uint16(b.h), Left: float32(b.left), Top: float32(b.top)}
}
// TextParams returns how renderers correct the coverage of glyphs, as
// the system's settings say, for the frame being painted, and has glyphs
// on opaque backgrounds take subpixel antialiasing if they ask for it.
func (s *System) TextParams() scene.TextParams {
s.mu.Lock()
defer s.mu.Unlock()
p, subpixel := s.engine().textParams()
s.subpixel = subpixel
return p
}
// alloc finds lasting room in an atlas, or records that it is full.
func (s *System) alloc(color bool, w, h int) (int, int, bool) {
a := s.MaskAtlas
if color {
a = s.ColorAtlas
}
// The first bitmap can size an empty atlas without invalidating any
// glyphs already painted. In particular, the color atlas starts with
// one transparent texel and needs no repaint to show its first emoji.
if a.Version() == 0 {
for (w+1 > a.W || h+1 > a.H) && a.Grow() {
}
}
if x, y, ok := a.Alloc(w, h); ok {
return x, y, true
}
s.leftOut(color, w, h)
return 0, 0, false
}
func (s *System) leftOut(color bool, w, h int) {
i := 0
if color {
i = 1
}
s.full[i] = true
s.want[i] += (w + 1) * (h + 1)
s.wantSize[i].X = max(s.wantSize[i].X, w+1)
s.wantSize[i].Y = max(s.wantSize[i].Y, h+1)
s.failed++
}
// Mask returns a coverage mask cached under key in the mask atlas,
// drawing it when it is not: draw returns its size and one byte per pixel.
// Icons and other vector shapes use it.
// If the dimensions cannot fit the current atlas, draw may return nil
// pixels: the miss records that size for MakeRoom without rasterizing it.
//
// A mask a frame draws for the first time may be one frame of an
// animation, never drawn again: it lasts for that frame only, in the
// atlas's transient room. Later frames try to cache it in lasting room,
// requesting MakeRoom when that is full. A recovery paint can fall back
// to transient room if lasting room is still full.
func (s *System) Mask(key uint64, draw func() (w, h int, pix []byte)) GlyphImage {
return s.mask(key, draw, true)
}
// TryMask is Mask without asking for room: a mask that finds none is not
// left out of the frame, which then neither reports Full nor has MakeRoom
// make room for it, for a caller that draws it another way.
func (s *System) TryMask(key uint64, draw func() (w, h int, pix []byte)) GlyphImage {
return s.mask(key, draw, false)
}
func (s *System) mask(key uint64, draw func() (w, h int, pix []byte), ask bool) GlyphImage {
s.mu.Lock()
defer s.mu.Unlock()
if e, ok := s.masks[key]; ok {
e.used = s.frame
return e.GlyphImage
}
if g, ok := s.transient[key]; ok {
s.transientUses++
return g
}
if _, out := s.outMasks[key]; out {
return GlyphImage{}
}
last, seen := s.recent[key]
lasting := seen && last != s.frame
// Remember repeated requests through recovery paints, even when they
// fail or can only use transient room. A later attempt may find space
// in a lasting shelf that has since been compacted.
seenAt := s.frame
if lasting {
seenAt--
}
w, h, pix := draw()
if w <= 0 || h <= 0 {
return GlyphImage{}
}
var x, y int
var ok bool
if pix != nil {
if lasting {
x, y, ok = s.MaskAtlas.Alloc(w, h)
// Let the first miss reclaim stale lasting masks. Otherwise
// a repeated mask can stay transient and be drawn anew forever.
if !ok && s.rooms > 0 {
x, y, ok = s.MaskAtlas.AllocTransient(w, h)
if ok {
lasting = false
}
}
} else {
x, y, ok = s.MaskAtlas.AllocTransient(w, h)
}
}
if !ok {
s.recent[key] = seenAt
if !ask {
return GlyphImage{}
}
s.leftOut(false, w, h)
if s.outMasks == nil {
s.outMasks = map[uint64]struct{}{}
}
s.outMasks[key] = struct{}{}
return GlyphImage{}
}
s.MaskAtlas.Put(x, y, w, h, pix, w)
g := GlyphImage{OK: true, X: uint16(x), Y: uint16(y), W: uint16(w), H: uint16(h)}
if lasting {
delete(s.recent, key)
s.masks[key] = &atlasEntry{g, s.frame}
} else {
s.transient[key] = g
s.recent[key] = seenAt
s.transientUses++
}
return g
}
// Unkeep lets the masks cached under keys go as the atlas makes room for
// the frame being painted (MakeRoom), unless it draws them again first:
// masks it drew that the frame painted again draws otherwise, which the
// room made would keep but no paint draws.
func (s *System) Unkeep(keys []uint64) {
s.mu.Lock()
defer s.mu.Unlock()
for _, k := range keys {
if e, ok := s.masks[k]; ok && e.used == s.frame {
e.used = s.frame - 1
// If a recovery paint needs it again, it is still a repeated
// request and may share the room left in lasting shelves.
s.recent[k] = s.frame - 1
}
}
}
// GlyphBitmap rasterizes a glyph of f for drawing on the CPU, as the text
// of SVG documents is drawn, and keeps it nowhere: at scale pixels per
// DIP, its origin dx pixels right of the left edge of a pixel (0 ≤ dx <
// 1), unshaded, or with stroke > 0 the stroke of its outline stroke
// pixels wide (StrokeGlyph). It returns w×h bytes of coverage, color
// glyphs' alpha, placed left and top pixels from the glyph's origin.
func (s *System) GlyphBitmap(f *Font, id uint32, scale, dx, stroke float32) (left, top, w, h int, pix []byte) {
s.mu.Lock()
defer s.mu.Unlock()
if f == nil {
return
}
b := s.engine().glyph(f, id, scale, dx, f.shadeFor(Flat), false)
if b.w <= 0 || b.h <= 0 || b.w > 2048 || b.h > 2048 {
return
}
if stroke > 0 {
b = strokeBitmap(b, min(stroke, 128)/2)
return b.left, b.top, b.w, b.h, b.pix
}
// A copy: engines may draw the next glyph into the same memory.
cov := make([]byte, b.w*b.h)
for i := range cov {
switch {
case b.color:
cov[i] = b.pix[4*i+3]
case b.subpixel:
cov[i] = max(b.pix[4*i], b.pix[4*i+1], b.pix[4*i+2])
default:
cov[i] = b.pix[i]
}
}
return b.left, b.top, b.w, b.h, cov
}
+69
View File
@@ -0,0 +1,69 @@
//go:build darwin
package text
import (
"runtime"
"unsafe"
"github.com/ebitengine/purego"
)
// The leaves of rundelegate_darwin_*.s.
func runDelegateDealloc()
func runDelegateAscent()
func runDelegateDescent()
func runDelegateWidth()
func runDelegateFuncs() (dealloc, ascent, descent, width uintptr)
// runDelegateCallbacks is a CTRunDelegateCallbacks, version 1.
type runDelegateCallbacks struct {
version int
dealloc, ascent, descent, width uintptr
}
// delegates makes Core Text's run delegates, which give inline objects
// their size, from metrics the engine keeps, pinned, until it lays out the
// next text.
type delegates struct {
create uintptr // CTRunDelegateCreate
attribute uintptr // kCTRunDelegateAttributeName
callbacks runDelegateCallbacks
metrics [][3]float64
pinner runtime.Pinner
}
var runDelegates delegates
// initDelegates finds Core Text's run delegates in the framework text.
func initDelegates(text uintptr, optional func(lib uintptr, name string) uintptr) {
d := &runDelegates
if sym, err := purego.Dlsym(text, "CTRunDelegateCreate"); err == nil {
d.create = sym
}
d.attribute = optional(text, "kCTRunDelegateAttributeName")
dealloc, ascent, descent, width := runDelegateFuncs()
d.callbacks = runDelegateCallbacks{version: 1, dealloc: dealloc, ascent: ascent, descent: descent, width: width}
}
// reset lets go of the metrics of the last text laid out, and makes room
// for n objects.
func (d *delegates) reset(n int) {
d.pinner.Unpin()
d.metrics = make([][3]float64, n)
if n > 0 {
d.pinner.Pin(&d.metrics[0])
d.pinner.Pin(&d.callbacks)
}
}
// delegate returns a run delegate, owned, giving object k its height
// above the baseline, its descent below it and its width.
func (d *delegates) delegate(k int, width, height, descent float32) uintptr {
if d.create == 0 || d.attribute == 0 || k >= len(d.metrics) {
return 0
}
d.metrics[k] = [3]float64{float64(height), float64(descent), float64(width)}
r, _, _ := purego.SyscallN(d.create, uintptr(unsafe.Pointer(&d.callbacks)), uintptr(unsafe.Pointer(&d.metrics[k])))
return r
}
@@ -0,0 +1,35 @@
//go:build darwin
#include "textflag.h"
// The callbacks of Core Text's run delegates, which lay out inline
// objects: getters return a CGFloat, which Go callbacks cannot, so they
// are leaves reading it from the object's metrics their refCon points at,
// {ascent, descent, width} in float64s.
TEXT ·runDelegateDealloc(SB), NOSPLIT|NOFRAME, $0-0
RET
TEXT ·runDelegateAscent(SB), NOSPLIT|NOFRAME, $0-0
MOVSD 0(DI), X0
RET
TEXT ·runDelegateDescent(SB), NOSPLIT|NOFRAME, $0-0
MOVSD 8(DI), X0
RET
TEXT ·runDelegateWidth(SB), NOSPLIT|NOFRAME, $0-0
MOVSD 16(DI), X0
RET
// func runDelegateFuncs() (dealloc, ascent, descent, width uintptr)
TEXT ·runDelegateFuncs(SB), NOSPLIT, $0-32
LEAQ ·runDelegateDealloc(SB), AX
MOVQ AX, dealloc+0(FP)
LEAQ ·runDelegateAscent(SB), AX
MOVQ AX, ascent+8(FP)
LEAQ ·runDelegateDescent(SB), AX
MOVQ AX, descent+16(FP)
LEAQ ·runDelegateWidth(SB), AX
MOVQ AX, width+24(FP)
RET
@@ -0,0 +1,35 @@
//go:build darwin
#include "textflag.h"
// The callbacks of Core Text's run delegates, which lay out inline
// objects: getters return a CGFloat, which Go callbacks cannot, so they
// are leaves reading it from the object's metrics their refCon points at,
// {ascent, descent, width} in float64s.
TEXT ·runDelegateDealloc(SB), NOSPLIT|NOFRAME, $0-0
RET
TEXT ·runDelegateAscent(SB), NOSPLIT|NOFRAME, $0-0
FMOVD 0(R0), F0
RET
TEXT ·runDelegateDescent(SB), NOSPLIT|NOFRAME, $0-0
FMOVD 8(R0), F0
RET
TEXT ·runDelegateWidth(SB), NOSPLIT|NOFRAME, $0-0
FMOVD 16(R0), F0
RET
// func runDelegateFuncs() (dealloc, ascent, descent, width uintptr)
TEXT ·runDelegateFuncs(SB), NOSPLIT, $0-32
MOVD $·runDelegateDealloc(SB), R0
MOVD R0, dealloc+0(FP)
MOVD $·runDelegateAscent(SB), R0
MOVD R0, ascent+8(FP)
MOVD $·runDelegateDescent(SB), R0
MOVD R0, descent+16(FP)
MOVD $·runDelegateWidth(SB), R0
MOVD R0, width+24(FP)
RET
+76
View File
@@ -0,0 +1,76 @@
package text
import "testing"
// BenchmarkSelectionVisual finds the hit boxes of four six-rune inline spans
// per wrapped line, as committing a paragraph with many links does. SmallInline
// uses four lines, LongInline 128, and VeryLongInline 512, each with 64 glyphs
// per line. WholeRange selects all 512 lines as a control. Fixed advances keep
// the fixtures independent of installed fonts; shaping and setup are not timed.
// One inline operation processes every span in the paragraph.
func BenchmarkSelectionVisual(b *testing.B) {
for _, tc := range []struct {
name string
lines int
whole bool
}{
{"SmallInline", 4, false},
{"LongInline", 128, false},
{"VeryLongInline", 512, false},
{"WholeRange", 512, true},
} {
b.Run(tc.name, func(b *testing.B) {
layout := selectionBenchmarkLayout(tc.lines)
var ranges []Range
if tc.whole {
ranges = []Range{{0, len(layout.Runes)}}
} else {
for _, line := range layout.Lines {
for offset := 4; offset < 64; offset += 16 {
ranges = append(ranges, Range{line.Start + offset, line.Start + offset + 6})
}
}
}
want := len(ranges)
if tc.whole {
want = tc.lines
}
b.ReportAllocs()
for b.Loop() {
count := 0
for _, r := range ranges {
count += len(layout.SelectionVisual(r.Start, r.End, false))
}
if count != want {
b.Fatalf("got %d rectangles, want %d", count, want)
}
}
})
}
}
func selectionBenchmarkLayout(lines int) *Layout {
const glyphsPerLine = 64
l := &Layout{
Runes: make([]rune, lines*glyphsPerLine),
Lines: make([]Line, lines),
Width: glyphsPerLine * 8,
Height: float32(lines * 20),
}
for i := range l.Runes {
l.Runes[i] = 'a'
}
for i := range l.Lines {
start := i * glyphsPerLine
line := &l.Lines[i]
*line = Line{
Start: start, End: start + glyphsPerLine,
Y: float32(i * 20), Width: l.Width, Height: 20,
Glyphs: make([]Glyph, glyphsPerLine),
}
for j := range line.Glyphs {
line.Glyphs[j] = Glyph{X: float32(j * 8), Advance: 8, Cluster: start + j, Runes: 1}
}
}
return l
}
+66
View File
@@ -0,0 +1,66 @@
package text
import "math"
// blurBitmap returns the coverage of b blurred by a Gaussian of standard
// deviation sigma pixels, as a mask reaching three of them past b on each
// side: a glyph's shadow. Color glyphs blur their alpha, subpixel ones
// their most covered channel; a sigma of 0 leaves the coverage sharp.
func blurBitmap(b bitmap, sigma float32) bitmap {
pad := 0
if sigma > 0 {
pad = int(math.Ceil(float64(3*sigma))) + 1
}
w, h := b.w+2*pad, b.h+2*pad
cov := make([]float32, w*h)
for y := range b.h {
for x := range b.w {
i := y*b.w + x
var c byte
switch {
case b.color:
c = b.pix[4*i+3]
case b.subpixel:
p := b.pix[4*i:]
c = max(p[0], p[1], p[2])
default:
c = b.pix[i]
}
cov[(y+pad)*w+x+pad] = float32(c) / 255
}
}
if pad > 0 {
// The kernel, normalized, and the blur in rows, then in columns.
kernel := make([]float32, 2*pad+1)
var sum float32
for i := range kernel {
d := float64(i - pad)
kernel[i] = float32(math.Exp(-d * d / (2 * float64(sigma) * float64(sigma))))
sum += kernel[i]
}
for i := range kernel {
kernel[i] /= sum
}
tmp := make([]float32, w*h)
blur := func(dst, src []float32, n, step, lines, across int) {
for l := range lines {
for i := range n {
var v float32
for k, kv := range kernel {
if j := i + k - pad; j >= 0 && j < n {
v += src[l*across+j*step] * kv
}
}
dst[l*across+i*step] = v
}
}
}
blur(tmp, cov, w, 1, h, w) // rows
blur(cov, tmp, h, w, w, 1) // columns
}
pix := make([]byte, w*h)
for i, c := range cov {
pix[i] = uint8(min(max(c, 0), 1)*255 + 0.5)
}
return bitmap{left: b.left - pad, top: b.top - pad, w: w, h: h, pix: pix}
}
+38
View File
@@ -0,0 +1,38 @@
package text
import "testing"
// TestBlurBitmap blurs a square of coverage: it keeps its sum, spreads
// three standard deviations past it, symmetric, and shades a sharp
// shadow of a color glyph by its alpha.
func TestBlurBitmap(t *testing.T) {
b := bitmap{left: 2, top: -8, w: 4, h: 4, pix: make([]byte, 16)}
for i := range b.pix {
b.pix[i] = 255
}
sharp := blurBitmap(b, 0)
if sharp.w != 4 || sharp.h != 4 || sharp.left != 2 || sharp.top != -8 || sharp.pix[5] != 255 {
t.Fatalf("unblurred: %dx%d at (%d, %d)", sharp.w, sharp.h, sharp.left, sharp.top)
}
soft := blurBitmap(b, 2)
pad := (soft.w - 4) / 2
if pad != 7 || soft.h != soft.w || soft.left != 2-pad || soft.top != -8-pad {
t.Fatalf("blurred: %dx%d at (%d, %d)", soft.w, soft.h, soft.left, soft.top)
}
sum := 0
for _, v := range soft.pix {
sum += int(v)
}
if want := 16 * 255; sum < want*98/100 || sum > want*102/100 {
t.Errorf("the blur sums %d, the square %d", sum, want)
}
center := soft.pix[(soft.h/2)*soft.w+soft.w/2]
edge := soft.pix[(soft.h/2)*soft.w]
if center <= edge || center == 255 || soft.pix[(soft.h/2)*soft.w+1] != soft.pix[(soft.h/2)*soft.w+soft.w-2] {
t.Errorf("the blur shades the center %d, the edge %d, unevenly", center, edge)
}
emoji := bitmap{w: 1, h: 1, color: true, pix: []byte{200, 10, 10, 128}}
if s := blurBitmap(emoji, 0); s.color || s.pix[0] != 128 {
t.Errorf("a color glyph's shadow is %v", s.pix)
}
}
+85
View File
@@ -0,0 +1,85 @@
package text
import "math"
// strokeBitmap returns the coverage of a stroke along the edge of the
// coverage of b, reaching r pixels to each side of it, round at corners:
// what b dilated by r covers and b eroded by r does not. An edge pixel's
// coverage places the edge within it, so that the stroke's edges are as
// smooth as the glyph's. Color glyphs stroke the edge of their alpha.
func strokeBitmap(b bitmap, r float32) bitmap {
pad := int(math.Ceil(float64(r))) + 1
w, h := b.w+2*pad, b.h+2*pad
cov := make([]float32, b.w*b.h)
for i := range cov {
switch {
case b.color:
cov[i] = float32(b.pix[4*i+3]) / 255
case b.subpixel:
p := b.pix[4*i:]
cov[i] = float32(max(p[0], p[1], p[2])) / 255
default:
cov[i] = float32(b.pix[i]) / 255
}
}
// The pixels a pixel's coverage reaches: within r of its edge, which
// is up to a pixel from its center.
type offset struct {
dx, dy int
d float32
}
// Nearest first, as the coverage of a pixel saturates soonest: by
// their squared distances, counted.
reach := r + 1
maxSq := 2 * pad * pad
counts := make([]int, maxSq+2)
for dy := -pad; dy <= pad; dy++ {
for dx := -pad; dx <= pad; dx++ {
counts[dx*dx+dy*dy+1]++
}
}
for i := 1; i < len(counts); i++ {
counts[i] += counts[i-1]
}
kernel := make([]offset, counts[len(counts)-1])
for dy := -pad; dy <= pad; dy++ {
for dx := -pad; dx <= pad; dx++ {
sq := dx*dx + dy*dy
kernel[counts[sq]] = offset{dx, dy, float32(math.Sqrt(float64(sq)))}
counts[sq]++
}
}
for len(kernel) > 0 && kernel[len(kernel)-1].d >= reach {
kernel = kernel[:len(kernel)-1]
}
at := func(x, y int) float32 {
if x < 0 || y < 0 || x >= b.w || y >= b.h {
return 0
}
return cov[y*b.w+x]
}
pix := make([]byte, w*h)
for y := range h {
for x := range w {
// out is what the dilated glyph covers, in what the eroded
// background does.
var out, in float32
for _, k := range kernel {
c := at(x-pad+k.dx, y-pad+k.dy)
if c > 0 {
out = max(out, min(r+c-k.d, 1))
}
if c < 1 {
in = max(in, min(r+1-c-k.d, 1))
}
if out >= 1 && in >= 1 {
break
}
}
if v := out + in - 1; v > 0 {
pix[y*w+x] = uint8(v*255 + 0.5)
}
}
}
return bitmap{left: b.left - pad, top: b.top - pad, w: w, h: h, pix: pix}
}
+175
View File
@@ -0,0 +1,175 @@
package text
import (
"fmt"
"math"
"strings"
"testing"
)
// TestStrokeBitmap strokes a square: around its edge, centered on it,
// neither inside its middle nor far outside.
func TestStrokeBitmap(t *testing.T) {
const n = 20
pix := make([]byte, n*n)
for i := range pix {
pix[i] = 255
}
b := strokeBitmap(bitmap{left: 3, top: -n, w: n, h: n, pix: pix}, 2)
pad := 3 // ⌈2⌉ + 1
if b.w != n+2*pad || b.h != n+2*pad || b.left != 3-pad || b.top != -n-pad {
t.Fatalf("stroked box %d×%d at (%d, %d)", b.w, b.h, b.left, b.top)
}
at := func(x, y int) byte { return b.pix[(y+pad)*b.w+x+pad] }
// The square's edge is at 0, between pixels -1 and 0: the stroke
// covers [-2, 2) of it, pixels -2 and -1 outside and 0 and 1 inside.
for _, x := range []int{-2, -1, 0, 1} {
if v := at(x, n/2); v < 250 {
t.Errorf("pixel %d from the edge has %d of coverage, want full", x, v)
}
}
for _, x := range []int{-3, 3, n / 2} {
if v := at(x, n/2); v > 5 {
t.Errorf("pixel %d from the edge has %d of coverage, want none", x, v)
}
}
// Round at the corner: the pixel diagonally out past the stroke's
// reach is clear, the one at its edge partly covered.
if v := at(-3, -3); v != 0 {
t.Errorf("past the corner: %d", v)
}
if v := at(-2, -2); v == 0 || v == 255 {
t.Errorf("at the corner's curve: %d, want partial", v)
}
}
// TestStrokeBitmapHalfCovered keeps the place of an antialiased edge: a
// column half covered moves the stroke by half a pixel.
func TestStrokeBitmapHalfCovered(t *testing.T) {
const n = 10
pix := make([]byte, n*n)
for y := range n {
for x := range n {
switch {
case x < 5:
pix[y*n+x] = 255
case x == 5:
pix[y*n+x] = 128
}
}
}
b := strokeBitmap(bitmap{w: n, h: n, pix: pix}, 1)
pad := 2
row := b.pix[(n/2+pad)*b.w:]
// The edge is at 5.5: the stroke covers [4.5, 6.5), half of pixels 4
// and 6, all of 5.
for x, want := range map[int]float64{3: 0, 4: 0.5, 5: 1, 6: 0.5, 7: 0} {
if v := float64(row[x+pad]) / 255; math.Abs(v-want) > 0.1 {
t.Errorf("pixel %d: %.2f of coverage, want %.2f", x, v, want)
}
}
}
func TestStrokeGlyph(t *testing.T) {
s := newSystem()
l := s.Layout(Params{Text: "O", Style: Style{Size: 40}})
g := l.Lines[0].Glyphs[0]
fill := s.Glyph(g.Font, g.ID, 1, 0, 0, false)
stroke := s.StrokeGlyph(g.Font, g.ID, 1, 0, 0, false, 4)
if !fill.OK || !stroke.OK {
t.Fatalf("glyph %+v, its stroke %+v", fill, stroke)
}
// Two pixels out on each side, and one of padding.
if stroke.W != fill.W+6 || stroke.H != fill.H+6 || stroke.Left != fill.Left-3 || stroke.Top != fill.Top-3 {
t.Errorf("glyph %+v, its stroke %+v", fill, stroke)
}
if again := s.StrokeGlyph(g.Font, g.ID, 1, 0, 0, false, 4); again != stroke {
t.Errorf("stroked again: %+v, then %+v", stroke, again)
}
if wider := s.StrokeGlyph(g.Font, g.ID, 1, 0, 0, false, 8); wider.W != fill.W+10 {
t.Errorf("a stroke 8 pixels wide is %d wide, the glyph %d", wider.W, fill.W)
}
// Ink where the glyph has none, around it and in its hole.
px := func(gi GlyphImage, x, y int) byte {
if x < 0 || y < 0 || x >= int(gi.W) || y >= int(gi.H) {
return 0
}
return s.MaskAtlas.Pix[(int(gi.Y)+y)*s.MaskAtlas.W+int(gi.X)+x]
}
var outside int
for y := range int(stroke.H) {
for x := range int(stroke.W) {
f := px(fill, x-3, y-3)
if f == 0 && px(stroke, x, y) > 128 {
outside++
}
}
}
if outside < 20 {
t.Errorf("the stroke covers %d pixels outside the glyph", outside)
}
}
// TestTabSize puts tab stops every TabSize spaces from the start of each
// line.
func TestTabSize(t *testing.T) {
s := newSystem()
s.UseTabSize()
style := Style{Family: "monospace", Size: 16}
space := s.Layout(Params{Text: "a a", Style: style}).Width - s.Layout(Params{Text: "aa", Style: style}).Width
if space <= 0 {
t.Fatal("a space has no advance")
}
// The X of the first glyph of rune i of a layout's line li.
x := func(l *Layout, li, i int) float32 {
for _, g := range l.Lines[li].Glyphs {
if g.Cluster == i {
return g.X - l.Lines[li].X
}
}
t.Fatalf("no glyph of rune %d in line %d of %q", i, li, l.Params.Text)
return 0
}
for _, c := range []struct {
text string
size float32
at int
want float32 // in spaces
}{
{"\tb", 4, 1, 4},
{"\tb", 2, 1, 2},
{"a\tb", 4, 2, 4},
{"abcde\tb", 4, 6, 8},
{"\t\tb", 3, 2, 6},
} {
st := style
st.TabSize = c.size
l := s.Layout(Params{Text: c.text, Style: st})
if got := x(l, 0, c.at); math.Abs(float64(got-c.want*space)) > 0.5 {
t.Errorf("%q with tabs of %v: rune %d at %v, want %v (%v spaces); glyphs %s", c.text, c.size, c.at, got, c.want*space, c.want, glyphList(l.Lines[0]))
}
}
// Each line counts from its start, after a newline and where it wraps.
st := style
st.TabSize = 4
l := s.Layout(Params{Text: "abcdef\n\tb", Style: st})
if got := x(l, 1, 8); math.Abs(float64(got-4*space)) > 0.5 {
t.Errorf("after a newline: at %v, want %v; glyphs %s", got, 4*space, glyphList(l.Lines[1]))
}
l = s.Layout(Params{Text: "abcdefgh abcdefgh\tb", Style: st, Width: 14 * space})
if len(l.Lines) != 2 {
t.Fatalf("%d lines", len(l.Lines))
}
if got := x(l, 1, 18); math.Abs(float64(got-12*space)) > 0.5 {
t.Errorf("on a wrapped line: at %v, want %v", got, 12*space)
}
}
// glyphList lists the clusters, places and advances of a line's glyphs.
func glyphList(line Line) string {
var b strings.Builder
for _, g := range line.Glyphs {
fmt.Fprintf(&b, "[%d at %v, %v wide] ", g.Cluster, g.X, g.Advance)
}
return fmt.Sprintf("%sfrom %v", b.String(), line.X)
}
+59
View File
@@ -0,0 +1,59 @@
package text
import (
"errors"
"math"
"github.com/egoist/mygo/internal/scene"
)
// stubEngine lays out text without fonts where the system has no text
// engine MyGo can use: every rune takes half an em and draws nothing.
type stubEngine struct {
shapeScratch
fonts map[float32]*Font
}
func (e *stubEngine) font(style Style) *Font {
size := style.FontSize()
if f, ok := e.fonts[size]; ok {
return f
}
if e.fonts == nil {
e.fonts = map[float32]*Font{}
}
f := &Font{Size: size, Ascent: size * 0.8, Descent: size * 0.2}
e.fonts[size] = f
return f
}
func (e *stubEngine) shape(text []rune, style Style, spans []Span, width float32, rtl, wholeWords bool) []shapedLine {
f := e.font(style)
run := shapedRun{font: f, end: len(text)}
for i := range text {
run.glyphs = append(run.glyphs, Glyph{Font: f, X: float32(i) * f.Size / 2, Advance: f.Size / 2, Cluster: i, RTL: rtl})
}
return []shapedLine{{end: len(text), runs: []shapedRun{run}}}
}
func (e *stubEngine) glyph(f *Font, id uint32, scale, dx float32, _ Shade, _ bool) bitmap {
return bitmap{}
}
func (e *stubEngine) textParams() (scene.TextParams, bool) { return scene.TextParams{}, false }
func (e *stubEngine) positions(*Font, float32, bool) (int, bool) { return 1, true }
func (e *stubEngine) decorate(decoRange) []Stroke { return nil }
func (e *stubEngine) join() bool { return false }
func (e *stubEngine) baseline(y float32) float32 { return float32(math.Round(float64(y))) }
func (e *stubEngine) appFamilies() []FontFamily { return nil }
func (e *stubEngine) systemFamilies() func() []FontFamily { return nil }
func (e *stubEngine) register(data []byte, family string) error {
return errors.New("mygo: this system has no text engine to add fonts to")
}
File diff suppressed because it is too large. Load diff
+39
View File
@@ -0,0 +1,39 @@
package text
import "unicode"
// Word boundaries, without a dictionary: a word is a run of letters,
// digits and underscores, as in the scripts written with spaces between
// words (Latin, Cyrillic, Greek, Hangul…), except that each Han
// ideograph, Hiragana and Katakana is a word of its own. Chinese and
// Japanese are written without spaces and only a dictionary finds their
// words (UAX #29 leaves them to one); a character at a time is what
// platforms do without one, rather than a whole sentence as one word.
// Thai, also written without spaces, keeps its runs: its vowels are
// combining marks, so a rune at a time would split syllables.
// IsWordRune reports whether r is part of a word: a letter, a digit or
// an underscore.
func IsWordRune(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' }
// StandsAlone reports whether r is a word on its own: a Han ideograph
// (with the iteration mark 々), a Hiragana or a Katakana (with the
// prolonged sound mark ー).
func StandsAlone(r rune) bool {
if r < 0x2e80 {
return false
}
switch r {
case 0x30fc, 0xff70: // ー and its halfwidth form, of the Common script
return true
}
return IsWordRune(r) && (unicode.Is(unicode.Han, r) || unicode.Is(unicode.Hiragana, r) || unicode.Is(unicode.Katakana, r))
}
// WordBoundary reports whether a and b, next to each other, are in
// different words or runs of other runes: one is part of a word and the
// other is not, or either is a word on its own (StandsAlone). Script
// changes between Latin and Han or kana and kanji are boundaries so.
func WordBoundary(a, b rune) bool {
return IsWordRune(a) != IsWordRune(b) || StandsAlone(a) || StandsAlone(b)
}
+88
View File
@@ -0,0 +1,88 @@
package text
import (
"slices"
"testing"
)
func TestStandsAlone(t *testing.T) {
for _, r := range "我们公园今日直骨々あをはカタナーカー" {
if !StandsAlone(r) || !IsWordRune(r) {
t.Errorf("%q: StandsAlone %v, IsWordRune %v", r, StandsAlone(r), IsWordRune(r))
}
}
// Spaced scripts, Hangul among them, digits, punctuation and spaces.
for _, r := range "aZé_9жω한글ไทย,。、「」 \n !1" {
if StandsAlone(r) {
t.Errorf("%q stands alone", r)
}
}
}
func TestWordBoundary(t *testing.T) {
for _, c := range []struct {
a, b rune
want bool
}{
{'a', 'b', false}, {'a', '_', false}, {'9', 'x', false}, {'한', '글', false},
{'a', ' ', true}, {',', ' ', false}, {'a', '中', true}, {'中', 'a', true},
{'今', '日', true}, {'は', '直', true}, {'カ', 'タ', true}, {'中', ',', true},
} {
if got := WordBoundary(c.a, c.b); got != c.want {
t.Errorf("WordBoundary(%q, %q) = %v, want %v", c.a, c.b, got, c.want)
}
}
}
// words walks s with next from 0 (and prev from its end) and returns the
// offsets it stops at.
func words(s string, step func(*Boundaries, int) int, from int) []int {
var b Boundaries
b.Reset([]rune(s))
var stops []int
for i := from; ; {
j := step(&b, i)
if j == i {
return stops
}
stops, i = append(stops, j), j
}
}
func TestWordMovement(t *testing.T) {
next := (*Boundaries).NextWord
prev := (*Boundaries).PrevWord
for _, c := range []struct {
s string
right, left []int
}{
{"hello brave new_world", []int{5, 11, 21}, []int{12, 6, 0}},
{"한국어 문장", []int{3, 6}, []int{4, 0}},
{"我们去公园", []int{1, 2, 3, 4, 5}, []int{4, 3, 2, 1, 0}},
{"今天,好", []int{1, 2, 4}, []int{3, 1, 0}},
{"今日は直接骨を見た", []int{1, 2, 3, 4, 5, 6, 7, 8, 9}, []int{8, 7, 6, 5, 4, 3, 2, 1, 0}},
{"Go语言 is fun", []int{2, 3, 4, 7, 11}, []int{8, 5, 3, 2, 0}},
{"カタカナとabc", []int{1, 2, 3, 4, 5, 8}, []int{5, 4, 3, 2, 1, 0}},
} {
n := len([]rune(c.s))
if got := words(c.s, next, 0); !slices.Equal(got, c.right) {
t.Errorf("%q: NextWord stops at %v, want %v", c.s, got, c.right)
}
if got := words(c.s, prev, n); !slices.Equal(got, c.left) {
t.Errorf("%q: PrevWord stops at %v, want %v", c.s, got, c.left)
}
}
}
func TestWordAtCJK(t *testing.T) {
s := "say 我们去,ok_1\nx"
var b Boundaries
b.Reset([]rune(s))
for _, c := range []struct{ i, start, end int }{
{0, 0, 3}, {3, 3, 4}, {4, 4, 5}, {5, 5, 6}, {6, 6, 7}, {7, 7, 8}, {8, 8, 12}, {11, 8, 12}, {12, 12, 12}, {13, 13, 14},
} {
if a, z := b.WordAt(c.i); a != c.start || z != c.end {
t.Errorf("WordAt(%d) = %d, %d, want %d, %d", c.i, a, z, c.start, c.end)
}
}
}
+141
View File
@@ -0,0 +1,141 @@
package text
import (
"hash/maphash"
"math"
"strings"
"unicode"
"unsafe"
)
// Wrapping a text at a new width needs its line breaks, which the system's
// text engine finds as it shapes the text again. But a line of Latin text is
// a run of the glyphs of the whole text, moved back to the start of the line.
// So a text wrapped across widths is shaped once into one line, whose glyphs
// its lines take, as GPUI does: Core Text's (wrap_darwin.go) and
// DirectWrite's (wrap_windows.go).
//
// Lines break where the system surely would: at the spaces before plain
// words. What could tell them apart goes to the system: all but plain Latin
// text, and a line ending where the next word does not fit and may break
// inside itself, or is too long for a line. And the first texts of a font,
// and one in every few hundred after them, are also wrapped by the system: a
// font where the two differ is left to it from then on.
const (
// wrapCheckedFirst is how many wrappings in a font are checked before it
// is trusted, and wrapCheckedEvery how often after that.
wrapCheckedFirst = 16
wrapCheckedEvery = 256
// wrapTolerance is how far a position may be from the system's, which
// hands them over rounded.
wrapTolerance = 1e-3
)
// wrapFont is what wrapping keeps for a font.
type wrapFont struct {
// space is the advance of a space with nothing after it, which a space
// ending a line has; spaceKnown tells that it was measured.
space float32
spaceKnown bool
// lines is how many texts were wrapped, checked how many of them the
// system agreed with, and disagreed that it did not with one.
lines, checked uint64
disagreed bool
}
// shapedWhole is a text shaped into one line: for each rune its glyph, its
// advance, and the pen before it, with the pen at the end.
type shapedWhole struct {
font *Font
ids []uint32
advances []float32
pens []float64
}
// plainLatin reports whether text is ASCII or Latin-1 letters, without tabs and
// other marks line breaking or shaping may treat apart.
func plainLatin(text []rune) bool {
for _, r := range text {
if r < 0x20 || r > 0x7E && (r < 0xC0 || r > 0xFF) {
return false
}
}
return true
}
// plainWord reports whether a line can only break before or after a word:
// letters and digits, perhaps with an apostrophe, which may open with a bracket
// or a quote, and close with them or a mark of punctuation.
func plainWord(word []rune) bool {
i, n := 0, len(word)
for i < n && strings.ContainsRune("([{\"'", word[i]) {
i++
}
for n > i && strings.ContainsRune(".,;:!?)]}\"'", word[n-1]) {
n--
}
if i == n {
return false
}
for _, r := range word[i:n] {
if !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '\'' {
return false
}
}
return true
}
func growTo[T any](s []T, n int) []T {
if cap(s) < n {
return make([]T, n)
}
return s[:n]
}
// textHash is what a text comes to in the key of what is kept of it, its own
// rather than a string of it, which would take making one for each text at
// each width.
func textHash(seed maphash.Seed, text []rune) uint64 {
return maphash.Bytes(seed, unsafe.Slice((*byte)(unsafe.Pointer(&text[0])), len(text)*4))
}
// runeIndex returns the identity map of a text of BMP runes, as appendUTF16
// makes it, up to its end.
func runeIndex(index []int, n int) []int {
index = growTo(index, n+1)
for i := range index {
index[i] = i
}
return index
}
// sameLines reports whether lines wrapped from one line are those the system
// wrapped.
func sameLines(a, b []shapedLine) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i].start != b[i].start || a[i].end != b[i].end {
return false
}
if len(a[i].runs) != len(b[i].runs) || len(a[i].runs) == 0 {
return false
}
for r := range a[i].runs {
x, y := &a[i].runs[r], &b[i].runs[r]
if x.font != y.font || x.start != y.start || x.end != y.end || len(x.glyphs) != len(y.glyphs) {
return false
}
for k := range x.glyphs {
g, h := &x.glyphs[k], &y.glyphs[k]
if g.ID != h.ID || g.Font != h.Font || g.Cluster != h.Cluster || g.RTL != h.RTL || g.Y != h.Y ||
math.Abs(float64(g.X-h.X)) > wrapTolerance || math.Abs(float64(g.Advance-h.Advance)) > wrapTolerance {
return false
}
}
}
}
return true
}
+148
View File
@@ -0,0 +1,148 @@
package text
// Core Text's wrapping from one line (wrap.go). Core Text finds line breaks
// a line at a time, opening a line for each and shaping it into glyphs
// through a call for each of its properties. But a line of Latin text is a run
// of the glyphs of the whole text, moved back to the start of the line. So a
// text kept across widths (keptTypesetter) is shaped once into one line, whose
// glyphs its lines take, as GPUI does.
//
// Lines break where Core Text surely would: at the spaces before plain words.
// What could tell them apart goes to Core Text, line by line, or whole: all but
// plain Latin text, and a line ending where the next word does not fit and may
// break inside itself, or is too long for a line. And the first texts of a font,
// and one in every few hundred after them, are also wrapped by Core Text: a font
// where the two differ is left to it from then on.
// shapeWhole shapes a kept text into one line, or returns nil if it does not
// come out as one run with a glyph for each rune.
func (e *coreText) shapeWhole(typesetter uintptr, text []rune, italic bool) *shapedWhole {
n := len(text)
line := ct.typesetterCreateLine(typesetter, cfRange{0, n})
if line == 0 {
return nil
}
defer ct.release(line)
runs := ct.lineGetGlyphRuns(line)
if ct.arrayGetCount(runs) != 1 {
return nil
}
run := ct.arrayGetValueAtIndex(runs, 0)
if ct.runGetGlyphCount(run) != n || ct.runGetStatus(run)&ctRunStatusRightToLeft != 0 {
return nil
}
attrs := ct.runGetAttributes(run)
w := &shapedWhole{
font: e.runFont(ct.dictionaryGetValue(attrs, ct.fontAttributeName), italic || ct.dictionaryGetValue(attrs, e.italic) != 0),
ids: make([]uint32, n),
advances: make([]float32, n),
pens: make([]float64, n+1),
}
e.runIDs = growTo(e.runIDs, n)
e.runPoints = growTo(e.runPoints, n)
e.runAdvances = growTo(e.runAdvances, n)
e.runIndices = growTo(e.runIndices, n)
all := cfRange{}
ct.runGetGlyphs(run, all, &e.runIDs[0])
ct.runGetPositions(run, all, &e.runPoints[0])
ct.runGetAdvances(run, all, &e.runAdvances[0])
ct.runGetStringIndices(run, all, &e.runIndices[0])
for i := range n {
if e.runIndices[i] != i || e.runPoints[i].y != 0 {
return nil
}
w.ids[i] = uint32(e.runIDs[i])
w.advances[i] = float32(e.runAdvances[i].w)
w.pens[i] = e.runPoints[i].x
}
w.pens[n] = w.pens[n-1] + e.runAdvances[n-1].w
return w
}
// wrapKept wraps a kept text from its one line, or returns nil for Core Text to
// wrap it.
func (e *coreText) wrapKept(kept *keptTypesetter, text []rune, style Style, width float32) []shapedLine {
f := e.wrapFonts[kept.font]
if f == nil {
f = &wrapFont{}
e.wrapFonts[kept.font] = f
}
if f.disagreed {
return nil
}
if !kept.shaped {
kept.shaped = true
kept.whole = e.shapeWhole(kept.typesetter, text, style.Italic)
}
w := kept.whole
if w == nil {
return nil
}
if !f.spaceKnown {
f.spaceKnown = true
f.space = -1
if run := oneRun(e.shapeText([]rune{' '}, Style{Size: style.Size, Family: style.Family, Weight: style.Weight, Italic: style.Italic}, nil, 0, false, false)); run != nil && len(run.glyphs) == 1 {
f.space = run.glyphs[0].Advance
}
}
if f.space < 0 {
return nil
}
n := len(text)
limit := float64(width) + 1.0/1024
var lines []shapedLine
mark := len(e.shapeScratch.lines)
for start := 0; start < n; {
end, pen, plain := start, w.pens[start], true
for i := start; i < n; {
// A word and the spaces after it, which take no room.
word := i
for i < n && text[i] != ' ' {
i++
}
fits := w.pens[i]-pen <= limit
plain = plainWord(text[word:i])
if !fits {
break
}
for i < n && text[i] == ' ' {
i++
}
end = i
}
if end == start || end < n && !plain {
// The first word does not fit, or the next may break inside.
count := max(ct.suggestLineBreak(kept.typesetter, start, limit), 1)
line := ct.typesetterCreateLine(kept.typesetter, cfRange{start, count})
if line == 0 {
return nil
}
e.index = runeIndex(e.index, n)
lines = e.addLine(mark, e.line(line, e.index, n, style.Italic))
ct.release(line)
start += count
continue
}
glyphs := e.glyphRoom(end - start)
for i := start; i < end; i++ {
glyphs[i-start] = Glyph{Font: w.font, ID: w.ids[i], X: float32(w.pens[i] - pen), Advance: w.advances[i], Cluster: i}
}
if end < n {
glyphs[end-start-1].Advance = f.space
}
line := shapedLine{start: start, end: end, runs: e.addRun(len(e.shapeScratch.runs), shapedRun{font: w.font, start: start, end: end, glyphs: glyphs})}
lines = e.addLine(mark, line)
start = end
}
f.lines++
if f.checked < wrapCheckedFirst || f.lines%wrapCheckedEvery == 0 {
e.index = runeIndex(e.index, n)
shaped := e.typesetLines(kept.typesetter, n, width, nil, false, false, e.index, style.Italic)
if !sameLines(lines, shaped) {
f.disagreed = true
return shaped
}
f.checked++
}
return lines
}
+191
View File
@@ -0,0 +1,191 @@
//go:build windows && (amd64 || arm64)
package text
import "slices"
// DirectWrite's wrapping from one line (wrap.go). DirectWrite lays a text out
// again at each width, a text layout of its own with its runs analyzed and
// shaped anew. A plain Latin text wrapped across widths is shaped once into
// one line instead, kept while frames wrap it, and its lines take their
// glyphs from it. A line DirectWrite could break otherwise has the whole text
// laid out by DirectWrite.
// wholeKey is a text of a text format (formatKey), which its hash stands for.
type wholeKey struct {
format formatKey
text uint64
}
// keptWhole is a text shaped into one line, nil when it does not come out
// as one run with a glyph for each rune, kept across frames.
type keptWhole struct {
text []rune
whole *shapedWhole
used uint64
}
// keptWholeFrames is how many frames a text stays kept unused: windows take
// turns, so a text wrapping again in each frame of its window may wait for
// the others'.
const keptWholeFrames = 8
// wrapsFromWhole reports whether text of a style and spans, wrapped to width
// in a direction, may be wrapped from its one line.
func wrapsFromWhole(text []rune, style Style, spans []Span, width float32, rtl, wholeWords bool) bool {
return width > 0 && len(spans) == 0 && !rtl && !wholeWords && style.tabStop <= 0 && style.LetterSpacing == 0 && style.Features == "" &&
!keepsAnyWords(style.Lang, nil) && plainLatin(text) && !languageShapes(text, style.Lang)
}
// wrapWhole wraps text from its one line, or returns nil for DirectWrite to
// wrap it.
func (e *dwrite) wrapWhole(text []rune, style Style, width float32) []shapedLine {
family, custom := e.family(style.Family)
format := formatKey{style.Family, family, custom, style.weight(), style.Italic, style.FontSize(), style.Lang}
f := e.wrapFonts[format]
if f == nil {
f = &wrapFont{}
e.wrapFonts[format] = f
}
if f.disagreed {
return nil
}
key := wholeKey{format, textHash(e.textSeed, text)}
kept := e.wholes[key]
// Texts of one hash are rare: one takes the other's place.
if kept == nil || !slices.Equal(kept.text, text) {
kept = &keptWhole{text: slices.Clone(text), whole: e.shapeWhole(text, style)}
e.wholes[key] = kept
}
kept.used = e.frame
w := kept.whole
if w == nil {
return nil
}
n := len(text)
// As shapeText wraps.
limit := float64(width) + 1e-3
var lines []shapedLine
mark := len(e.shapeScratch.lines)
for start := 0; start < n; {
end, pen, plain := start, w.pens[start], true
last := rune(0) // the last character of the last word that fits
for i := start; i < n; {
// A word and the spaces after it, which take no room.
word := i
for i < n && text[i] != ' ' {
i++
}
fits := w.pens[i]-pen <= limit
plain = plainWord(text[word:i])
if !fits {
break
}
if i > word {
last = text[i-1]
}
for i < n && text[i] == ' ' {
i++
}
end = i
}
if end == start || end < n && (!plain || !breaksAcross(last, text[end])) {
// The first word does not fit, the next may break inside, or
// the spaces before it may not break.
return nil
}
// DirectWrite shapes the whole text before breaking it into lines,
// whose glyphs keep their advances, and draws the spaces ending a
// line as a run of their own.
glyphs := e.glyphRoom(end - start)
for i := start; i < end; i++ {
glyphs[i-start] = Glyph{Font: w.font, ID: w.ids[i], X: float32(w.pens[i] - pen), Advance: w.advances[i], Cluster: i}
}
spaces := end
for spaces > start && text[spaces-1] == ' ' {
spaces--
}
var runs []shapedRun
runMark := len(e.shapeScratch.runs)
if spaces > start {
runs = e.addRun(runMark, shapedRun{font: w.font, start: start, end: spaces, glyphs: glyphs[: spaces-start : spaces-start]})
}
if spaces < end {
runs = e.addRun(runMark, shapedRun{font: w.font, start: spaces, end: end, glyphs: glyphs[spaces-start:]})
}
lines = e.addLine(mark, shapedLine{start: start, end: end, runs: runs})
start = end
}
f.lines++
if f.checked < wrapCheckedFirst || f.lines%wrapCheckedEvery == 0 {
shaped := e.shapeText(text, style, nil, width, false, false)
if !sameLines(lines, shaped) {
f.disagreed = true
return shaped
}
f.checked++
}
return lines
}
// breaksAcross reports whether a line surely breaks at the spaces between a
// word ending with last and one starting with next, both plain, which most
// do. Unicode's line breaking keeps an opening bracket with what follows it
// across spaces, and a quotation mark with an opening bracket after it
// (UAX #14, LB14 and LB15).
func breaksAcross(last, next rune) bool {
switch last {
case '(', '[', '{':
return false
case '"', '\'':
return next != '(' && next != '[' && next != '{'
}
return true
}
// shapeWhole shapes text into one line, or returns nil if it does not come
// out in one font with a glyph for each rune, from the left: in one run, or
// two when it ends with spaces, which DirectWrite draws apart.
func (e *dwrite) shapeWhole(text []rune, style Style) *shapedWhole {
lines := e.shapeText(text, style, nil, 0, false, false)
n := len(text)
if len(lines) != 1 || len(lines[0].runs) == 0 || lines[0].runs[0].font == nil {
return nil
}
font := lines[0].runs[0].font
w := &shapedWhole{font: font, ids: make([]uint32, n), advances: make([]float32, n), pens: make([]float64, n+1)}
i := 0
for _, run := range lines[0].runs {
if run.font != font || run.start != i {
return nil
}
for _, g := range run.glyphs {
if i == n || g.Cluster != i || g.Y != 0 || g.RTL || g.Font != font {
return nil
}
w.ids[i], w.advances[i], w.pens[i] = g.ID, g.Advance, float64(g.X)
i++
}
if run.end != i {
return nil
}
}
if i != n {
return nil
}
w.pens[n] = w.pens[n-1] + float64(w.advances[n-1])
return w
}
// endFrame lets go of the texts that stopped wrapping again.
func (e *dwrite) endFrame() {
e.frame++
for k, t := range e.wholes {
if e.frame-t.used > keptWholeFrames {
delete(e.wholes, k)
}
}
}
// releaseShaping lets go of all texts kept, as windows go idle.
func (e *dwrite) releaseShaping() { clear(e.wholes) }
+172
View File
@@ -0,0 +1,172 @@
//go:build windows && (amd64 || arm64)
package text
import (
"math/rand/v2"
"os"
"strconv"
"strings"
"testing"
)
// Latin text wrapped from one line is what DirectWrite wraps, for any text
// made of what wrapping takes, at any width, in a font's first checks and
// beyond.
func TestDWriteWrapFuzz(t *testing.T) {
iterations := 400
if n, err := strconv.Atoi(os.Getenv("MYGO_WRAP_FUZZ")); err == nil {
iterations = n
}
words := []string{"a", "I", "to", "the", "window", "layout", "AVATAR", "Type", "fi", "ffl", "office", "don't", "well-known", "e.g.", "U.S.A.", "1,234.56", "3.14", "$5", "50%", "a/b", "http://example.com/path?q=1&r=2", "(paren)", "[box]", "{curly}", "\"quoted\"", "'single'", "end.", "yes,", "stop;", "wait:", "what?", "no!", "x+y", "a=b", "#tag", "@me", "under_score", "<tag>", "~", "*star*", "pipe|", `back\slash`, "café", "Über", "señor", "naïve", "Ærø", "garçon", "verylongwordthatdoesnotfitalineandhastobrokenbydirectwrite", "--", "-", "...", "A-1", "1-2", "T.", "V,", "Y.", "L'", "f)", "ß"}
seps := []string{" ", " ", " ", " ", " ", " ", "", "-", "/"}
styles := []Style{{Size: 13}, {Size: 14, Weight: 700}, {Size: 13, Italic: true}, {Size: 15, Family: "Georgia"}, {Size: 12, Family: "Arial"}, {Size: 13, Family: "Consolas"}, {Size: 16, Family: "Times New Roman"}, {Size: 13, Family: "Calibri"}, {Size: 13, Lang: "en-US"}}
rng := rand.New(rand.NewPCG(1, 2))
s := newSystem()
s.mu.Lock()
defer s.mu.Unlock()
e := s.engine().(*dwrite)
wrapped, leftOut := 0, 0
defer func() { t.Logf("%d wrappings compared, %d left to DirectWrite", wrapped, leftOut) }()
for it := range iterations {
var b strings.Builder
for range 1 + rng.IntN(80) {
b.WriteString(words[rng.IntN(len(words))])
b.WriteString(seps[rng.IntN(len(seps))])
}
text := []rune(b.String())
style := styles[it%len(styles)]
if !wrapsFromWhole(text, style, nil, 1, false, false) {
continue
}
family, custom := e.family(style.Family)
format := formatKey{style.Family, family, custom, style.weight(), style.Italic, style.FontSize(), style.Lang}
for _, width := range []float32{float32(20 + rng.IntN(100)), float32(100 + rng.IntN(400)), float32(300+rng.IntN(500)) + rng.Float32()} {
e.resetScratch()
// Every wrapping checked by the test, not only some.
if f := e.wrapFonts[format]; f != nil {
f.checked = wrapCheckedFirst
f.lines = 1
}
got := e.wrapWhole(text, style, width)
if got == nil {
// What does not shape as a glyph for each rune, or may
// break otherwise, stays with DirectWrite.
leftOut++
continue
}
wrapped++
want := e.shapeText(text, style, nil, width, false, false)
if !sameLines(got, want) {
report(t, text, style, width, got, want)
return
}
}
}
for k, f := range e.wrapFonts {
if f.disagreed {
t.Errorf("%+v disagreed with DirectWrite", k)
}
}
if wrapped == 0 {
t.Error("nothing was wrapped from one line")
}
}
// A text wrapped across widths is kept while frames wrap it, and let go of
// after.
func TestDWriteWrapKept(t *testing.T) {
s := newSystem()
s.mu.Lock()
defer s.mu.Unlock()
e := s.engine().(*dwrite)
text := []rune("the window layout wraps again at every width of the window")
style := Style{Size: 13}
for w := 100; w < 140; w++ {
e.resetScratch()
if e.wrapWhole(text, style, float32(w)) == nil {
t.Fatalf("not wrapped from one line at %d", w)
}
e.endFrame()
}
if len(e.wholes) != 1 {
t.Fatalf("%d texts kept, want 1", len(e.wholes))
}
for range keptWholeFrames + 1 {
e.endFrame()
}
if len(e.wholes) != 0 {
t.Errorf("%d texts kept after they stopped wrapping", len(e.wholes))
}
}
// report tells the first line where wrapped text differs from DirectWrite's.
func report(t *testing.T, text []rune, style Style, width float32, got, want []shapedLine) {
t.Helper()
t.Logf("text %q", string(text))
for i := range min(len(got), len(want)) {
if got[i].start != want[i].start || got[i].end != want[i].end {
t.Fatalf("in %+v at %v, line %d is %q, DirectWrite's %q", style, width, i, string(text[got[i].start:got[i].end]), string(text[want[i].start:want[i].end]))
}
if !sameLines(got[i:i+1], want[i:i+1]) {
x, y := got[i].runs, want[i].runs
t.Errorf("in %+v at %v, line %d %q has %d runs, DirectWrite's %d", style, width, i, string(text[got[i].start:got[i].end]), len(x), len(y))
if len(x) == 1 && len(y) == 1 {
for k := range min(len(x[0].glyphs), len(y[0].glyphs)) {
g, h := x[0].glyphs[k], y[0].glyphs[k]
if g.ID != h.ID || g.X != h.X || g.Advance != h.Advance {
t.Errorf(" glyph %d (%q): id %d/%d x %v/%v advance %v/%v", k, string(text[g.Cluster]), g.ID, h.ID, g.X, h.X, g.Advance, h.Advance)
}
}
}
t.FailNow()
}
}
t.Fatalf("in %+v at %v, %d lines, DirectWrite's %d", style, width, len(got), len(want))
}
// Prose of plain words, as most text is, wraps from one line in every font,
// as DirectWrite wraps it.
func TestDWriteWrapProse(t *testing.T) {
words := []string{"a", "I", "to", "the", "window", "layout", "AVATAR", "Type", "don't", "end.", "yes,", "stop;", "wait:", "what?", "no!", "(paren)", "\"quoted\"", "café", "Über", "señor", "naïve", "Ærø", "garçon", "T.", "V,", "Y.", "L'", "ß", "WAVE", "Toyota", "AVAST", "1984", "x2"}
styles := []Style{{Size: 13}, {Size: 14, Weight: 700}, {Size: 13, Italic: true}, {Size: 15, Family: "Georgia"}, {Size: 12, Family: "Arial"}, {Size: 13, Family: "Consolas"}, {Size: 16, Family: "Times New Roman"}, {Size: 11, Family: "Tahoma"}, {Size: 13, Lang: "en-US"}}
rng := rand.New(rand.NewPCG(3, 4))
s := newSystem()
s.mu.Lock()
defer s.mu.Unlock()
e := s.engine().(*dwrite)
wrapped, leftOut := 0, 0
for it := range 600 {
var b strings.Builder
for k := range 1 + rng.IntN(70) {
if k > 0 {
b.WriteString(" ")
}
b.WriteString(words[rng.IntN(len(words))])
}
text := []rune(b.String())
style := styles[it%len(styles)]
family, custom := e.family(style.Family)
format := formatKey{style.Family, family, custom, style.weight(), style.Italic, style.FontSize(), style.Lang}
for _, width := range []float32{float32(60 + rng.IntN(100)), float32(150+rng.IntN(400)) + rng.Float32()} {
e.resetScratch()
if f := e.wrapFonts[format]; f != nil {
f.checked = wrapCheckedFirst
f.lines = 1
}
got := e.wrapWhole(text, style, width)
if got == nil {
leftOut++
continue
}
wrapped++
if want := e.shapeText(text, style, nil, width, false, false); !sameLines(got, want) {
report(t, text, style, width, got, want)
}
}
}
t.Logf("%d wrappings compared, %d left to DirectWrite", wrapped, leftOut)
if leftOut > wrapped/10 {
t.Errorf("%d of %d wrappings left to DirectWrite", leftOut, wrapped+leftOut)
}
}