text

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 22 Imported by: 0 modules, 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 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.

Index

Constants

View Source
const Shades = 4

Shades is the number of shades of text.

Variables

This section is empty.

Functions

func EncodeSpans

func EncodeSpans(spans []Span) string

EncodeSpans writes spans for Params.Spans, which, as a string, keeps Params a value layouts are cached by.

Types

type Affinity

type Affinity uint8

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.

const (
	Downstream Affinity = iota
	Upstream
)

type Align

type Align uint8

Align is the horizontal alignment of the lines of a layout.

const (
	// Start aligns lines to the left, or to the right in right-to-left
	// paragraphs.
	Start Align = iota
	Center
	End
	// Left and Right align lines so whatever their direction, as the
	// start and the end of an interface laid out right to left do.
	Left
	Right
)

type Boundaries

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

Boundaries finds grapheme and word boundaries in text.

func (*Boundaries) GraphemeOffsets

func (b *Boundaries) GraphemeOffsets() []int

GraphemeOffsets returns a copy of the grapheme starts and text's end for a retained shaped-text layout.

func (*Boundaries) NextGrapheme

func (b *Boundaries) NextGrapheme(i int) int

NextGrapheme returns the end of the grapheme starting at or containing i.

func (*Boundaries) NextWord

func (b *Boundaries) NextWord(i int) int

NextWord returns the end of the word after i, skipping what is between.

func (*Boundaries) PrevGrapheme

func (b *Boundaries) PrevGrapheme(i int) int

PrevGrapheme returns the start of the grapheme before i.

func (*Boundaries) PrevWord

func (b *Boundaries) PrevWord(i int) int

PrevWord returns the start of the word before i.

func (*Boundaries) Reset

func (b *Boundaries) Reset(runes []rune)

Reset prepares b for runes.

func (*Boundaries) WordAt

func (b *Boundaries) WordAt(i int) (start, end int)

WordAt returns the word, or the run of other runes, around i.

type CaretPosition

type CaretPosition struct {
	Index    int
	Affinity Affinity
}

type Decoration

type Decoration uint8

Decoration is a line drawn along text.

const (
	Underline Decoration = iota
	Strikethrough
)

type Font

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
	// contains filtered or unexported fields
}

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.

type FontFamily

type FontFamily struct {
	Name string
	// Monospaced is whether its regular font gives every character the
	// same advance.
	Monospaced bool
	// Registered is whether the app registered it (RegisterFont).
	Registered bool
}

A FontFamily is a font family text can use.

type Glyph

type Glyph struct {
	Font *Font
	ID   uint32
	// Size is the font size in DIPs.
	Size float32
	// X is the glyph's drawing origin, including shaping offsets, Y its
	// baseline. Advance moves the pen independently of those offsets.
	X, Y    float32
	Advance float32
	// Cluster is the first rune of the glyph's cluster, Runes how many
	// runes the cluster holds; glyphs of the ellipsis have Runes 0.
	Cluster, Runes int
	RTL            bool
	// Object marks the box of an inline object (Span.ObjectWidth), which
	// draws no glyph: what shows there is the caller's.
	Object bool
}

Glyph is a positioned glyph.

type GlyphImage

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
}

GlyphImage is a rasterized glyph in an atlas.

type Layout

type Layout struct {
	Params Params
	Runes  []rune
	Lines  []Line
	// Width is the width of the longest line, Height the sum of the line
	// heights.
	Width, Height float32

	// Truncated reports that MaxLines cut the text.
	Truncated bool
	// contains filtered or unexported fields
}

Layout is shaped and wrapped text. Positions are in DIPs relative to the top-left corner of the text.

func (*Layout) AppendSelection

func (l *Layout) AppendSelection(dst []Rect, start, end int, on bool) []Rect

AppendSelection appends the rectangles of SelectionVisual to dst, for callers that keep them frame after frame.

func (*Layout) Caret

func (l *Layout) Caret(index int) (x, y, h float32)

Caret returns the position of the caret before rune index: its x, the top of its line and the line's height.

func (*Layout) CaretAt

func (l *Layout) CaretAt(p CaretPosition) (x, y, h float32)

CaretAt preserves affinity at bidi boundaries and soft line breaks.

func (*Layout) IndexAt

func (l *Layout) IndexAt(x, y float32) int

IndexAt returns the rune index of the caret position closest to (x, y).

func (*Layout) LineAt

func (l *Layout) LineAt(index int) int

LineAt returns the index of the line holding rune index, the start of the next line at a soft line break.

func (*Layout) MoveCaret

func (l *Layout) MoveCaret(p CaretPosition, direction int) CaretPosition

MoveCaret advances one visual grapheme, preserving the edge arrived at.

func (*Layout) PositionAt

func (l *Layout) PositionAt(x, y float32) CaretPosition

PositionAt hit-tests whole graphemes, retaining the visual edge chosen.

func (*Layout) Selection

func (l *Layout) Selection(start, end int) []Rect

Selection returns the rectangles covering the runes from start to end.

func (*Layout) SelectionOn

func (l *Layout) SelectionOn(start, end int, on bool) []Rect

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 (*Layout) SelectionRanges

func (l *Layout) SelectionRanges(a, b CaretPosition) []Range

SelectionRanges returns logical ranges covered by a visual gesture. A gesture through mixed-direction text can cover discontiguous ranges.

func (*Layout) SelectionVisual

func (l *Layout) SelectionVisual(start, end int, on bool) []Rect

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.

type Line

type Line struct {
	// X, Y, Width and Height are the line's box; X includes the alignment.
	X, Y, Width, Height float32
	// Baseline is the y of the baseline; Ascent and Descent the extent of
	// the fonts above and below it.
	Baseline, Ascent, Descent float32
	// Start and End are the line's runes; a newline ending it is not
	// included.
	Start, End int
	// RTL reports a right-to-left paragraph.
	RTL    bool
	Glyphs []Glyph
	// contains filtered or unexported fields
}

Line is a line of a Layout.

type Params

type Params struct {
	Text  string
	Style Style
	// Width wraps lines to this many DIPs; 0 or less only breaks lines at
	// newlines.
	Width float32
	// MaxLines truncates the text to that many lines, ending it with
	// Ellipsis ("…" when empty); 0 is unlimited.
	MaxLines int
	Ellipsis string
	// NoWrap breaks lines only at newlines, aligning them within Width
	// all the same.
	NoWrap bool
	Align  Align
	// RTL makes paragraphs without a strongly directional character, as
	// numbers or an empty line, right to left, as in an interface laid out
	// right to left; the others read in the direction of their first
	// strongly directional character, as Unicode's bidirectional
	// algorithm finds it by default (rules P2 and P3), whichever this is.
	RTL bool
	// KeepSpaces keeps the advance of whitespace at the end of wrapped
	// lines, as text editors do.
	KeepSpaces bool
	// NoBreakWords only breaks lines between words, letting a long word
	// overflow the width instead of breaking it.
	NoBreakWords bool
	// Spans styles runs of the text apart from Style, as EncodeSpans
	// writes them.
	Spans string
}

Params describe a text to lay out.

type Range

type Range struct{ Start, End int }

type Rect

type Rect struct{ X, Y, W, H float32 }

Rect is a rectangle in DIPs relative to the layout.

type Shade

type Shade uint8

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.

const Flat Shade = Shades + 1

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 Thick Shade = Shades

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.

func ShadeOf

func ShadeOf(r, g, b uint8) Shade

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.

type Span

type Span struct {
	End           int
	Family        string
	Size          float32
	Weight        int
	Italic        bool
	LetterSpacing float32
	Features      string
	// Lang is the language of the runes, as Style.Lang; "" keeps the
	// text's.
	Lang string
	// ObjectWidth and ObjectHeight, when ObjectWidth is set, make each
	// rune of the span, an object replacement character (U+FFFC), an
	// inline object: a box that wide, standing that high on the baseline,
	// which lines break around and which draws no glyph, as an image in a
	// rich text's line (Glyph.Object).
	ObjectWidth, ObjectHeight float32
}

Span styles the runes of a text before End, after those of the spans before it. What it sets replaces the Style of the layout; Italic only turns italics on.

func DecodeSpans

func DecodeSpans(s string) []Span

DecodeSpans reads what EncodeSpans wrote.

type Stroke

type Stroke struct{ X0, X1, Top, Bottom float32 }

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 Style

type Style struct {
	// Family is a comma-separated list of font families, where "system-ui"
	// and "monospace" are the system's own; "" is the system UI font.
	Family string
	// Size in DIPs; 0 is 14.
	Size float32
	// Weight from 100 (thin) to 900 (black); 0 is 400.
	Weight int
	Italic bool
	// LineHeight is the height of a line as a multiple of Size; 0 takes
	// the font's own line spacing.
	LineHeight float32
	// LetterSpacing adds DIPs after every character; negative tightens.
	LetterSpacing float32
	// Features are OpenType features, comma separated: a tag turns one
	// on, and tag=value sets it, as "tnum, liga=0, salt=2".
	Features string
	// Lang is the language of the text, a BCP 47 tag as "ja" or
	// "zh-Hant": the system's text stack picks the glyphs of that
	// language, as the Han characters Chinese and Japanese write apart,
	// and falls back to fonts for it. "" is the language of the System
	// (SetLanguage).
	Lang string
}

Style selects the font of a text.

func (Style) FontSize

func (s Style) FontSize() float32

FontSize returns the size in DIPs.

type System

type System struct {

	// MaskAtlas holds coverage masks, ColorAtlas color glyphs.
	MaskAtlas, ColorAtlas *scene.Atlas
	// contains filtered or unexported fields
}

System lays out text and rasterizes glyphs with the system's own text engine. Use Shared.

func Shared

func Shared() *System

Shared returns the process-wide text system.

func (*System) Baseline

func (s *System) Baseline(y float32) float32

Baseline returns where the system's text stack draws a baseline that is y device pixels from the top: on a whole pixel.

func (*System) BeginFrame

func (s *System) BeginFrame()

BeginFrame starts painting a frame: the masks drawn for the previous frame alone are forgotten.

func (*System) Decorate

func (s *System) Decorate(l *Layout, li, i, j int, x, y, scale float32, d Decoration, thick float32) []Stroke

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, or, if thick is positive, thick DIPs around their middle, rounded to whole pixels (at least one) and on whole pixels, so that they are as sharp as browsers draw text-decoration-thickness.

func (*System) EndFrame

func (s *System) EndFrame()

EndFrame forgets layouts no frame used for a while. The ui package calls it after each frame.

func (*System) FontFamilies

func (s *System) FontFamilies() []FontFamily

FontFamilies lists the families text can use: the app's registered ones first, under the names it gave them, or their own when it gave none, then the system's, each once and sorted without regard to case. The system's are listed once, outside the lock, and kept until RegisterFont.

func (*System) Full

func (s *System) Full() bool

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 (*System) Generation

func (s *System) Generation() uint64

Generation returns a number that changes whenever the system forgets its layouts, as it lets go of its fonts (EndFrame) or takes other ones: the layouts it returned before are then to be made anew, and those of fonts it let go of must not be drawn.

func (*System) Glyph

func (s *System) Glyph(f *Font, id uint32, scale, x float32, shade Shade, opaque bool) GlyphImage

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 (*System) GlyphRun

func (s *System) GlyphRun(f *Font, ids []uint32, xs []float32, scale float32, shade Shade, opaque bool) GlyphImage

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 (*System) JoinsGlyphs

func (s *System) JoinsGlyphs() bool

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 (*System) Language

func (s *System) Language() string

Language returns the language SetLanguage set.

func (*System) Layout

func (s *System) Layout(p Params) *Layout

Layout shapes and wraps p.Text. The result is shared and must not be modified.

func (*System) LayoutsMade

func (s *System) LayoutsMade() uint64

LayoutsMade returns how many layouts the system has made, those Layout found in its cache left out.

func (*System) MakeRoom

func (s *System) MakeRoom()

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 (*System) Mask

func (s *System) Mask(key uint64, draw func() (w, h int, pix []byte)) GlyphImage

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.

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, and is cached once a later frame draws it too.

func (*System) Metrics

func (s *System) Metrics(style Style) (ascent, descent, lineHeight float32)

Metrics returns the ascent, descent and default line height of a style.

func (*System) Preload

func (s *System) Preload()

Preload starts the text engine and finds the system UI font, which the first layout otherwise waits for.

func (*System) RegisterFont

func (s *System) RegisterFont(data []byte, family string) error

RegisterFont adds a TrueType or OpenType font (or collection) to the fonts text can use, under family, or the font's own family name when family is empty.

func (*System) SetFontRendering

func (s *System) SetFontRendering(antialias, hinting, subpixels string)

SetFontRendering sets how text is rasterized where the system's text stack does not know the desktop's settings, as Pango on Linux: antialiasing ("none", "gray" or "subpixel"), hinting ("none", "slight", "medium" or "full") and the order of the screen's subpixels ("rgb", "bgr", "vrgb" or "vbgr"), "" for the default. Other engines ignore it.

func (*System) SetLanguage

func (s *System) SetLanguage(tag string)

SetLanguage sets the language of the texts whose Style names none, a BCP 47 tag, or "" for none: the system's text stack then picks glyphs and fallback fonts as it does by default, by the user's settings. The ui package sets the language the app shows. The layouts made before are made anew (Generation).

func (*System) SetUIFamily

func (s *System) SetUIFamily(family string)

SetUIFamily sets the family "system-ui" stands for where the system's text stack does not know the desktop's interface font, as Pango on Linux, which finds fontconfig's default sans-serif. Other engines ignore it.

func (*System) Shape

func (s *System) Shape(p Params) *Layout

Shape lays out p.Text as Layout does, but caches nothing, for text that its caller keeps or rarely draws twice. The result belongs to the caller.

func (*System) Shares

func (s *System) Shares(a GlyphImage, ax, ay float32, b GlyphImage, bx, by float32) bool

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 (*System) TextParams

func (s *System) TextParams() scene.TextParams

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.

Jump to

Keyboard shortcuts

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