text

package
v0.0.0-...-91353d5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 19 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package text is gophics's text stack: shaping, bidi, font fallback, and line breaking, built on go-text/typesetting (the shared pure-Go HarfBuzz-family stack used by Gio, Fyne, and Ebitengine). It exists because the rendering backend's own shaper handles Latin only: gophics shapes here and hands positioned glyph outlines to the paint backend.

Coordinates follow gophics conventions: logical pixels, y down, line origin at the left end of the baseline.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Direction

type Direction uint8

Direction is a paragraph's base writing direction. It decides two things a per-run bidi analysis cannot: how runs of opposite direction are ordered relative to each other, and which edge a line is anchored to.

const (
	// DirAuto derives the base direction from the text itself — the first
	// strong character wins (UAX #9 rules P2/P3), which is what a browser
	// does for dir="auto". This is the zero value, so a Shaper handles
	// Arabic and Hebrew correctly without being told about them.
	DirAuto Direction = iota
	// DirLTR forces a left-to-right base direction.
	DirLTR
	// DirRTL forces a right-to-left base direction — the setting a UI in an
	// RTL locale wants even for the strings that happen to be Latin.
	DirRTL
)

type Editor

type Editor struct {
	// contains filtered or unexported fields
}

Editor is a single-line text editing model: content, caret, and selection. It is pure state — widgets own one and render from it.

The caret and anchor (see Caret/Anchor) are rune indices in [0, Len]. When they differ, [min,max) is the selection and the caret is the moving end. Horizontal movement and deletion step by grapheme cluster (UAX #29), so emoji and combining sequences behave as single characters.

func (*Editor) Anchor

func (e *Editor) Anchor() int

Anchor returns the selection anchor, a rune index in [0, Len]; when it differs from Caret, [min,max) of the two is the selection.

func (*Editor) CanRedo

func (e *Editor) CanRedo() bool

func (*Editor) CanUndo

func (e *Editor) CanUndo() bool

CanUndo and CanRedo report whether the corresponding menu item is enabled.

func (*Editor) Caret

func (e *Editor) Caret() int

Caret returns the caret position, a rune index in [0, Len].

func (*Editor) DeleteBackward

func (e *Editor) DeleteBackward()

DeleteBackward deletes the selection, or the grapheme before the caret.

func (*Editor) DeleteForward

func (e *Editor) DeleteForward()

DeleteForward deletes the selection, or the grapheme after the caret.

func (*Editor) DeleteToLineEnd

func (e *Editor) DeleteToLineEnd()

DeleteToLineEnd deletes from the caret to the end of its line — Ctrl+K. On an empty remainder it deletes the newline itself, as Emacs does, so repeated Ctrl+K eats lines.

func (*Editor) DeleteToLineStart

func (e *Editor) DeleteToLineStart()

DeleteToLineStart deletes from the caret to the start of its line — Cmd+ Backspace on a Mac. A selection is deleted instead.

func (*Editor) DeleteWordBackward

func (e *Editor) DeleteWordBackward()

DeleteWordBackward deletes from the caret to the start of the previous word, or the selection if there is one.

func (*Editor) DeleteWordForward

func (e *Editor) DeleteWordForward()

DeleteWordForward deletes from the caret to the end of the next word, or the selection if there is one.

func (*Editor) End

func (e *Editor) End(extend bool)

func (*Editor) HasSelection

func (e *Editor) HasSelection() bool

HasSelection reports whether a nonempty range is selected.

func (*Editor) Home

func (e *Editor) Home(extend bool)

Home moves to the start; End to the end.

func (*Editor) Insert

func (e *Editor) Insert(s string)

Insert replaces the selection (or inserts at the caret) with s.

func (*Editor) Len

func (e *Editor) Len() int

Len returns the content length in runes.

func (*Editor) LineEnd

func (e *Editor) LineEnd(extend bool)

LineEnd is LineHome's counterpart.

func (*Editor) LineHome

func (e *Editor) LineHome(extend bool)

LineHome moves to the start of the caret's line — Home on a multiline field, Cmd+Left on a Mac, Ctrl+A in Emacs bindings. In single-line text this is the start of the text.

func (*Editor) Move

func (e *Editor) Move(dir int, extend bool)

Move moves the caret one grapheme left (dir < 0) or right (dir > 0). With extend, the anchor stays put (shift-selection); otherwise a selection collapses to its edge in the movement direction.

func (*Editor) MoveTo

func (e *Editor) MoveTo(idx int, extend bool)

MoveTo places the caret at the given rune index; with extend the anchor stays put.

func (*Editor) MoveWord

func (e *Editor) MoveWord(dir int, extend bool)

MoveWord moves the caret one word left (dir < 0) or right, extending the selection when extend is set. Without extend, a selection collapses to its edge first, the way Move does.

func (*Editor) MoveWordStart

func (e *Editor) MoveWordStart(extend bool)

MoveWordStart is Windows' word-right: to the start of the next word rather than the end of this one. Ctrl+Right on a PC lands before the next word, where Alt+Right on a Mac lands after the current one; both are "a word", and a user of each expects theirs. Left is the same on both platforms.

func (*Editor) Redo

func (e *Editor) Redo() bool

Redo reapplies the last undone group; false if there was none.

func (*Editor) Replace

func (e *Editor) Replace(s string)

Replace is Insert as one undo step that never coalesces with typing: a paste, an autocorrect, a programmatic change.

func (*Editor) SelectAll

func (e *Editor) SelectAll()

SelectAll selects the whole content.

func (*Editor) SelectLineAt

func (e *Editor) SelectLineAt(idx int)

SelectLineAt selects the whole line containing idx — a triple click.

func (*Editor) SelectWordAt

func (e *Editor) SelectWordAt(idx int)

SelectWordAt selects the word (run of letters/digits/underscore) containing idx — the double-click-to-select behavior. If idx isn't on a word character, it selects the single character there, matching common editor behavior.

func (*Editor) SelectedText

func (e *Editor) SelectedText() string

SelectedText returns the selected content.

func (*Editor) Selection

func (e *Editor) Selection() (start, end int)

Selection returns the selected range [start, end); start == end means no selection.

func (*Editor) SetSelection

func (e *Editor) SetSelection(anchor, caret int)

SetSelection places the anchor and caret, clamping both into range. This is the only way to set them from outside the package: a raw write could leave an index past the end of the text and panic the next edit.

func (*Editor) SetText

func (e *Editor) SetText(s string)

SetText replaces the content and clamps the caret/selection.

func (*Editor) Text

func (e *Editor) Text() string

Text returns the content.

func (*Editor) Undo

func (e *Editor) Undo() bool

Undo reverts the last edit group; false if there was none.

type Font

type Font struct {
	// contains filtered or unexported fields
}

Font is a parsed font usable for shaping and outline extraction.

func Parse

func Parse(data []byte) (*Font, error)

Parse parses TTF/OTF font data.

func (*Font) AppendGlyphPath

func (f *Font) AppendGlyphPath(sink PathSink, gid uint32, size float32, dx, dy float32)

AppendGlyphPath emits gid's outline at the given size into sink, with the glyph origin (baseline pen position) at (dx, dy). It emits nothing for a glyph that is not an outline: a colour bitmap glyph (sbix, CBDT), an SVG glyph, or a COLR paint graph. A caller that wants those drawn must ask separately — ColorGlyphBox and ColorGlyphImage handle the bitmap kind, which is what colour emoji are on macOS, iOS and Android; see coloremoji.go for why COLR is out of scope and what that costs on Windows.

func (*Font) ColorGlyphBox

func (f *Font) ColorGlyphBox(gid uint32, size float32) (geom.Rect, bool)

ColorGlyphBox reports where gid's colour bitmap paints at the given logical size, relative to the pen position on the baseline, y down — so the top of the glyph is negative, matching InkBounds elsewhere in gophics. ok is false for every glyph this cannot blit: outlines, SVG glyphs, COLR paint graphs (see the package note above), and bitmap formats other than PNG.

This is separate from ColorGlyphImage because the two callers need different halves. Ink bounds and damage need the box and must not pay to decode a PNG; drawing needs the pixels and knows the device scale that decides which strike to decode. The box is the same either way: it comes from the font's glyph extents, which for a bitmap glyph are read out of the bitmap table (and, for Apple Color Emoji, measured as exactly one em square sitting on the baseline and independent of ppem).

func (*Font) ColorGlyphImage

func (f *Font) ColorGlyphImage(gid uint32, ppem int) (image.Image, bool)

ColorGlyphImage decodes gid's colour bitmap at the given pixels-per-em, which must come from ColorGlyphPpem. ok is false for the same set of glyphs ColorGlyphBox rejects, and for a PNG the standard library cannot decode.

ppem is not advisory: it selects the strike. A font asked at ppem 0 — which is what a face gophics never told a size to reports — hands back its *largest* strike, measured at 160x160 and 23,780 bytes of PNG for Apple Color Emoji where the 20-ppem strike is 20x20 and 1,093 bytes. That is 20x the decode and, worse, an 8x minification through the image pipeline's fixed bilinear sampler with no mipmaps, which aliases visibly. Passing the right ppem is the difference between a crisp emoji and a muddy one.

The decode is image/png from the standard library. The font library locates and identifies the bitmap but does not decode it: GlyphBitmap.Data is raw PNG bytes.

Only safe on the goroutine that owns the Shaper. Setting the strike mutates the face, and faces are shared — fontscan hands the same *font.Face to every size, and harfbuzz already writes into a face's cmap cache while shaping, so UseSystemFonts' documented single-goroutine invariant is what makes this sound. The SetPpem call is kept adjacent to the GlyphData call below so no shaping can interleave between them.

func (*Font) ColorGlyphPpem

func (f *Font) ColorGlyphPpem(px int) int

ColorGlyphPpem quantises a wanted size in device pixels to a pixels-per-em value the font actually has a bitmap strike for, or returns 0 when the font has no strikes.

Callers must quantise, for two reasons that are both about the cache above this one. A glyph atlas keyed on the exact device size mints a fresh cell on every frame of a zoom animation, because 33, 34 and 35 device pixels all decode the same 40-ppem strike; and asking twice for two sizes that land on one strike decodes the same PNG twice. Apple Color Emoji carries strikes at ppem 20, 26, 32, 40, 48, 52, 64, 96 and 160, so the quantisation is coarse and the saving is large.

The rule mirrors the font library's own strike choice (sbix.chooseStrike): the smallest strike at least as large as the request, and the largest strike when the request exceeds them all. Mirroring it is what makes the value idempotent — passing the result back in selects the same strike — which is what a cache key needs.

func (*Font) Extents

func (f *Font) Extents(size float32) (ascent, descent, gap float32)

Extents returns the font's line metrics at the given size, y-down: ascent above the baseline, descent below (both positive), plus line gap.

func (*Font) HasGlyph

func (f *Font) HasGlyph(r rune) bool

HasGlyph reports whether the font maps r to a glyph.

func (*Font) NominalGID

func (f *Font) NominalGID(r rune) (uint32, bool)

NominalGID returns the unshaped cmap glyph for r (for tests/tools).

type Glyph

type Glyph struct {
	Font *Font
	GID  uint32
	// Cluster is the rune index (into the shaped string) of the cluster
	// this glyph belongs to — the unit for caret placement and hit testing.
	Cluster int
	// X, Y position the glyph origin relative to the line origin (baseline).
	X, Y float32
	// Advance is the pen advance contributed by this glyph.
	Advance float32
	// RTL reports that the glyph's run reads right to left, which decides
	// which edge the caret "before" its cluster sits on (see CaretX). It is
	// recorded here rather than inferred from neighbouring clusters because
	// a run of one glyph has no neighbours to infer from.
	RTL bool
}

Glyph is one positioned glyph on a line.

type Line

type Line struct {
	Glyphs []Glyph
	// Width is the total advance width.
	Width float32
	// Ascent/Descent/Gap are the maxima over the fonts used (y-down:
	// both ascent and descent positive).
	Ascent, Descent, Gap float32
	// Start/End are the rune range of the source string on this line.
	Start, End int
	// RTL reports that the line's base direction is right-to-left, so it
	// should be anchored to the right edge of its box when the caller is
	// aligning to the "start" of the text rather than to a fixed side.
	RTL bool
}

Line is one shaped, positioned line of text.

func (Line) CaretX

func (l Line) CaretX(idx int) float32

CaretX returns the x position of the caret placed before rune index idx.

In a right-to-left run the caret before a cluster sits at that glyph's right edge, because "before" means earlier in reading order and reading runs the other way. Getting this wrong puts the caret on the far side of the character being typed, which is the usual symptom of an LTR-only implementation.

An index inside a cluster — between the f and the i of an "fi" ligature, where Editor.Move lands because they are separate graphemes — has no glyph edge of its own. The caret is interpolated across the cluster by rune fraction, as browsers do, rather than jumping to the end of the line.

func (Line) IndexAt

func (l Line) IndexAt(x float32) int

IndexAt returns the rune index whose caret position is nearest to x (for click-to-position): the inverse of CaretX.

It is literally that — the index i in [0, Len] minimising |CaretX(i) − x| — because CaretX is what the caret is drawn with, and a click has to land where the caret will appear. Deciding per glyph which half was clicked gave the right answer inside a run and the wrong one at a bidi run boundary, where the index "after" a glyph in reading order can be drawn at the far end of the line: clicking the last glyph of "abc 123" on an RTL line returned 7, drawn at x=0. Two indices can share a position at a run boundary (there is no caret affinity); the later one wins, so a click at the end of the line lands at the end of the text.

type PathSink

type PathSink interface {
	MoveTo(x, y float32)
	LineTo(x, y float32)
	QuadTo(cx, cy, x, y float32)
	CubeTo(c1x, c1y, c2x, c2y, x, y float32)
	Close()
}

PathSink receives a glyph outline as path commands, y down.

type Script

type Script string

Script is the writing system a rune belongs to, as its ISO 15924 four-letter tag: "Latn", "Cyrl", "Grek", "Hani", "Arab", "Hebr", "Deva", "Thai".

Script, not rune, is the unit font fallback works in. A face either covers a script or it does not, so a chain missing Han is missing all 90,000 of its runes; a diagnostic keyed on the rune would repeat itself a thousand times and an on-demand font fetch keyed on the rune would issue a thousand identical requests, where one answer per script settles the matter.

The tag is a string rather than an enum because it is already the name the font world uses — it needs no translation on its way into a URL path, a CSS `unicode-range` comment or a log line — and because it stays correct for scripts gophics has never heard of: a rune from a Unicode block added after this file was written classifies itself.

const (
	// ScriptCommon ("Zyyy") is the tag for runes belonging to no single
	// script: digits, most punctuation, arrows, mathematical operators and
	// box drawing. A face chosen for it is a symbol font, not a text font.
	ScriptCommon Script = "Zyyy"
	// ScriptUnknown ("Zzzz") is the tag for unassigned code points and for
	// anything the table cannot place. A fallback keyed on it will not find
	// a font, which is the correct outcome.
	ScriptUnknown Script = "Zzzz"
	// ScriptEmoji ("Zsye", "Symbols, emoji style") is reported for runes
	// that are script-neutral but pictographic, so that emoji do not land in
	// the same bucket as "→" and ask a symbol font to draw a face.
	//
	// Note that resolving a face for Zsye is not the same as rendering it.
	// The common system emoji fonts carry no outlines, so AppendGlyphPath
	// emits nothing for them — blank, not tofu. What draws instead depends on
	// the table: a bitmap face (Apple Color Emoji's sbix, Android's CBDT Noto
	// Color Emoji) is blitted through ColorGlyphImage, a COLR face (Windows'
	// Segoe UI Emoji) is not drawn at all, and a monochrome outline face such
	// as Noto Emoji goes down the ordinary outline path. See coloremoji.go.
	ScriptEmoji Script = "Zsye"
)

func ScriptOf

func ScriptOf(r rune) Script

ScriptOf reports the script of r.

The classification itself is go-text/typesetting's UAX #24 table, which the segmenter already carries in every gophics binary, so this costs no new data — the point of deriving the answer there rather than keeping a second table here.

type Shaper

type Shaper struct {
	// contains filtered or unexported fields
}

Shaper shapes text through a font fallback chain, optionally extended by the system's fonts (UseSystemFonts). It caches segmentation and wrapping state; it is not safe for concurrent use (UI goroutine only).

func NewShaper

func NewShaper(fonts ...*Font) *Shaper

NewShaper returns a shaper over the given fallback chain; fonts[0] is the primary. At least one font is required before shaping.

func (*Shaper) Line

func (s *Shaper) Line(str string, size float32) Line

Line shapes str as a single line (no wrapping; newlines are not special).

func (*Shaper) OnMissingGlyph

func (s *Shaper) OnMissingGlyph(fn func(r rune, script Script))

OnMissingGlyph replaces what a Shaper does the first time it finds a rune no font in its chain covers — the tofu case, where shaping falls back to the primary face and draws the wrong glyph or a box.

fn is called once per script, not once per rune (see Script), from the goroutine that is shaping. Passing nil silences the report entirely.

There is a report at all, rather than a silent fallback, because the failure is otherwise undiagnosable from inside the program: the shaper returns glyphs, the painter draws them, nothing errors, and the developer is left looking at a row of boxes with no string to search for. On the web that was the whole of the system-font story — UseSystemFonts there was a no-op that returned nil, so an app rendering Japanese had no way to learn that it never could. The default report names the rune, its script and the three things that fix it; an app that would rather route it somewhere (a telemetry sink, a developer overlay) passes its own fn.

func (*Shaper) Paragraph

func (s *Shaper) Paragraph(str string, size, maxWidth float32) []Line

Paragraph shapes and wraps str to maxWidth (Inf or <= 0 disables wrapping). Newlines force breaks. Line Start/End are rune indices into str; a trailing newline yields an empty final line.

func (*Shaper) Primary

func (s *Shaper) Primary() *Font

Primary returns the primary font, or nil.

func (*Shaper) SetDirection

func (s *Shaper) SetDirection(d Direction)

SetDirection sets the base writing direction for subsequent shaping. The default, DirAuto, reads it off each paragraph's own content.

func (*Shaper) SetFonts

func (s *Shaper) SetFonts(fonts ...*Font)

SetFonts replaces the fallback chain.

func (*Shaper) ShareSystemFonts

func (s *Shaper) ShareSystemFonts(other *Shaper)

ShareSystemFonts gives s the system font map other loaded with UseSystemFonts (or nothing, if other has none), so one scan serves every Shaper of an owner. The two must then be used from the same goroutine: the map's faces carry shaping caches that are not safe to write concurrently.

func (*Shaper) UseSystemFonts

func (s *Shaper) UseSystemFonts(cacheDir string) error

UseSystemFonts extends the fallback chain with the platform's installed fonts (via fontscan): runes not covered by the explicit chain — CJK, emoji, symbols — resolve to a system font. cacheDir holds fontscan's index ("" uses the OS user cache dir). Scanning is slow the first time and cached afterward; loading the index is tens of milliseconds each call, so an owner with several Shapers should scan once and hand the result on with ShareSystemFonts rather than call this on each.

The map is private to this Shaper and whoever it is shared with, never to the process. It cannot be otherwise: fontscan's FontMap hands out *font.Face values it caches, and harfbuzz writes into a Face's cmap cache while shaping, so two goroutines shaping through faces from one map race on the faces themselves — a lock around ResolveFace would not reach that. Sharing among the Shapers of one Painter is fine because they all run on that app's UI goroutine.

This lives in a native-only file so the heavy fontscan package (OS font scanning) is not linked into the wasm binary, where there are no system fonts to scan; see the js stub in system_js.go.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL