painter

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: BSD-3-Clause Imports: 36 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

Index

Constants

View Source
const BlurPasses = 2

BlurPasses is how many times PlanBlur's blur runs along each axis.

View Source
const (
	// DefaultTabWidth is the default width in spaces
	DefaultTabWidth = 4
)

Variables

This section is empty.

Functions

func BlurSigma added in v1.2.0

func BlurSigma(radius float32) float32

BlurSigma is the Gaussian sigma a BlurRadius of canvas.BoxShadow or canvas.BackdropBlur asks for, in the radius's units: half the radius, as in CSS (#442).

func ClearFontCache

func ClearFontCache()

ClearFontCache is used to remove cached fonts in the case that we wish to re-load Font faces

func ConcatenateSubpaths

func ConcatenateSubpaths(subpaths [][]geo.Position) []geo.Position

ConcatenateSubpaths joins multiple subpaths (from FlattenPath) into a single continuous polyline for text placement. Subpaths are concatenated in order; if the end of one subpath differs from the start of the next, a connecting segment is implicitly created.

func DrawArc

func DrawArc(arc *canvas.Arc, vectorPad float32, scale func(float32) float32) *image.RGBA

DrawArc rasterizes the given arc object into an image. The scale function is used to understand how many pixels are required per unit of size. The arc is drawn from StartAngle to EndAngle (in degrees). 0°/360 is top, 90° is right, 180° is bottom, 270° is left 0°/-360 is top, -90° is left, -180° is bottom, -270° is right

func DrawCircle

func DrawCircle(circle *canvas.Circle, vectorPad float32, scale func(float32) float32) *image.RGBA

DrawCircle rasterizes the given circle object into an image. The bounds of the output image will be increased by vectorPad to allow for stroke overflow at the edges. The scale function is used to understand how many pixels are required per unit of size.

func DrawLine

func DrawLine(line *canvas.Line, vectorPad float32, scale func(float32) float32) *image.RGBA

DrawLine rasterizes the given line object into an image. The bounds of the output image will be increased by vectorPad to allow for stroke overflow at the edges. The scale function is used to understand how many pixels are required per unit of size.

func DrawPath

func DrawPath(path *canvas.Path, vectorPad float32, scale func(float32) float32) *image.RGBA

DrawPath rasterizes the given path object into an image using rasterx. Path coordinates map directly into the object's local space. The scale function is used to understand how many pixels are required per unit of size.

func DrawPolygon

func DrawPolygon(polygon *canvas.Polygon, vectorPad float32, scale func(float32) float32) *image.RGBA

DrawPolygon rasterizes the given regular polygon object into an image. The bounds of the output image will be increased by vectorPad to allow for stroke overflow at the edges. The scale function is used to understand how many pixels are required per unit of size.

func DrawRectangle

func DrawRectangle(rect *canvas.Rectangle, rWidth, rHeight, vectorPad float32, scale func(float32) float32) *image.RGBA

DrawRectangle rasterizes the given rectangle object with stroke border into an image. The bounds of the output image will be increased by vectorPad to allow for stroke overflow at the edges. The scale function is used to understand how many pixels are required per unit of size.

func DrawString

func DrawString(dst draw.Image, s string, clr color.Color, f shaping.Fontmap, fontSize, scale float32, style bellui.TextStyle)

DrawString draws a string into an image.

func DrawStyledRuns

func DrawStyledRuns(dst draw.Image, runs []canvas.TextRun, defaultColor color.Color,
	defaultSize float32, scale float32,
)

DrawStyledRuns draws multiple styled text runs into a single image. Each run is rendered at successive x positions with its own color, size, style, and font. The runs share a common baseline derived from the tallest run's ascent.

func DrawTextOnPath

func DrawTextOnPath(top *canvas.TextOnPath, scale float32) *image.NRGBA

DrawTextOnPath renders text along a path into an NRGBA image. Each glyph is positioned at the correct distance along the path and rotated to follow the path tangent. Returns nil if there is nothing to draw.

func ExpandFillFringe

func ExpandFillFringe(subpaths [][]geo.Position, fringeWidth float32) []float32

ExpandFillFringe generates a 1-pixel-wide alpha-fading strip along subpath boundaries. Each vertex is (x, y, alpha) — inner edge vertices have alpha=1, outer edge vertices have alpha=0. This provides anti-aliased fill edges.

func ExpandStroke

func ExpandStroke(subpaths [][]geo.Position, width float32, cap canvas.LineCap, join canvas.LineJoin, miterLimit float32, dashPattern []float32, dashOffset float32) []float32

ExpandStroke converts flattened subpaths into filled triangle geometry representing the stroke. Returns a flat slice of (x, y) float32 pairs.

func ExpandStrokeAA

func ExpandStrokeAA(subpaths [][]geo.Position, width float32, cap canvas.LineCap, join canvas.LineJoin,
	miterLimit float32, dashPattern []float32, dashOffset float32, fringeWidth float32,
) []float32

ExpandStrokeAA generates stroke geometry with alpha fringe on both edges. Core stroke vertices have alpha=1, outer fringe vertices have alpha=0. Returns (x, y, alpha) triples.

func FanTriangulate

func FanTriangulate(subpaths [][]geo.Position) []float32

FanTriangulate generates triangle fan geometry from each subpath's first vertex to every edge. The resulting triangles overlap, so they are intended for stencil-buffer fill (not direct color rendering). The stencil resolves the correct interior via winding or even-odd rules. Returns a flat slice of (x, y) float32 pairs, every 6 floats forming one triangle.

func FlattenPath

func FlattenPath(elements []canvas.PathElement, scale float32) [][]geo.Position

FlattenPath converts a Path's elements into flattened subpaths (polylines). Curves are subdivided into line segments until the deviation from the true curve is less than tolerance.

func FontCacheGeneration added in v1.2.0

func FontCacheGeneration() uint64

FontCacheGeneration returns a counter bumped by each ClearFontCache. Between two equal readings, CachedFontFace returns the same fonts for the same text style, font source and theme scope, so a cache of work derived from those fonts can key on the generation instead of looking the fonts up (#483).

func FontParses added in v1.2.0

func FontParses() uint64

FontParses reports how many font files have been parsed.

func GetCornerRadius

func GetCornerRadius(perCornerRadius, baseCornerRadius float32) float32

GetCornerRadius returns the effective corner radius for a rectangle or square corner. If the specific corner radius (perCornerRadius) is zero, it falls back to the baseCornerRadius. Otherwise, it uses the specific corner radius provided.

This allows for per-corner customization while maintaining a default overall radius.

func GetMaximumCornerRadius

func GetMaximumCornerRadius(radius, adjacentWidthRadius, adjacentHeightRadius float32, size geo.Size) float32

GetMaximumCornerRadius returns the maximum possible corner radius for an individual corner, considering the specified corner radius, the radii of adjacent corners, and the maximum radii allowed for the width and height of the shape. Corner radius may utilize unused capacity from adjacent corners with radius smaller than maximum value so this corner can grow up to double the maximum radius of the smaller dimension (width or height) without causing overlaps.

This is typically used for drawing circular corners in rectangles or squares with different corner radii.

func GetMaximumRadius

func GetMaximumRadius(size geo.Size) float32

GetMaximumRadius returns the maximum possible corner radius that fits within the given size. It calculates half of the smaller dimension (width or height) of the provided geo.Size.

This is typically used for drawing circular corners in rectangles, circles or squares with the same radius for all corners.

func GetMaximumRadiusArc

func GetMaximumRadiusArc(outerRadius, innerRadius, sweepAngle float32) float32

GetMaximumRadiusArc returns the maximum possible corner radius for an arc segment based on the outer radius, inner radius, and sweep angle in degrees. It calculates half of the smaller dimension (thickness or effective length) of the provided arc parameters

func HalveTexels added in v1.2.0

func HalveTexels(n int) int

HalveTexels is a texture side after one halving: never less than a texel.

func MayContainRTL

func MayContainRTL(runes []rune) bool

MayContainRTL reports whether the runes include any character from a right-to-left script (Hebrew, Arabic, Syriac, Thaana, NKo, Samaritan, Mandaic, their presentation forms, and assorted historic/maths RTL blocks). It is a cheap pre-filter: callers use it to skip the bidi visual-layout path for pure-LTR text. False positives (e.g. a stray RTL punctuation mark) merely trigger the full layout, which then reports HasRTL accurately.

func MeasureString

func MeasureString(f shaping.Fontmap, s string, textSize float32, style bellui.TextStyle) (size geo.Size, advance float32)

MeasureString returns how far dot would advance by drawing s with f. Tabs are translated into a dot location change.

func MeasureStyledRuns

func MeasureStyledRuns(runs []canvas.TextRun, defaultSize float32) (size geo.Size, advances []float32)

MeasureStyledRuns measures the combined size of multiple styled text runs. It returns the total size (sum of widths, max height) and per-run advances.

func NormalizeArcAngles

func NormalizeArcAngles(startAngle, endAngle float32) (float32, float32)

NormalizeArcAngles adjusts the given start and end angles for arc drawing. It converts the angles from the Unit circle coordinate system (where 0 degrees is along the positive X-axis) to the coordinate system used by the painter, where 0 degrees is at the top (12 o'clock position). The function also reverses the direction: positive is clockwise, negative is counter-clockwise

func PaintImage

func PaintImage(img *canvas.Image, c core.Canvas, width, height int) image.Image

PaintImage renders a given bellui Image to a Go standard image If a core.Canvas is given and the image’s fill mode is “fill original” the image’s min size has to fit its original size. If it doesn’t, PaintImage does not paint the image but adjusts its min size. The image will then be painted on the next frame because of the min size change.

func PathRasterBounds

func PathRasterBounds(path *canvas.Path) (origin geo.Position, size geo.Size)

PathRasterBounds returns the path-local axis-aligned box a path must be rasterized into: its minimum corner (origin) and its size. The object's laid-out Size is expanded in every direction to also cover the path's own control-point bounding box, so a path whose segments fall outside its Size — e.g. a widget renderer drawing in canvas space with a zero-sized object, or segments reaching above/left of the object origin — still rasterizes in full. This matches the GL and WebGPU painters, which draw paths in full path-local space rather than clipping to Size. The origin is (0,0) unless the path reaches into negative coordinates.

func PlanBlur added in v1.2.0

func PlanBlur(sigma float32) (halvings int, step float32)

PlanBlur is how a painter blurs a texture by sigma texels with the 9-tap kernel: it halves the texture halvings times, then blurs it along each axis BlurPasses times, with taps step texels apart at that size. Taps much more than a texel apart would sample a hard edge as separate copies of it, which show as bands; the halved texture also costs less to blur, and the blur hides the detail halving loses.

Halving, and drawing the halved texture stretched, blur too: measured on WebGPU, by halvingVariance·4^halvings texels² on average (#442), and the kernel's own step leaves that out. How much depends on where the edges fall on the halved texels, between none and about twice that, so a blur halved several times can be off by up to about a tenth of sigma. Passes that each blur by sigma/√2 reach further before the texture has to be halved: with one pass per axis, DialogLevel's shadow came out 11% wide.

func RenderedTextSize

func RenderedTextSize(text string, fontSize float32, style bellui.TextStyle, source bellui.Resource) (size geo.Size, baseline float32)

RenderedTextSize looks up how big a string would be if drawn on screen. It also returns the distance from top to the text baseline.

func ShapeString added in v1.2.0

func ShapeString(f shaping.Fontmap, s string, fontSize, scale float32, style bellui.TextStyle, cb func(run shaping.Output, x float32)) (baseline int)

ShapeString shapes s on one line as DrawString draws it, calling cb with each shaped run and its pen x in pixels. It returns the baseline's y in pixels from the top of the text, as DrawString places it. The batched WebGPU painter places atlas glyphs with it (#475).

func SweepFontCache

func SweepFontCache(expiry time.Duration)

SweepFontCache removes font cache entries that have not been accessed for the given duration. This is called periodically from the cache clean cycle to bound memory usage.

func TextOnPathBounds

func TextOnPathBounds(top *canvas.TextOnPath) geo.Size

TextOnPathBounds returns the bounding box size of text on path rendering. This is used by MinSize calculations.

func TriangulateFill

func TriangulateFill(subpaths [][]geo.Position) []float32

TriangulateFill converts closed subpaths into triangles using ear-clipping. Returns a flat slice of (x, y) float32 pairs, every 6 floats forming one triangle.

func VectorPad

func VectorPad(obj core.CanvasObject) float32

VectorPad returns the number of additional points that should be added around a texture. This is to accommodate overflow caused by stroke and line endings etc. THe result is in geo.Size type coordinates and should be scaled for output.

Types

type CaretAffinity

type CaretAffinity bool

CaretAffinity disambiguates the two visual positions a single logical caret offset can have at an LTR↔RTL direction boundary, where one offset maps to two valid x positions. Away from a boundary both resolve to the same x.

const (
	// AffinityDownstream attaches the caret to the character that logically
	// follows it (its leading edge). This is the zero value and matches CaretX.
	AffinityDownstream CaretAffinity = false
	// AffinityUpstream attaches the caret to the character that logically
	// precedes it (the trailing edge of offset-1) — e.g. so the caret sticks to a
	// just-typed character rather than jumping across a direction boundary.
	AffinityUpstream CaretAffinity = true
)

type FontCacheItem

type FontCacheItem struct {
	Fonts shaping.Fontmap
	// contains filtered or unexported fields
}

FontCacheItem holds a cached font face set with a last-access timestamp for expiry-based eviction.

func CachedFontFace

func CachedFontFace(style bellui.TextStyle, source bellui.Resource, o core.CanvasObject) *FontCacheItem

CachedFontFace returns a Font face held in memory. These are loaded from the current theme.

type FontFamilyInfo

type FontFamilyInfo struct {
	Name           string   // Display name (e.g. "Arial", "Roboto")
	File           string   // Filesystem path to the regular font file
	BoldFile       string   // Filesystem path to the bold variant (may be empty)
	ItalicFile     string   // Filesystem path to the italic variant (may be empty)
	BoldItalicFile string   // Filesystem path to the bold-italic variant (may be empty)
	Styles         []string // Available style names (e.g. "Regular", "Bold", "Italic")
}

FontFamilyInfo describes a discovered font family.

func SystemFontFamilies

func SystemFontFamilies() []FontFamilyInfo

SystemFontFamilies returns all font families available on the system, sorted alphabetically. Results are cached after the first call. Safe for concurrent use.

type LineLayout

type LineLayout struct {
	// Carets has len(text)+1 entries. Carets[i] is the visual x of the leading
	// edge of logical rune i; Carets[len] is the trailing edge of the line. For
	// RTL or mixed-direction text the sequence is not monotonic. Boundary carets
	// carry forward affinity, so they are insertion points, not glyph edges —
	// use extents for glyph geometry (e.g. selection rectangles).
	Carets []float32

	// Width is the total visual advance of the line.
	Width float32
	// contains filtered or unexported fields
}

LineLayout is the visual layout of one logical line of a single text style. It maps logical rune offsets to visual x positions, accounting for the bidi reordering of mixed LTR/RTL runs within the line. It is the shared primitive behind widget-level bidi: caret placement, click hit-testing, selection rectangles and visual arrow navigation.

Positions are in unscaled (device-independent) coordinates, matching MeasureString, so callers that already work in DP can use them directly.

func LineVisualLayout

func LineVisualLayout(faces shaping.Fontmap, runes []rune, textSize float32, style bellui.TextStyle) LineLayout

LineVisualLayout shapes a single logical line of one text style and returns its visual layout: a logical-rune → visual-x caret table plus the total width. It reuses the same Segmenter/HarfBuzz pipeline as walkString, so the caret positions agree with how the line is measured and drawn.

The line must not contain newlines (callers split on '\n' first). Tab expansion is not applied here; callers should gate caret usage on HasRTL and keep the legacy logical-prefix path for pure-LTR text, which handles tabs.

func StyledLineVisualLayout

func StyledLineVisualLayout(runs []StyledRun) LineLayout

StyledLineVisualLayout is the multi-style analogue of LineVisualLayout. It lays out one logical line whose runes are partitioned into style runs, resolving the bidi visual order across the entire line while shaping each run with its own font and size. Runs flagged Box are opaque inline boxes (non-text segments): they take a slot in the bidi order and consume width but contribute no caret columns. The returned LineLayout's Carets/extents are indexed by global logical rune offset over the concatenation of all the non-box runs' Runes.

Adjacent text runs that share a face (size, style, font) and both may contain RTL text are merged before shaping (joinAdjacentStyledRuns), so cursive joining is preserved across an Arabic word split into two same-font segments (pre-rebrand issue #26). Runs differing in face, boxes, and pure-LTR neighbours are still shaped separately. The line must not contain newlines, and tabs are not expanded — callers gate on HasRTL and keep the legacy path for pure-LTR text, exactly as for LineVisualLayout.

func (LineLayout) BoxCaretX

func (l LineLayout) BoxCaretX(box int, after bool) float32

BoxCaretX returns the visual caret x for the insertion point logically before (after=false) or after (after=true) the line's box-th opaque box, in logical (run-supply) order. The "before" side is the edge facing the logically-preceding content — the right edge when the bidi flow around the box runs right-to-left (pre-rebrand tracker #913). Out-of-range indices clamp to the line edges.

func (LineLayout) BoxCount

func (l LineLayout) BoxCount() int

BoxCount returns the number of opaque inline boxes in the line.

func (LineLayout) CaretX

func (l LineLayout) CaretX(logical int) float32

CaretX returns the visual x of the leading edge of logical rune offset, using forward affinity at direction boundaries. Out-of-range offsets are clamped.

func (LineLayout) CaretXAt

func (l LineLayout) CaretXAt(logical int, aff CaretAffinity) float32

CaretXAt returns the visual x of logical offset under the given affinity. With AffinityDownstream it is identical to CaretX (forward affinity). With AffinityUpstream it returns the trailing edge of the preceding rune, which differs from the downstream x only when offset sits exactly at a direction boundary. Out-of-range offsets are clamped.

func (LineLayout) HasRTL

func (l LineLayout) HasRTL() bool

HasRTL reports whether the line contains any right-to-left run. When false, logical order equals visual order and Carets is monotonically increasing.

func (LineLayout) HitTest

func (l LineLayout) HitTest(x float32) int

HitTest maps a visual x to the nearest logical rune offset, i.e. the insertion point a click at x should select. Because Carets is non-monotonic for mixed text, this picks the logical offset whose visual caret is closest to x.

func (LineLayout) HitTestAffinity

func (l LineLayout) HitTestAffinity(x float32) (int, CaretAffinity)

HitTestAffinity is HitTest extended with affinity: at a direction boundary the same logical offset has a downstream and an upstream visual position, and a click should resolve to whichever side it landed on. It returns the logical offset and the affinity of the nearest caret position, considering both the downstream (Carets) and upstream (caretsBwd) candidate of every offset.

func (LineLayout) HitTestBoxes

func (l LineLayout) HitTestBoxes(x float32) (off int, aff CaretAffinity, box int, after bool, isBox bool)

HitTestBoxes maps a visual x to the nearest insertion point, considering both text carets and the edges of opaque inline boxes (pre-rebrand tracker #983) — the box-aware inverse of BoxCaretX, extending HitTestAffinity so a click on or beside an inline atom resolves to the atom's own boundary rather than snapping to the nearest text caret (which HitTestAffinity does, being box-blind).

When the result is a box edge, isBox is true with the box's logical (run-supply) index and which side (after) the insertion point sits — a click inside a box resolves to the nearer edge, before/after following the bidi flow around the box (before = the edge facing logically-preceding content). Otherwise isBox is false and off/aff are HitTestAffinity's text hit.

func (LineLayout) SelectionSpans

func (l LineLayout) SelectionSpans(start, end int) [][2]float32

SelectionSpans returns the disjoint visual x-intervals [x1,x2] that cover the logical column range [start,end). In LTR text this is a single interval; in RTL/mixed text a logically-contiguous selection can map to several disjoint visual rectangles, which this merges and returns left-to-right.

Opaque boxes ride their owning rune: a box is filled when the text rune it logically trails lies in the selection, exactly as the legacy left-to-right single-rectangle path folds a non-text segment's width into the run before it. Callers whose selection model gives an atom its own selectable position should use SelectionSpansBoxes instead.

func (LineLayout) SelectionSpansBoxes

func (l LineLayout) SelectionSpansBoxes(start, end int, boxSelected func(int) bool) [][2]float32

SelectionSpansBoxes is SelectionSpans with the box-inclusion decision supplied by the caller: boxSelected is asked once per opaque box, indexed in logical (run-supply) order. It serves selection models where an inline atom occupies its own selectable position (e.g. RichEntry's document space, pre-rebrand tracker #913) rather than riding its preceding rune — including an atom-only selection with an empty text range.

func (LineLayout) VisualNeighbor

func (l LineLayout) VisualNeighbor(logical, dir int) int

VisualNeighbor returns the logical offset of the caret position immediately to the visual right (dir > 0) or left (dir < 0) of the given logical offset, for visual arrow-key navigation. It returns -1 when there is no caret in that direction (the cursor is at the visual edge of the line and the caller should cross to an adjacent row).

type PathSampler

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

PathSampler provides arc-length parameterized access to a flattened polyline. Given a distance along the path, it returns the interpolated position and tangent angle at that point.

func NewPathSampler

func NewPathSampler(points []geo.Position) *PathSampler

NewPathSampler creates a PathSampler from a polyline (flattened path points). The points slice must contain at least 2 points.

func (*PathSampler) Sample

func (ps *PathSampler) Sample(dist float32) (x, y, angle float32)

Sample returns the position (x, y) and tangent angle (radians, measured from the +X axis) at distance dist along the path. Distances before the start clamp to the first point; distances beyond the end clamp to the last point. The tangent at clamped endpoints uses the first or last segment direction respectively.

func (*PathSampler) TotalLength

func (ps *PathSampler) TotalLength() float32

TotalLength returns the total arc length of the path.

type StyledRun

type StyledRun struct {
	Runes      []rune
	TextSize   float32
	Style      bellui.TextStyle
	FontSource bellui.Resource

	// Box marks this run as an opaque inline box (a non-text RichText segment such
	// as a HyperlinkSegment or image) of width BoxWidth. It occupies one slot in
	// the line's bidi visual order but contributes no caret columns; its Runes are
	// ignored. This lets a bidi row interleave non-text segments with RTL text
	// while keeping the text-only column model (pre-rebrand issue #41).
	Box      bool
	BoxWidth float32
}

StyledRun is one contiguous logical span of runes sharing a single text style, the unit StyledLineVisualLayout lays out. Each run carries its own size, style and font, so a line assembled from several differently-styled spans (e.g. the TextSegments of one RichText row) shapes each span correctly while a single bidi resolution orders the whole line.

Directories

Path Synopsis
Package webgpu will host the WebGPU implementation of the backend-neutral gpu.Painter interface (WebGPU migration, pre-rebrand issue #198, Phase 2 / pre-rebrand tracker #201).
Package webgpu will host the WebGPU implementation of the backend-neutral gpu.Painter interface (WebGPU migration, pre-rebrand issue #198, Phase 2 / pre-rebrand tracker #201).

Jump to

Keyboard shortcuts

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