text
分层
只有 api/stable/ui_text.txt 列出的符号受兼容性承诺约束。标有「实验性」的符号,以及类型下「实验性成员」列出的字段,任何 0.x 版本都可能有不兼容变化(docs/release.md「API 稳定性」)。
import "github.com/tangoui/tango/ui/text"本页由
site/tools/apigen从源码注释生成(按 darwin 构建标签选文件),请勿手改。
Package text shapes and lays out text for the Tango self-drawn UI.
It uses go-text/typesetting (HarfBuzz port) for shaping and UAX #14 line breaking on every platform but macOS. On macOS (not iOS) CoreText does all of it instead (shaping, UAX #14 line breaking, bidi levels and glyph rasterization) and no go-text code is linked; the build tag tango_gotext restores go-text there. Both give correct per-character breaking for Chinese and the basic kinsoku rules (no break before ",。!?)" or after "(「"). Fonts are resolved per rune through a fallback chain: fonts registered by the application with RegisterFont first, then platform fonts. By default the platform text engine finds and rasterizes them (CoreText: SF Pro + PingFang SC on macOS; DirectWrite: Segoe UI + Microsoft YaHei on Windows; fontconfig + FreeType: Noto / DejaVu + Noto Sans CJK / WenQuanYi on Linux), with its hinting, and per-rune platform fallback; see engine.go and UseSystemEngine. Without the engine (never on macOS without tango_gotext), font files are parsed and rasterized in pure Go (SF + Hiragino on macOS, Segoe UI + Microsoft YaHei on Windows, Noto/DejaVu/WenQuanYi on Linux). No font files are bundled. On platforms with no discoverable fonts (js/wasm) text is measured with approximate metrics and not drawn until the app registers a font.
API tiers: only the symbols listed in api/stable/ui_text.txt are covered by the compatibility promise of docs/release.md ("API 稳定性"); every other exported symbol is Experimental and may change in any 0.x release. The API reference on the documentation site marks the experimental symbols.
常量
const ItalicSkew = 0.2ItalicSkew is the slant of synthetic italics (tan of ~11°).
实验性
函数
func DefaultLang
func DefaultLang() stringDefaultLang returns the tag set by SetDefaultLang ("zh-Hans" initially).
func Engine 实验性
func Engine() stringEngine names the text engine rendering system fonts: "coretext", "directwrite", "freetype", or "go" when the system engine is disabled or unavailable. On macOS (without tango_gotext) it always reports "coretext" (see UseSystemEngine).
func Families
func Families() []stringFamilies lists the fallback chain names in priority order (loading system fonts if needed); families that failed to load are omitted.
func LineHeightOf 实验性
func LineHeightOf(st Style) float32LineHeightOf returns the line height used for st.
func Measure
func Measure(s string, st Style, opt Options) geom.SizeMeasure returns the size of s laid out with opt.
func RegisterFont
func RegisterFont(familyName string, data []byte) errorRegisterFont adds a TTF/OTF/TTC font under family. Faces registered by the app take priority over system fonts; registering several families builds your own fallback chain (first registered wins). Variable fonts with a wght axis are instantiated at 300-700.
func SetDefaultLang
func SetDefaultLang(tag string)SetDefaultLang sets the BCP 47 language tag used for text whose Style.Lang is empty (the application language; ui.SetDefaultLocale calls it). The language picks script-specific shaping (OpenType locl, e.g. Japanese vs Simplified Chinese ideograph forms). An empty tag restores the initial "zh-Hans".
func TrimCaches 实验性
func TrimCaches()TrimCaches drops the shaped-text caches of Shape and the run shaping (they refill as text is shaped again), for a low-memory warning (docs/specs/mobile-canvas.md §3.4). LineCache instances belong to their owners and are left alone, as are loaded fonts. Any goroutine.
func TrimFontCaches 实验性
func TrimFontCaches()TrimFontCaches drops discovered system font chains and all shaped caches. The next layout rebuilds only the families it needs. Existing Layout and LineCache owners may retain their Face pointers until they are replaced.
func TrimSpaceRight 实验性
func TrimSpaceRight(s string) stringTrimSpaceRight is a helper for callers building labels.
func UseSystemEngine 实验性
func UseSystemEngine(on bool) (prev bool)UseSystemEngine enables (the default) or disables the system text engine for system fonts. Disabled, system font files are parsed and rasterized in pure Go, which renders identically on every machine with the same fonts (golden images, CPU/GPU comparison tests). The environment variable TANGO_TEXT_ENGINE=go or =system sets the initial state.
On macOS (not iOS) there is a single text engine, CoreText, which shapes, breaks and rasterizes; no pure-Go text engine is linked. There UseSystemEngine changes nothing and returns true (UseSystemEngine(false) does not turn CoreText off), Engine always reports "coretext", and TANGO_TEXT_ENGINE is ignored. Built with -tags tango_gotext, macOS keeps the go-text engine and this switch (golden images and other tests that need the pure-Go path), like every other platform.
It is a process-wide switch (all windows, renderers and goroutines) and takes effect through new glyph sources: a switch drops the layout cache and the next Shape builds the system font chain again with new *Face values (each a distinct paint.GlyphSource, so a distinct Src in the GPU atlas key). A Face never changes path: engine faces always rasterize through the engine (paint.GlyphRasterizer), pure-Go faces always through their outlines. Layouts shaped before the switch keep their old faces and draw exactly as before; reshape (or let the UI re-run its frame) to pick up the new engine. Fonts added with RegisterFont use the pure-Go path, except on macOS (without tango_gotext), where CoreText reads them like system fonts. Call it before rendering starts when possible (tests: at the top of the test or in TestMain). It returns the previous setting, for restoring.
func UseSystemFonts
func UseSystemFonts(on bool)UseSystemFonts enables or disables platform font discovery (enabled by default). Disabling is useful for deterministic tests that register their own fonts.
func Width
func Width(s string, st Style) float32Width returns the single-line advance width of s.
类型
Direction
type Direction uint8Direction is the base direction of a paragraph (UAX #9 paragraph embedding level). It lives in Options rather than Style because it is a property of the paragraph, not of a run: a future ShapeRuns(text, runs, opt) gives every run its own Style but one direction for the paragraph.
const (
// DirAuto takes the direction of the first strong character of each
// paragraph (rules P2/P3); paragraphs without one are left-to-right.
DirAuto Direction = iota
// DirLTR forces a left-to-right paragraph level.
DirLTR
// DirRTL forces a right-to-left paragraph level.
DirRTL
)Face 实验性
type Face struct {
Family string
Weight Weight
Italic bool // a designed italic or oblique face
// contains filtered or unexported fields
}Face is one loaded font face at one weight and slant. It implements paint.GlyphSource.
func (*Face) GlyphPath 实验性
func (f *Face) GlyphPath(id uint32, size float32) *paint.PathGlyphPath implements paint.GlyphSource.
func (*Face) HasRune 实验性
func (f *Face) HasRune(r rune) boolHasRune reports whether the face maps r.
func (*Face) Metrics 实验性
func (f *Face) Metrics(size float32) (ascent, descent float32)Metrics returns ascent and descent in px at size.
func (*Face) RasterGlyph 实验性
func (f *Face) RasterGlyph(id uint32, size float32, subx uint8, skew float32) (*image.Alpha, image.Point, bool)RasterGlyph implements paint.GlyphRasterizer. Pure-Go faces always return ok=false (their outlines are rasterized by paint); engine faces always rasterize through the engine, except keys the engine failed on, which keep falling back for the life of the face.
func (*Face) SystemRasterized 实验性
func (f *Face) SystemRasterized() boolSystemRasterized reports whether the face's glyphs are rasterized by the system text engine.
Layout 实验性
type Layout struct {
Text string
Runes []rune
Style Style
Width float32 // widest line
Height float32
Lines []Line
Glyphs []paint.Glyph // visual order, line by line; origin: layout top-left; Y is the baseline
// GlyphCluster[g] is the rune index (into Runes) Glyphs[g] was shaped
// from: the first rune of its cluster (ligatures and combining
// sequences map to their first rune). -1 marks the synthesized
// ellipsis. Same length as Glyphs.
GlyphCluster []int32
// GlyphRun[g] is the index (into the runs given to ShapeRuns) of the
// style run Glyphs[g] belongs to; the ellipsis takes the run of the
// last rune kept on its line. Same length as Glyphs; all 0 in layouts
// made by Shape (one implicit run).
GlyphRun []int32
Truncated bool
Ascent float32
LineHeight float32
// contains filtered or unexported fields
}Layout is shaped, wrapped text ready for painting and hit testing.
func Shape 实验性
func Shape(s string, st Style, opt Options) *LayoutShape lays out s. Results are cached; the returned Layout must not be mutated.
func ShapeInto 实验性
func ShapeInto(dst *Layout, s string, st Style, opt Options) *LayoutShapeInto updates dst for the compact fixed numeric label path and reuses its backing slices.
func ShapeRuns 实验性
func ShapeRuns(s string, runs []Run, opt Options) *LayoutShapeRuns lays out s like Shape, with a Style per rune range: each paragraph is cut at bidi level changes and where the shaping style changes, and every piece is shaped on its own with its run's font, weight, slant, size and language (the paragraph direction stays opt.Direction). Adjacent runs whose styles shape alike (equal Style fields once normalized, with the same resolved language) are shaped as one piece, so kerning and ligatures cross token boundaries that only differ in what Style does not hold (color, decoration); GlyphRun still names each glyph's own run. Shaping keeps the text around a piece as context, so Arabic letters still join across a style boundary; kerning and ligatures do not cross one.
Coverage: runs are clamped to the text; a rune covered by several runs takes the last of them, a rune covered by none takes run 0. With no runs ShapeRuns is Shape(s, Style{}, opt); with one run covering the text the result is identical to Shape(s, runs[0].Style, opt).
Line metrics: every line has the largest LineHeight among the runs that cover some rune (Layout.LineHeight, uniform so IndexAt still works by line), and one baseline shared by all runs, placed so that the union of the runs' font ascents and descents is centred in the line (for one run: Shape's rule). Layout.Ascent is the largest ascent, Layout.Style is runs[0].Style (normalized). Each glyph keeps its run's Size and Skew, and Layout.GlyphRun maps it to its run. Results are cached; the returned Layout must not be mutated.
func (*Layout) Caret 实验性
func (l *Layout) Caret(i int) (x, top, height float32)Caret returns the caret x and the line box for logical rune index i (the caret sits before rune i).
With mixed directions a logical position can sit at two visual places (the end of the previous run and the start of the next); Caret follows the character before it: x is the trailing edge of rune i-1 (its right edge if it is left-to-right, its left edge if right-to-left). At the start of a line, where there is no previous rune on the line, x is the leading edge of rune i (left edge for LTR, right edge for RTL). In pure left-to-right text this is simply the pen position before rune i.
func (*Layout) IndexAt 实验性
func (l *Layout) IndexAt(x, y float32) intIndexAt returns the logical rune index for the point (layout coords): the position whose caret (see Caret) is nearest x on the line at y, so Caret(IndexAt(x, y)) is the caret drawn closest to x and IndexAt(Caret(i)) is i or, at a direction boundary, another position drawn at the same x. When two positions share the nearest x, the rune under the point decides: the left half of a left-to-right rune k means k, its right half k+1; for a right-to-left rune the left half means k+1 and the right half k.
func (*Layout) LineOf 实验性
func (l *Layout) LineOf(i int) intLineOf returns the index of the line containing rune index i (carets at a wrap boundary belong to the next line).
func (*Layout) SelectionRects 实验性
func (l *Layout) SelectionRects(start, end int) []geom.RectSelectionRects returns the boxes covering the runes [start,end) (in any order), one or more per line: on a line mixing directions a logical range is visually discontiguous, so it yields one rect per visual stretch, left to right. Rects are in layout coordinates with the full line height. Lines contribute nothing when none of their visible runes is selected (an empty line in the middle of a selection included); callers that mark selected line breaks add that themselves.
func (*Layout) Size 实验性
func (l *Layout) Size() geom.SizeSize returns the layout box.
Line 实验性
type Line struct {
Start, End int // rune range [Start,End) of the source text shown on this line
Width float32 // advance width without trailing spaces
Top float32
Baseline float32
// RTL reports a right-to-left paragraph level. Glyphs of every line
// still start at x=0 (visible content spans [0,Width]; trailing spaces
// of an RTL line hang left of 0), so callers right-align RTL lines
// themselves when they want natural alignment.
RTL bool
// contains filtered or unexported fields
}Line is one laid-out line.
LineCache 实验性
type LineCache struct {
// contains filtered or unexported fields
}LineCache shapes single lines of a code editor (or any list of independent single-line paragraphs) and keeps the most recently used layouts. Shape(line, runs, opt) returns what
ShapeRuns(line, runs', Options{NoWrap: true, Direction: opt.Direction})
returns, where runs' are runs with opt.Lang filled into empty Style.Lang, plus LineOptions' tab stops and ligature setting: same glyphs, carets, GlyphRun and metrics. The line must not hold '\n' (it would be laid out as several lines, through the general path).
Entries are keyed by the line text, the runs (ranges and styles), and every LineOptions field, and evicted least recently used first; a change of the font registry or of DefaultLang empties the cache. The layouts bypass the shared Shape/ShapeRuns cache, so scrolling a long file does not evict other text's layouts.
Monospace fast path: when every run is Mono, ligatures are off and the line is left-to-right, the line is not run through HarfBuzz as a whole. It is cut the way the general path cuts it (style runs, script, font face) and further into grapheme clusters, and each cluster's shaping is memoized per face, size, script and language, then the clusters are placed side by side (tabs expanded, combining marks and zero-width characters taking the advance HarfBuzz gives them, wide CJK and emoji glyphs their own advance). This equals shaping the whole run only when nothing reaches across clusters, so the fast path is used only with faces that have no kerning, cursive attachment, required ligatures or AAT tables (emoji fonts excepted: their sequences are grapheme clusters), for scripts that need no contextual shaping (Latin, Greek, Cyrillic, Armenian, Georgian, CJK and symbols), and when every rune resolves to a face; anything else, including any right-to-left or bidi control character, goes through the general path. Lines of printable ASCII skip the segmentation step entirely.
A LineCache is safe for concurrent use; the returned Layout is shared and must not be mutated.
func NewLineCache 实验性
func NewLineCache(capacity int) *LineCacheNewLineCache returns a cache holding up to capacity lines (<= 0: 2048).
func (*LineCache) Len 实验性
func (c *LineCache) Len() intLen returns the number of cached lines.
func (*LineCache) Reset 实验性
func (c *LineCache) Reset()Reset empties the cache.
func (*LineCache) Shape 实验性
func (c *LineCache) Shape(line string, runs []Run, opt LineOptions) *LayoutShape lays out line with the style runs (see ShapeRuns) as one unwrapped line, from the cache when it holds the same line, runs and options.
LineOptions 实验性
type LineOptions struct {
// TabSize is the tab stop interval in columns (<= 0 means 4). A column
// is the advance of a space in the monospace face at the size of the
// first run; a tab advances the pen to the next multiple of TabSize
// columns, measured in pixels from the line start (so after wide
// characters the stop is where their actual glyph widths put it).
TabSize int
// Ligatures keeps the OpenType ligature features (liga, clig, calt)
// HarfBuzz applies by default; false turns them off. Code editors
// usually leave it false; true always takes the general path.
Ligatures bool
// Lang is the language of runs whose Style.Lang is empty (empty:
// DefaultLang).
Lang string
// Direction is the paragraph direction (Options.Direction).
Direction Direction
}LineOptions are the per-line settings of LineCache.Shape.
Options
type Options struct {
MaxWidth float32 // <=0 or +Inf: no width limit
MaxLines int // 0: unlimited
NoWrap bool // keep a single line per paragraph
Ellipsis bool // cut overflow with "…" (needs MaxWidth)
// Direction is the base direction of every paragraph ('\n'-separated
// block); the zero value DirAuto takes it from the paragraph's first
// strong character (UAX #9 P2/P3).
Direction Direction
// contains filtered or unexported fields
}Options control wrapping and truncation.
Run 实验性
type Run struct {
Start, End int // rune range
Style Style
}Run is a style run of ShapeRuns: runes [Start,End) of the text use Style.
Style
type Style struct {
Size float32 // px; 0 means 14
Weight Weight // 0 means Regular
LineHeight float32 // px; 0 means round(Size*22/14)
Mono bool // prefer the monospace chain
// Italic selects each family's italic (or oblique) face; families
// without one draw their upright face slanted by ItalicSkew (advances
// unchanged). Widths always come from the face actually used.
Italic bool
// Lang is the BCP 47 language tag of the text ("ja", "zh-Hant", "ar");
// empty means the application language (DefaultLang). It selects
// language-specific shaping (OpenType locl): the same ideograph takes
// its Japanese or Chinese form. Runs of another script get that
// script's language (e.g. Arabic runs inside "en" text).
Lang string
// FontFamily is a comma-separated list of preferred registered or
// installed families, in order. Names are case-insensitive. The
// generics monospace, sans-serif and system-ui use platform families.
// Missing fonts or glyphs fall through to the usual fallback chain.
// Mono selects the monospace chain after these preferences.
FontFamily string
}Style selects font and size.
Weight
type Weight intWeight is a CSS font weight.
const (
Light Weight = 300
Regular Weight = 400
Medium Weight = 500
Semibold Weight = 600
Bold Weight = 700
)