render

package
v0.3.9 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 45 Imported by: 2 modules, 28 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

The CSS box primitives: per-corner rounded fills, rounded border rings with per-side widths and colors, angled multi-stop linear gradients, and box shadows with offset, spread, blur, and inset — everything a CSS box paints behind its content. Every primitive is a per-pixel signed-distance coverage pass at the device scale and blends through the single blend site, so PushAlpha and PushBrightness apply by construction.

Package render holds pure drawing and damage primitives. Nothing in here touches Wayland; everything is unit-testable.

The shadow raster cache. Canvas.Shadow paints a blurred rounded-rect silhouette; the expensive half of that is the coverage field - the Gaussian kernel and the per-pixel signed-distance sweep - and it depends only on (rect size, corner radius, blur, device scale), never on the color or what is underneath. This file builds each field once and hands the cached raster back, so a hover twitch that repaints the same floating surface every frame re-blends the ring but never re-Gaussians it. The counters double as the paint-count proof: a second identical Shadow must be a hit, not a rebuild.

Index

Constants

View Source
const Ellipsis = "…"

Ellipsis is the mark a truncated text carries where it was cut.

View Source
const MaxFilters = 8

MaxFilters bounds a filter list; later functions past it are dropped with a parse warning.

View Source
const MaxPooledLayers = 6

MaxPooledLayers bounds the scratch layers kept for reuse: a few nesting depths of effects, on a window and its popups.

Variables

View Source
var Identity = Affine{A: 1, D: 1}

Identity is the affine map that moves nothing.

View Source
var Identity3 = M3{1, 0, 0, 0, 1, 0, 0, 0, 1}

Identity3 is the projective map that moves nothing.

View Source
var Identity4 = Mat4{
	1, 0, 0, 0,
	0, 1, 0, 0,
	0, 0, 1, 0,
	0, 0, 0, 1,
}

Identity4 moves nothing.

View Source
var ImageCentered = ImagePos{X: 0.5, Y: 0.5}

ImageCentered is the default placement, 50% 50%.

View Source
var Inv255 = Reciprocal(float32(255))

Inv255 is 1/255 in float32, what re-premultiplying scales by.

View Source
var SoftLightTable = func() (t [256]int32) {
	for b := range t {
		x := float64(b) / 255
		d := math.Sqrt(x)
		if x <= 0.25 {
			d = (float64((float64(16*x)-12)*x) + 4) * x
		}
		t[b] = int32(math.Round(d * blendK))
	}
	return t
}()

SoftLightTable is soft-light's D(Cb) for every 8-bit backdrop channel, in blendK units: the one curve the integer blend cannot compute exactly, tabled once for both renderers.

Functions

func AlignedPen

func AlignedPen(sh *ShapedText, box Rect, h Alignment, d text.Direction) (x, baseline int)

AlignedPen is where an aligned draw puts sh's pen inside box: the alignment mirrored for a right-to-left line, the line centered vertically on its baseline. Decorations and carets drawn after a DrawAligned use it to land on the painted text.

func ApplyFilters

func ApplyFilters(l *Layer, region Rect, f *Filters, shape FilterShape)

ApplyFilters applies the list to l's device region in place. The ops' lengths are logical (CSS) pixels, scaled here by the layer's device scale; shape is the box the list applies to. The region must already cover every op's Extent; blur, drop-shadow and refract read transparent outside it.

func BorderRing

func BorderRing(r Rect, radii Corners, widths Insets, num, denom int) (outer, oradii, inner, iradii, w [4]float32)

BorderRing is RoundedBorderSides' ring at device scale num/denom: the outer box (x0, y0, x1, y1) and radii, the inner box and radii, and the side widths, top, right, bottom, left.

func BoxDivisor

func BoxDivisor(n int) (half, recip uint32)

BoxDivisor is how a box pass of 2r+1 taps, or a downsample block of n pixels, divides its channel sums: (v + Half) * Recip >> 32, a rounded division a shader repeats with a 32x32-bit multiply's high word (Recip fits 32 bits from n 2 on; n 1 divides by nothing).

func BoxShadowMask

func BoxShadowMask(r Rect, radii Corners, s BoxShadow, num, denom int) (m *ShadowMask, box Rect, coreW, coreH int)

BoxShadowMask is how BoxShadow paints s for the box r at device scale num/denom: the cached mask of a core box coreW x coreH, the box's device rect, and the core's size. A shadow pixel (x, y) takes the mask's coverage at (stretch(x-box.X, box.W, coreW), stretch(y-box.Y, box.H, coreH)) less Origin, where stretch maps the box's columns onto the core's, repeating its middle one across a longer box: b below core/2 stays b, b from core/2+full-core on drops full-core, and the rest is core/2.

func CollapseWhiteSpace

func CollapseWhiteSpace(s string, newlines bool) string

CollapseWhiteSpace applies CSS white-space collapsing (CSS Text 3 §4.1.1) to a paragraph: tabs read as spaces, the spaces around a newline go, each run of spaces collapses to one, and every line loses its leading and trailing spaces. With newlines set the newlines collapse too, each becoming a space before the runs collapse (normal, nowrap); without it they stay (pre-line).

func DecodeImage

func DecodeImage(data []byte) (image.Image, error)

DecodeImage decodes image bytes: an animated GIF or APNG to an *Animation, anything else (PNG, JPEG, GIF, still WebP) to a still image. Animated WebP is not decoded: golang.org/x/image/webp, the pure-Go decoder, reads still images only.

func DeviceBox

func DeviceBox(r Rect, radii Corners, num, denom int) (box, rc [4]float32)

DeviceBox is the rounded box r with radii as the shape painters rasterize it at device scale num/denom: its device rect as x0, y0, x1, y1 and its radii clockwise from top-left, scaled down together where adjacent ones overlap.

func EllipsePath

func EllipsePath(p *Path, cx, cy, rx, ry float64)

EllipsePath appends the ellipse centered at (cx, cy) with radii rx and ry (logical pixels) to p as one closed subpath.

func EllipsizeText

func EllipsizeText(f Font, text string, mode EllipsizeMode, maxWidth, px float64) string

EllipsizeText shortens text so its advance fits maxWidth, cutting at mode and inserting an ellipsis; see Typeface.Ellipsize. Package-level so any Font - a lone typeface or a fallback chain - truncates through the same code path the methods use.

func FixtureFontData

func FixtureFontData() []byte

FixtureFontData returns the bytes of the bundled Cantarell Regular fixture font (SIL Open Font License 1.1; the license text ships in testdata/LICENSE-Cantarell.txt). It is the single face every golden snapshot is shaped with.

func FixtureHebrewFontData

func FixtureHebrewFontData() []byte

FixtureHebrewFontData returns the bytes of the bundled Hebrew fixture face; see render/testdata/README.md for why a second face exists.

func GlyphCoverage

func GlyphCoverage(face *Typeface, gid font.GID, scale, penX, penY float64, col Color) (*GlyphMask, Rect, bool)

GlyphCoverage is the coverage mask DrawGlyph tints with the text color for an outline glyph, and the device rect it covers with the pen at (penX, penY); false for a glyph drawn in color or from a bitmap, or a blank one.

func GrainStrength

func GrainStrength(opacity float64) uint32

GrainStrength is PaintGrain's opacity as the 0..255 factor its noise scales by.

func GrainTile

func GrainTile(w, h int) []byte

GrainTile is PaintGrain at full strength as w x h premultiplied BGRA pixels whose top left is the origin: a renderer without PaintGrain draws it at the strength's alpha, within one level of PaintGrain's blend, for the same grain at the same offsets.

func Hold

func Hold() (release func())

Hold keeps every Retire from now on from freeing its rasters until the function it returns is called: a renderer reading a raster's pixels past the List that drew it holds them for as long as it reads.

func NRGBA

func NRGBA(data []byte, stride, width, height int) *image.NRGBA

NRGBA converts a Canvas-format pixel buffer — ARGB8888 premultiplied in wl_shm byte order — into a straight-alpha image.NRGBA: exactly the pixel representation the PNG goldens store, so encode, decode, and compare all see the same bytes and the comparison is exact. stride is in bytes; the returned image's rows are tight.

func PathCoverageMask

func PathCoverageMask(p *Path, num, denom int) (CoverageMask, Rect, bool)

PathCoverageMask is p's whole coverage at device scale num/denom, cached by content whatever whole pixels it sits at, and the device rect it covers; false for a path past maxCachedPathMask or with no area. FillPath blends its color by it and ApplyPathMask multiplies a layer's region by it.

func Reciprocal

func Reciprocal[F float32 | float64](v F) F

Reciprocal is 1/v rounded to float32: the factor both renderers multiply by in place of dividing by v.

func RectShadow

func RectShadow(r Rect, cornerRadius, blur, num, denom int) (m *ShadowMask, box Rect, coreW, coreH int, ok bool)

RectShadow is how Shadow paints a shadow of blur around the logical rect r with cornerRadius at device scale num/denom, as BoxShadowMask describes: the cached mask of a core box coreW x coreH and the box's device rect; false when there is none to paint. The mask depends on the box only through the rounded corners it clamps, so a resize rebuilds nothing.

func Resample

func Resample(src image.Image, srcRect image.Rectangle, dstW, dstH int) *image.RGBA

Resample scales srcRect of src into a fresh dstW x dstH RGBA with the CatmullRom kernel. Cubic resampling is what keeps fractional and non-integer down- and upscales from the blockiness of a nearest-neighbor pass (stubbedev/lys-ui#14); the canvas's own image drawing is nearest-neighbor and must never see unresampled pixels.

Memory stays bounded by the rows in flight, never the image: a downscale by two or more first box-averages whole factor blocks (one source row read at a time), and the cubic pass keeps only the horizontally filtered rows its vertical taps span. Any source model reads through a row converter, YCbCr and NRGBA without a per-pixel interface call.

func ResampleInto

func ResampleInto(dst, src *image.RGBA, srcRect image.Rectangle)

ResampleInto scales srcRect of src over all of dst bilinearly, reusing dst's pixels: the per-frame path for video, where a cubic kernel and a fresh raster per frame would cost more than the frame budget allows.

func ResampleTo

func ResampleTo(dst *image.RGBA, src image.Image, srcRect image.Rectangle) error

ResampleTo is Resample into an image the caller owns, pixels its memory holds (reused, or off the Go heap): srcRect of src scaled over all of dst, at dst's own stride and origin, so a sub-image takes it too. It writes every pixel of dst, the same bytes Resample would, and refuses an empty dst or one its pixels cannot hold.

func Retire

func Retire(free func())

Retire runs free, which releases the memory of rasters their owner has already made unreachable for new draws, once every List whose recording started before the call has ended: at once, on the calling goroutine, when none is open; otherwise on the goroutine that ends the last of them. Frees run in the order they were retired. It is safe from any goroutine.

func RoundedRadius

func RoundedRadius(full Rect, radius, num, denom int) float32

RoundedRadius is RoundedRect's corner radius over its device rect full at num/denom: radius scaled, at most half the shorter side.

func RoundedRectPath

func RoundedRectPath(p *Path, r Rect, radii Corners)

RoundedRectPath appends the rounded rect r (logical pixels, radii clockwise from top-left) to p as one closed subpath.

func SideReciprocals

func SideReciprocals(w [4]float32) [4]float32

SideReciprocals are a border's reciprocal side widths (top, right, bottom, left), 0 for a side of no width: what borderSide, on the CPU and in the shader, scales each side's distance by.

func Stride

func Stride(widthPx int) int

Stride returns the row stride in bytes for a width in pixels (ARGB8888).

func TexelScale

func TexelScale(n int, size float32) float32

TexelScale is the factor that maps a tile offset onto one of n texels across a tile size device pixels long: n over size, rounded once to float32, so both renderers truncate the same product.

func TrimLayers

func TrimLayers() error

TrimLayers frees the pooled scratch layers and hands their pages back: a whole canvas each, kept so the next effect allocates none. An application calls it once it has been idle a while; the next ScratchLayer allocates again.

func WordSep

func WordSep(r rune) bool

WordSep reports whether r is a CSS word separator: the characters word-spacing widens and justify distributes space across.

func WrapText

func WrapText(f Font, text string, maxWidth, px float64) []string

WrapText breaks text into lines of at most maxWidth pixels; see Wrap. Package-level so any Font wraps through the same code path.

func WrapTextOpts

func WrapTextOpts(f Font, s string, maxWidth, px float64, o WrapOptions) []string

WrapTextOpts breaks text into lines of at most maxWidth pixels under the wrap options; see WrapText for the default behavior.

Types

type Affine

type Affine struct{ A, B, C, D, E, F float64 }

Affine is a 2-D affine map in device pixels: (x, y) goes to (A·x + C·y + E, B·x + D·y + F). The zero value maps everything to the origin; Identity leaves points where they are.

func Rotate

func Rotate(deg float64) Affine

Rotate is the map rotating about the origin by deg degrees, clockwise on screen (y grows downward), as a GSK snapshot rotation does.

func Scale

func Scale(sx, sy float64) Affine

Scale is the map scaling about the origin.

func Translate

func Translate(dx, dy float64) Affine

Translate is the map moving by (dx, dy).

func (Affine) About

func (m Affine) About(px, py float64) Affine

About is m applied about the pivot (px, py) instead of the origin.

func (Affine) Apply

func (m Affine) Apply(x, y float64) (float64, float64)

Apply maps the point (x, y).

func (Affine) Invert

func (m Affine) Invert() (Affine, bool)

Invert returns the inverse map; false when m collapses an axis.

func (Affine) MapBounds

func (m Affine) MapBounds(r Rect) Rect

MapBounds is the smallest pixel rect covering r's image under m.

func (Affine) Mul

func (m Affine) Mul(n Affine) Affine

Mul is m∘n: the map applying n first, then m. A chain of snapshot operations t1, t2, t3 on a point is t1.Mul(t2).Mul(t3).

type Alignment

type Alignment uint8

Alignment selects how a drawn run is positioned inside its box.

const (
	AlignStart Alignment = iota
	AlignCenter
	AlignEnd
)

Text alignments: start (left for LTR lines), center, end.

type Animation

type Animation struct {
	Frames []StillImage
	Delays []time.Duration
	Loops  int
}

Animation is a decoded animated image (GIF, APNG): every frame fully composited over the canvas, how long each shows, and how many times the sequence plays (0: forever). It is an image.Image as its first frame, so every still-image path - sizing, a static paint, a cache - takes it unchanged; an animating painter steps through Frames. Each frame is a still image with its own identity, shared by every painter of the animation, so a GPU renderer keeps one texture per frame however many widgets show it.

func (*Animation) At

func (a *Animation) At(x, y int) color.Color

At implements image.Image: the first frame.

func (*Animation) Bounds

func (a *Animation) Bounds() image.Rectangle

Bounds implements image.Image: the canvas.

func (*Animation) ColorModel

func (a *Animation) ColorModel() color.Model

ColorModel implements image.Image (the first frame's).

func (*Animation) PixelBytes

func (a *Animation) PixelBytes() int

PixelBytes is the frames' combined pixel cost, what a byte-budget cache charges for the animation.

type ArcGeometry

type ArcGeometry struct {
	CX, CY, R, Half, Start, Sweep, SX, SY, EX, EY float32
	Full                                          bool
}

ArcGeometry is Arc's stroke in device pixels, in the float32 a GPU shader evaluates it in: the center, radius and half width, the start angle and sweep (Full for a whole turn), and the cap centers, the stroke's middle at both ends.

func ArcOf

func ArcOf(cx, cy, radius, width, start, sweep float64, num, denom int) ArcGeometry

ArcOf is the stroke Arc paints at device scale num/denom.

func (ArcGeometry) Coverage

func (g ArcGeometry) Coverage(x, y int) float32

Coverage is the stroke's coverage of pixel (x, y): within the sweep, the center's distance to the circle; past it, to the nearer cap. Angles come from atan2f, each step rounding as the shader's does.

type BlendMode

type BlendMode uint8

BlendMode is one CSS mix-blend-mode operator. BlendNormal is the zero value, so an unset property composites as plain source-over.

const (
	BlendNormal BlendMode = iota
	BlendMultiply
	BlendScreen
	BlendOverlay
	BlendDarken
	BlendLighten
	BlendColorDodge
	BlendColorBurn
	BlendHardLight
	BlendSoftLight
	BlendDifference
	BlendExclusion
	BlendHue
	BlendSaturation
	BlendColor
	BlendLuminosity
)

The blend modes, CSS's sixteen.

func BlendModeNamed

func BlendModeNamed(name string) (BlendMode, bool)

BlendModeNamed resolves a CSS keyword; false for anything else.

func (BlendMode) String

func (m BlendMode) String() string

String returns the CSS keyword of the mode.

type BlurPlan

type BlurPlan struct {
	D     int
	Boxes [3]int
}

BlurPlan is how a blur of a device radius runs: at 1/D resolution (D 1 runs at full), area-averaged down by D x D blocks and sampled back bilinearly in 1/256 steps, through three separable box passes of Boxes' radii (a pass of radius 0 is skipped). Every step is integer arithmetic, so a GPU repeats it exactly.

func BlurPlanOf

func BlurPlanOf(radius float64) (BlurPlan, bool)

BlurPlanOf is the plan for a blur of device radius radius; false for none.

type BoxShadow

type BoxShadow struct {
	X, Y, Blur, Spread int
	Color              Color
	Inset              bool
}

BoxShadow is one CSS box-shadow layer: an offset, a blur radius (the Gaussian spans two sigmas of it, CSS's convention), a spread, and whether it paints inside the box instead of outside.

func (BoxShadow) Extent

func (s BoxShadow) Extent() Insets

Extent returns how far an outer shadow paints beyond its box, per side; an inset shadow never paints outside. Callers owe these pixels damage.

type Canvas

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

Canvas paints into a raw ARGB8888 premultiplied pixel buffer: the exact format of a wl_shm buffer at any scale. All drawing clips to the intersection of the requested rect, the canvas bounds, and any clip set with PushClip, and blends through the opacity set with PushAlpha.

The canvas carries a device scale: a rational number of device (buffer) pixels per logical pixel - 240/120 is 2x, 150/120 is the fractional 1.25x. Primitive arguments (FillRect, RoundedRect, text, ...) are in logical pixels and land on device pixels rounded outward, so a logical rect fully covers the device area it spans; text is shaped at its logical size and rasterized at the device scale, which keeps it crisp at any factor. PushClip takes a logical rect like every primitive; the bounds returned by Rect and the explicit device bridge (MapRect, ClearDevice, FillRectDevice, PushClipDevice) are in device pixels.

func New

func New(data []byte, stride, width, height int) *Canvas

New returns a canvas over data: height rows of stride bytes holding width ARGB8888 pixels each, at device scale 1 (one device pixel per logical pixel).

func NewRecorder

func NewRecorder(width, height, num, denom int) *Canvas

NewRecorder returns a canvas that records into a fresh List instead of painting: a width x height device canvas at scale num/denom, as NewScaled's. Its layers record into the same List.

func NewScaled

func NewScaled(data []byte, stride, width, height, num, denom int) *Canvas

NewScaled returns a canvas over data at the given device scale: num device pixels per denom logical pixels (240/120 doubles). width and height are the buffer's device size. It panics on a non-positive scale, which is a programming error, not a runtime condition.

func (*Canvas) ApplyState

func (c *Canvas) ApplyState(s State)

ApplyState gives c the clip, opacity and brightness of s: a player rasterizing one recorded call onto a canvas of its own.

func (*Canvas) Arc

func (c *Canvas) Arc(cx, cy, radius, width, start, sweep float64, col Color)

Arc strokes a circular arc of the logical circle centered at (cx, cy) with the given radius (to the stroke's middle) and stroke width, clockwise from start through sweep radians (0 is three o'clock, -π/2 is twelve). Caps are round, like cairo's LINE_CAP_ROUND; a sweep of 2π or more is the whole circle. Anti-aliased by per-pixel signed distance at the device scale.

func (*Canvas) BeginOverlays

func (c *Canvas) BeginOverlays()

BeginOverlays arms the frame's top layer: until FlushOverlays, Overlay defers its paints instead of running them in place. A window arms it around painting its tree, so a widget that hangs content outside its own bounds (an open dropdown list) paints above every later sibling, as a popover would.

func (*Canvas) BorderRect

func (c *Canvas) BorderRect(r Rect, width int, col Color)

BorderRect blends col over a hollow rect of the given logical thickness. The stroke grows inward from the rect edges.

func (*Canvas) BoxShadow

func (c *Canvas) BoxShadow(r Rect, radii Corners, s BoxShadow)

BoxShadow paints one CSS box-shadow layer for the box r with the given corner radii. An outer shadow is the box offset and grown by the spread, blurred, and clipped to outside the box itself (so a translucent box never shows its own shadow through); an inset shadow fills the box's inside except the offset, spread-shrunk hole, blurred at the hole's edge. The blur is Gaussian with sigma half the blur radius, evaluated per pixel from the silhouette's signed distance.

func (*Canvas) Clear

func (c *Canvas) Clear(r Rect, col Color)

Clear overwrites the logical rect with col, ignoring what is underneath. ClearDevice is the device-space counterpart for callers that already hold mapped rects.

func (*Canvas) ClearDevice

func (c *Canvas) ClearDevice(r Rect, col Color)

ClearDevice overwrites the device-pixel rect r with col, ignoring what is underneath. Unlike Clear it applies no logical mapping: it is the bridge for frame pipelines that track damage in device pixels.

func (*Canvas) Composite

func (c *Canvas) Composite(l *Layer, src Rect, m Affine, alpha float64)

Composite draws the src device rect of l onto c through m (layer device pixels to canvas device pixels), bilinearly filtered, blended through c's opacity times alpha and clipped to c's clip. Pixels of l outside src count as transparent, so the drawn edge antialiases. A whole-pixel translation copies without filtering.

func (*Canvas) CompositeProjective

func (c *Canvas) CompositeProjective(l *Layer, src Rect, m M3, alpha float64)

CompositeProjective draws the src device rect of l onto c through the projective map m (layer device pixels to canvas device pixels), inverse-mapping each destination pixel, sampling bilinearly, and blending like Composite. Pixels mapping behind the viewer (w <= 0) are skipped — the classic near-plane clip a one-plane raster owes.

func (*Canvas) DeviceScale

func (c *Canvas) DeviceScale() (num, denom int)

DeviceScale returns the canvas's device scale as a rational: num device pixels per denom logical pixels.

func (*Canvas) DrawCanvasDevice

func (c *Canvas) DrawCanvasDevice(src *Canvas, x, y int)

DrawCanvasDevice paints src over c with its top-left device pixel at (x, y), one to one - a retained surface's canvas drawn back at the scale it was allocated at. Like DrawImageDevice it clips to c's clip, blends through c's opacity, and overwrites where both pixels are opaque.

func (*Canvas) DrawGlyph

func (c *Canvas) DrawGlyph(face *Typeface, gid font.GID, scale, penX, penY float64, col Color)

DrawGlyph paints one glyph of face with its baseline pen at the device point (penX, penY) at scale (device pixels per font unit), as shaped text paints each: a Player's Glyph.

func (*Canvas) DrawImage

func (c *Canvas) DrawImage(img image.Image, x, y int)

DrawImage blends img onto the canvas, scaled from its natural (logical) size to the device rect its logical placement spans.

func (*Canvas) DrawImageCover

func (c *Canvas) DrawImageCover(img image.Image, r Rect, radii Corners)

DrawImageCover blends img onto the canvas scaled to COVER r: the image scales uniformly until it fills the rect, centered, the overflow cropped (CSS background-size: cover), the whole masked by the rounded rect.

func (*Canvas) DrawImageCoverImage

func (c *Canvas) DrawImageCoverImage(ic *Icon, r Rect, radii Corners)

DrawImageCoverImage is DrawImageCover for an Icon's pixels.

func (*Canvas) DrawImageDevice

func (c *Canvas) DrawImageDevice(img image.Image, x, y int)

DrawImageDevice blends img onto the canvas one-to-one in device pixels, its top-left corner at (x, y). It is the device-space counterpart of DrawImage: rasters that were already resampled for the device rect they cover - widget.Image's cache - must land without a second scale, which DrawImage's nearest-neighbor logical mapping would apply at any device scale other than 1.

Opacity (PushAlpha) modulates here, at blit time, and nowhere earlier: the cached rasters are premultiplied and shared by every consumer, so baking a factor into them would double-multiply the next frame and bleed into widgets fading independently. Multiplying the premultiplied channels together (blend then modulate) keeps a modulated raster premultiplied, exactly like the AA coverage ramps.

func (*Canvas) DrawImageRect

func (c *Canvas) DrawImageRect(img image.Image, r Rect)

DrawImageRect blends img onto the canvas scaled into the logical rect r: nearest-neighbor sampling, the mask-image rasterizer's own.

func (*Canvas) DrawLayer

func (c *Canvas) DrawLayer(l *Layer, src Rect, mode BlendMode)

DrawLayer draws l's device rect over c one to one through the blend mode: every pixel of src blends over the canvas's pixel at the same coordinates, clipped to c's clip and modulated by c's opacity. BlendNormal is the plain source-over copy.

func (*Canvas) FillPath

func (c *Canvas) FillPath(p *Path, col Color)

FillPath fills the path's subpaths with col, anti-aliased, under the clip and the pushed opacity. Overlapping subpaths fill once.

func (*Canvas) FillRect

func (c *Canvas) FillRect(r Rect, col Color)

FillRect blends col over the logical rect with source-over compositing.

func (*Canvas) FillRectDevice

func (c *Canvas) FillRectDevice(r Rect, col Color)

FillRectDevice blends col over the device-pixel rect with source-over compositing; the device counterpart of FillRect.

func (*Canvas) FinishFocus

func (c *Canvas) FinishFocus()

FinishFocus draws the focus ring if no container reached its widget (a container defined outside the kit, a subtree composited from a layer) and disarms it.

func (*Canvas) FlushOverlays

func (c *Canvas) FlushOverlays()

FlushOverlays runs the deferred top-layer paints in queue order (one queued while flushing runs too) and disarms the frame.

func (*Canvas) Layer

func (c *Canvas) Layer(old *Layer, region Rect) *Layer

Layer returns a layer the size and scale of c whose region (device pixels) is transparent and is the layer's clip; drawing lands only there. old's buffer is reused whenever it is big enough, so a layer kept across frames allocates once, and again only when it grows.

func (*Canvas) Line

func (c *Canvas) Line(x0, y0, x1, y1, width int, col Color)

Line blends col along the segment from logical (x0, y0) to (x1, y1) with the given thickness in logical pixels, anti-aliased with per-pixel signed-distance coverage at the device scale. Caps are round.

func (*Canvas) MapRect

func (c *Canvas) MapRect(r Rect) Rect

MapRect maps the logical rect r into device pixels on this canvas.

func (*Canvas) MarkFocus

func (c *Canvas) MarkFocus(key any, paint func(*Canvas))

MarkFocus arms the frame's focus ring: Painted draws it the moment key's widget finishes painting, so everything painted after it in tree order (a card over a list, a later sibling) covers it, as a widget's own outline would be covered. A nil key clears it.

func (*Canvas) Overlay

func (c *Canvas) Overlay(paint func(*Canvas))

Overlay paints on the frame's top layer: deferred to FlushOverlays while a frame is armed, in place otherwise (a subtree painted on its own has no later siblings to escape). The deferred paint runs under the frame's clip, not the caller's, so a scrolled container does not cut it, with the opacity in force now.

func (*Canvas) PaintGradient

func (c *Canvas) PaintGradient(r Rect, radii Corners, g Gradient)

PaintGradient fills r with g, clipped to its rounded outline (radii in logical pixels). Colors interpolate premultiplied between the stops. A linear gradient's line spans the box's corners along its angle, CSS's rule; radial and conic geometry sizes against the box.

func (*Canvas) PaintGradientTiles

func (c *Canvas) PaintGradientTiles(g Gradient, t Tile, clip Rect, radii Corners)

PaintGradientTiles paints g over every tile t lays out, each tile its own gradient box, clipped to clip's rounded outline.

func (*Canvas) PaintGrain

func (c *Canvas) PaintGrain(r Rect, radii Corners, opacity float64, ox, oy int)

PaintGrain blends a fine luminance noise over the rounded rect r: each device pixel lightens or darkens by a hashed amount up to opacity, the etching of frosted glass. The noise is anchored at the logical origin (ox, oy) - the surface it belongs to - so it moves with the surface and repaints identically: a pure function of the pixel's offset from the origin, deterministic on every machine.

func (*Canvas) PaintImageTiles

func (c *Canvas) PaintImageTiles(img image.Image, t Tile, clip Rect, radii Corners)

PaintImageTiles paints img over every tile t lays out, each tile the image scaled to the tile's size and nearest sampled, all clipped to clip's rounded outline (radii in logical pixels).

func (*Canvas) Painted

func (c *Canvas) Painted(w any)

Painted reports that w finished painting: the containers call it after each child, drawing the armed focus ring after its widget.

func (*Canvas) PopAlpha

func (c *Canvas) PopAlpha(prev float64)

PopAlpha restores an opacity returned by PushAlpha.

func (*Canvas) PopBrightness

func (c *Canvas) PopBrightness(prev float64)

PopBrightness restores a factor returned by PushBrightness.

func (*Canvas) PopClip

func (c *Canvas) PopClip(prev Rect)

PopClip restores a clip returned by PushClip.

func (*Canvas) PushAlpha

func (c *Canvas) PushAlpha(a float64) float64

PushAlpha scales the opacity of everything painted until the matching PopAlpha: every blended primitive (FillRect, RoundedRect, gradients, Line, text, images) has its premultiplied color channels - color with the alpha, never the alpha alone - multiplied by a. It is the subtree-opacity primitive fades hang off: nested pushes multiply, and a zero push makes every blend a no-op without touching a pixel. a clamps to [0, 1], so a spring tween's overshoot saturates instead of over-brightening.

It returns the previous opacity; restore it with PopAlpha, the same save-and-restore shape as PushClip. Clear and ClearDevice are the one exception: they overwrite pixels rather than blend, so a faded subtree cannot punch transparent holes in its background.

func (*Canvas) PushBrightness

func (c *Canvas) PushBrightness(f float64) float64

PushBrightness multiplies the color channels of everything painted until the matching PopBrightness by f: CSS's filter: brightness(). Nested pushes multiply. Channels clamp at the pixel's alpha, so the result stays a valid premultiplied color. It returns the previous factor; restore it with PopBrightness.

func (*Canvas) PushClip

func (c *Canvas) PushClip(r Rect) Rect

PushClip narrows subsequent drawing to the intersection of the logical rect r, mapped to device pixels the way FillRect maps, and the current clip. It returns the previous clip; restore it with PopClip.

func (*Canvas) PushClipDevice

func (c *Canvas) PushClipDevice(r Rect) Rect

PushClipDevice is PushClip for a rect already in device pixels (a damage region, a layer's rect).

func (*Canvas) Recording

func (c *Canvas) Recording() *List

Recording is the List c records into, nil for a raster canvas.

func (*Canvas) Rect

func (c *Canvas) Rect() Rect

Rect returns the full canvas bounds in device pixels.

func (*Canvas) Reset

func (c *Canvas) Reset(data []byte, stride, width, height, num, denom int) *Canvas

Reset re-points the canvas at a fresh buffer, the window-owned canvas's per-frame entry: the same struct re-readied instead of a NewScaled allocation per painted frame. The scale must be positive, as NewScaled's. Frame state (overlays, focus, counters) starts clean, as after a completed frame.

func (*Canvas) ResetRecorder

func (c *Canvas) ResetRecorder(width, height, num, denom int) *Canvas

ResetRecorder readies a recording canvas for the next frame, as Reset does a raster one: its List ends, then empties and opens again (Retire), and the canvas takes the given size and scale.

func (*Canvas) ResetTouched

func (c *Canvas) ResetTouched() int

ResetTouched zeroes the drawn-pixel counter and returns the previous value.

func (*Canvas) ReuseLayer

func (c *Canvas) ReuseLayer(l *Layer, region Rect) bool

ReuseLayer readies l to be composited again as it was last painted, without clearing or repainting it, and reports whether it could: a false return leaves l to Layer and a repaint. On a raster canvas l must be live, not a scratch layer, and of c's stride, size and scale. On a recording canvas the player that last readied l must still hold its backing at c's size and scale; no call is recorded, so the List composites l from that backing, and it is that player that is to play the List.

func (*Canvas) RoundedBorder

func (c *Canvas) RoundedBorder(r Rect, radii Corners, widths Insets, col Color)

RoundedBorder strokes the ring between r's rounded outline and its inner edge, inset per side by widths: a CSS border. The inner corner radii shrink by the adjacent widths.

func (*Canvas) RoundedBorderSides

func (c *Canvas) RoundedBorderSides(r Rect, radii Corners, widths Insets, cols [4]Color)

RoundedBorderSides is RoundedBorder with a color per side (top, right, bottom, left). A ring pixel takes the color of the side it is relatively closest to, which splits the corners along their diagonals the way CSS borders join.

func (*Canvas) RoundedRect

func (c *Canvas) RoundedRect(r Rect, radius int, col Color)

RoundedRect blends col over a filled logical rect with corners rounded by radius logical pixels, anti-aliased with per-pixel signed-distance coverage. The rasterization runs at the device scale.

func (*Canvas) RoundedRectCorners

func (c *Canvas) RoundedRectCorners(r Rect, radii Corners, col Color)

RoundedRectCorners blends col over r with each corner rounded by its own radius, anti-aliased. Radii that overlap scale down together, per CSS.

func (*Canvas) ScratchLayer

func (c *Canvas) ScratchLayer(region Rect) *Layer

ScratchLayer is Layer for an offscreen buffer used within one paint: it comes from a pool shared by every widget and goes back with Release, so a subtree effect costs one buffer per nesting depth rather than one per widget held for good, and none at a new size while a pooled buffer is big enough.

func (*Canvas) ScratchSnapshot

func (c *Canvas) ScratchSnapshot(region Rect) *Layer

ScratchSnapshot is Snapshot into a scratch layer.

func (*Canvas) Shadow

func (c *Canvas) Shadow(r Rect, cornerRadius, blur int, col Color)

Shadow blends a box shadow for the logical rect: the blurred silhouette of a rounded rect, centered on r (no spread), falling off with a precomputed Gaussian kernel. blur is the falloff radius in logical pixels. The shadow paints OUTSIDE r - full strength at the edges, tail gone past blur - so callers keep layout and hit-testing on r itself and owe the ring only damage. The coverage raster is cached per core size, radius and blur in device pixels in RectShadow, so a hover twitch that repaints the same shadow re-blends the pixels but never re-Gaussians. Per-pixel coverage scales all four premultiplied channels exactly as RoundedRect's AA, and the draw blends through the PushAlpha stack like every primitive, so a fading surface fades its shadow with it.

func (*Canvas) Snapshot

func (c *Canvas) Snapshot(old *Layer, region Rect) *Layer

Snapshot copies c's device region into a layer shaped like c, reusing old's buffer when it fits, so a backdrop-filter held across frames allocates once. The snapshot is the input backdrop-filter filters: what has been painted under the region so far this frame.

func (*Canvas) Touched

func (c *Canvas) Touched() int

Touched returns the number of pixels written since the last ResetTouched (or since the canvas was created). Blends count even when their source color equals the destination.

type Chain

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

Chain shapes mixed-script text across faces: every rune goes to the first face that covers it, so a line mixing latin, CJK, and emoji renders instead of drawing .notdef boxes. The picks cache per rune, so repeated shapes pay one lookup per distinct rune. Like Typeface, a chain is not safe for concurrent use.

func FixtureChain

func FixtureChain() (*Chain, error)

FixtureChain returns a fresh fallback chain over the two bundled fixture faces — Latin and digits from Cantarell, Hebrew from Noto Sans Hebrew — the shape mixed-direction goldens pin.

func NewChain

func NewChain(primary *Typeface, fallback ...*Typeface) *Chain

NewChain returns a chain shaping with primary and, for runes it lacks, the first covering face of fallback. A nil primary panics here, naming the argument — the same nil-face contract the widget constructors enforce — instead of failing on the first Shape.

func (*Chain) Draw

func (c *Chain) Draw(cv *Canvas, s *ShapedText, x, baselineY int, col Color)

Draw paints a shaped line; see ShapedText.Draw.

func (*Chain) DrawAligned

func (c *Chain) DrawAligned(cv *Canvas, s string, box Rect, px float64, col Color, h Alignment) *ShapedText

DrawAligned draws text inside box with the given alignment; see Typeface.DrawAligned.

func (*Chain) DrawAlignedDir

func (c *Chain) DrawAlignedDir(cv *Canvas, s string, box Rect, px float64, col Color, h Alignment, d text.Direction) *ShapedText

DrawAlignedDir draws text inside box under base direction d; start and end mirror for a right-to-left base. See text.Direction.

func (*Chain) Ellipsize

func (c *Chain) Ellipsize(text string, maxWidth, px float64) string

Ellipsize shortens text to fit maxWidth; see Typeface.Ellipsize.

func (*Chain) Face

func (c *Chain) Face(r rune) *Typeface

Face returns the face rune r shapes with: the diagnostic view of the fallback decision, and a way for tests to pin which family a rune lands on.

func (*Chain) Metrics

func (c *Chain) Metrics() FaceMetrics

Metrics reports the primary face's metrics; the CSS font-relative units all resolve against the primary face.

func (*Chain) Prewarm

func (c *Chain) Prewarm(rs ...rune)

Prewarm resolves rs now, on the calling goroutine: a font store warming up off the paint path, so the first frame has its faces.

func (*Chain) Primary

func (c *Chain) Primary() *Typeface

Primary is the chain's first face: the one variants resolve from.

func (*Chain) Shape

func (c *Chain) Shape(s string, px float64) *ShapedText

Shape splits text into runs of consecutive runes sharing a face and shapes each with it, on one shared baseline, serving repeats from the process-wide shaping cache like Typeface.Shape. Within that, the line resolves into directional runs (internal/text.BidiRuns) laid out in visual order, so mixed Hebrew/Arabic + Latin lines render reading-correct. The chain is the key: a chain held by the app reuses its entries across frames, and two chains over the same faces never collide. Empty text still shapes one primary run, so its metrics reserve the font's line height.

func (*Chain) ShapeDir

func (c *Chain) ShapeDir(s string, px float64, d text.Direction) *ShapedText

ShapeDir shapes under base direction d; see Chain.Shape and text.Direction.

func (*Chain) ShapeDirRunes

func (c *Chain) ShapeDirRunes(rs []rune, px float64, d text.Direction) *ShapedText

ShapeDirRunes shapes a rune slice under d; see Font.ShapeDirRunes.

func (*Chain) ShapeRune

func (c *Chain) ShapeRune(r rune, px float64) *ShapedText

ShapeRune shapes one rune; see Font.ShapeRune and Chain.Shape.

func (*Chain) ShapeRunes

func (c *Chain) ShapeRunes(rs []rune, px float64) *ShapedText

ShapeRunes shapes a rune slice; see Font.ShapeRunes.

func (*Chain) Spaced

func (c *Chain) Spaced(px float64) *Chain

Spaced returns the chain shaping with px of letter spacing after every cluster, whichever face a rune lands on (see Typeface.Spaced).

func (*Chain) Tabular

func (c *Chain) Tabular() *Chain

Tabular returns the chain shaping with each face's tnum twin: digits on a uniform advance grid, what a clock or a numeric column wants. The variant keeps its own rune picks, so it never rewrites the base chain's.

func (*Chain) Weighted

func (c *Chain) Weighted(w int) *Chain

Weighted is the chain at CSS weight w (see Typeface.Weighted).

func (*Chain) WithFeatureSpec

func (c *Chain) WithFeatureSpec(spec string) *Chain

WithFeatureSpec returns the chain shaping with the OpenType features in spec on, whichever face a rune lands on (see Typeface.WithFeatureSpec).

func (*Chain) WithResolver

func (c *Chain) WithResolver(resolve func(rune) *Typeface, onResolved func()) *Chain

WithResolver installs a store-backed face picker for runes neither the primary nor the fallback list covers, and returns the chain. It runs on a goroutine of its own, as it may read and parse font files: until it answers, such a rune shapes with the primary. When an answer changes the shaping, lines shape anew under it and onResolved, nil for none, runs on that goroutine: the owner lays out and paints again. internal/sysfont.Fallback wires one to the system font store.

func (*Chain) WithVariations

func (c *Chain) WithVariations(vs ...Variation) *Chain

WithVariations returns the chain shaping with every face instantiated at vs (each face ignores axes it lacks); faces the store resolves for uncovered runes shape at their defaults.

func (*Chain) WordSpaced

func (c *Chain) WordSpaced(px float64) *Chain

WordSpaced returns the chain shaping with px of word spacing after every word separator, whichever face a rune lands on (see Typeface.WordSpaced).

func (*Chain) Wrap

func (c *Chain) Wrap(text string, maxWidth, px float64) []string

Wrap breaks text into lines of at most maxWidth pixels; see Typeface.Wrap.

type Color

type Color uint32

Color is a premultiplied ARGB8888 pixel value, laid out as 0xAARRGGBB. Premultiplied is the native format of both the wl_shm buffers and Go's image.RGBA, so colors pass through blending without conversion.

func ColorFromBytes

func ColorFromBytes(b []byte) Color

ColorFromBytes decodes a premultiplied color from the wl_shm byte order: little-endian ARGB8888, that is bytes B, G, R, A.

func RGB

func RGB(r, g, b uint8) Color

RGB builds an opaque color from non-premultiplied components.

func RGBA

func RGBA(r, g, b, a uint8) Color

RGBA builds a color from non-premultiplied components and premultiplies them.

func (Color) A

func (c Color) A() uint8

A returns the alpha channel.

func (Color) B

func (c Color) B() uint8

B returns the premultiplied blue channel.

func (Color) G

func (c Color) G() uint8

G returns the premultiplied green channel.

func (Color) R

func (c Color) R() uint8

R returns the premultiplied red channel.

func (Color) Straight

func (c Color) Straight() [4]byte

Straight returns the color as non-premultiplied bytes in R, G, B, A order, as PNG and most image code expect.

type Corners

type Corners struct {
	TopLeft, TopRight, BottomRight, BottomLeft int
}

Corners is a per-corner radius set in logical pixels, clockwise from the top-left.

func UniformCorners

func UniformCorners(r int) Corners

UniformCorners returns r on every corner.

type CoverGeometry

type CoverGeometry struct {
	Full                      Rect
	W, H                      int
	Rad, OffX, OffY, InvScale float32
}

CoverGeometry is DrawImageCover's placement of an image of size W x H over its device rect Full, in the float32 a GPU shader evaluates it in: the uniform scale that covers Full (as its reciprocal InvScale), the overflow cropped evenly (OffX, OffY), and Full's rounded corners (Rad, the top-left radius, at most half the shorter side).

func CoverOf

func CoverOf(b image.Rectangle, r Rect, radii Corners, num, denom int) CoverGeometry

CoverOf is the cover of image bounds b over the logical rect r with radii at device scale num/denom.

func (CoverGeometry) At

func (g CoverGeometry) At(x, y int) (cov float32, sx, sy int)

At is pixel (x, y)'s coverage by the rounded rect and the image texel it shows, from the image's top-left.

type CoverageMask

type CoverageMask interface {
	ID() ImageID
	Pix() []uint8
	Size() (w, h int)
}

CoverageMask is an immutable 8bpp coverage mask render caches and blends a color through: a glyph's (GlyphMask), a box-shadow core's or a rect shadow's (ShadowMask). A GPU renderer keys its mask atlas by its ID, which no other mask shares, whatever memory either lives in.

type Decoration

type Decoration struct {
	Lines DecorationLine
	Style DecorationStyle
	Color Color
}

Decoration is a text decoration: its lines, their style, and their color (zero: the text's).

type DecorationLine

type DecorationLine uint8

DecorationLine is a set of text decoration lines (CSS text-decoration-line).

const (
	Underline DecorationLine = 1 << iota
	Overline
	LineThrough
)

Decoration lines.

type DecorationStyle

type DecorationStyle uint8

DecorationStyle is how decoration lines are drawn (CSS text-decoration-style).

const (
	DecorationSolid DecorationStyle = iota
	DecorationDouble
	DecorationDotted
	DecorationDashed
	DecorationWavy
)

Decoration styles.

type DropShadow

type DropShadow struct {
	DX, DY, Blur float64
	Color        Color
}

DropShadow is one drop-shadow() shadow: the offset in device pixels, the blur radius, and the tint.

type EllipsizeMode

type EllipsizeMode uint8

EllipsizeMode selects which end of an overflowing line the ellipsis replaces.

const (
	// EllipsizeNone never truncates: long text overflows and clips.
	EllipsizeNone EllipsizeMode = iota
	// EllipsizeStart cuts from the front: "…cated text".
	EllipsizeStart
	// EllipsizeMiddle keeps the head and the tail: "trunc…text" - the
	// mode for paths and filenames, whose both halves identify them.
	EllipsizeMiddle
	// EllipsizeEnd cuts from the back: "truncated te…".
	EllipsizeEnd
)

type Extend

type Extend uint8

Extend says what lies beyond a gradient's first and last stops.

const (
	// ExtendPad continues the end colors (CSS's plain gradients).
	ExtendPad Extend = iota
	// ExtendRepeat repeats the stop range (CSS's repeating-*).
	ExtendRepeat
	// ExtendReflect mirrors the stop range back and forth (COLR).
	ExtendReflect
)

type FaceMetrics

type FaceMetrics struct {
	Ch, Ex, Cap, Ic, LineHeight float64
}

FaceMetrics is a face's font-relative metrics expressed as ratios of its font size: the advance of "0" (ch), the x-height (ex), the cap height (cap), the ideographic advance (ic), and the natural line height (lh). A zero field means the face does not report it and the CSS fallback ratio applies.

type FilterKind

type FilterKind uint8

FilterKind names one filter function.

const (
	FilterBlur FilterKind = iota
	FilterBrightness
	FilterContrast
	FilterGrayscale
	FilterHueRotate
	FilterInvert
	FilterOpacity
	FilterSaturate
	FilterSepia
	FilterDropShadow
	// FilterRefract is lys-ui's -lys-refract(): the backdrop bends
	// through a glass bezel along the shape's edge.
	FilterRefract
)

The filter functions.

type FilterOp

type FilterOp struct {
	Kind   FilterKind
	Amount float64
	Shadow DropShadow
	// Bezel is -lys-refract()'s bezel width; Amount is then its
	// displacement at the edge. Both CSS pixels.
	Bezel float64
}

FilterOp is one parsed filter function: its kind and amount — the blur radius, the brightness/contrast/opacity/saturate/grayscale/ invert/sepia factor, or the hue-rotate degrees; Shadow carries drop-shadow()'s geometry.

type FilterShape

type FilterShape struct {
	Box   Rect
	Radii Corners
}

FilterShape is the box a filter list applies to, in logical pixels: the border box and its corner radii, what -lys-refract() bends along. The zero shape has no edge, so nothing bends.

type FilterStep

type FilterStep struct {
	Kind    FilterStepKind
	Matrix  MatrixStep
	Blur    BlurPlan
	Shadow  ShadowPlan
	Refract RefractPlan
}

FilterStep is one function of a filter list as a GPU renderer applies it: the field its Kind names holds it.

type FilterStepKind

type FilterStepKind uint8

FilterStepKind is what a FilterStep applies.

const (
	// StepMatrix applies the step's Matrix.
	StepMatrix FilterStepKind = iota
	// StepBlur blurs by the step's Blur plan.
	StepBlur
	// StepShadow draws the step's Shadow plan.
	StepShadow
	// StepRefract bends by the step's Refract plan.
	StepRefract
)

type Filters

type Filters struct {
	N   int
	Ops [MaxFilters]FilterOp
}

Filters is a fixed-capacity filter list, comparable so a restyle can diff it.

func (*Filters) Append

func (f *Filters) Append(op FilterOp)

Append adds op, ignoring the overflow past MaxFilters.

func (*Filters) BrightnessOnly

func (f *Filters) BrightnessOnly() (float64, bool)

BrightnessOnly reports a list made solely of brightness() factors and their product: the PushBrightness fast path paints those without an offscreen layer.

func (*Filters) Empty

func (f *Filters) Empty() bool

Empty reports a list that filters nothing.

func (*Filters) Extent

func (f *Filters) Extent() Insets

Extent is how far the filters paint outside the box they apply to: blur's 3-sigma skirt and every drop-shadow's offset, skirt and spread. Damage rects and effect layers grow by it.

func (*Filters) Steps

func (f *Filters) Steps(steps []FilterStep, shape FilterShape, num, denom int) []FilterStep

Steps is f's functions as filter steps over shape, in order, at device scale num/denom; a function that changes nothing (a refract with no bezel) has none.

type Font

type Font interface {
	// Metrics reports the face's font-relative metrics as ratios of
	// its font size: the CSS ch, ex, cap, ic and lh unit bases. Widgets
	// feed these to the style engine's unit environment.
	Metrics() FaceMetrics
	// Shape lays text out at the given pixel size, resolving the base
	// paragraph direction from the text's first strong character.
	Shape(s string, px float64) *ShapedText
	// ShapeDir is Shape under an explicit base direction; see
	// text.Direction.
	ShapeDir(s string, px float64, d text.Direction) *ShapedText
	// ShapeRune shapes one rune at the pixel size - the per-rune probe
	// wrap measurement and advance math use. Rune-keyed in the caches,
	// so a probe never builds a one-rune string per call.
	ShapeRune(r rune, px float64) *ShapedText
	// ShapeRunes is Shape over a rune slice - the rune-holding widgets'
	// path, keyed on the runes so a frame's shaping never converts them
	// to a string per call.
	ShapeRunes(rs []rune, px float64) *ShapedText
	// ShapeDirRunes is ShapeDir over a rune slice; see ShapeRunes.
	ShapeDirRunes(rs []rune, px float64, d text.Direction) *ShapedText
	// Draw paints a shaped line with its baseline at logical
	// (x, baselineY).
	Draw(cv *Canvas, s *ShapedText, x, baselineY int, col Color)
	// DrawAligned draws text inside box with the given alignment; start
	// and end mirror for a right-to-left paragraph.
	DrawAligned(cv *Canvas, s string, box Rect, px float64, col Color, h Alignment) *ShapedText
	// DrawAlignedDir is DrawAligned under an explicit base direction.
	DrawAlignedDir(cv *Canvas, s string, box Rect, px float64, col Color, h Alignment, d text.Direction) *ShapedText
}

Font shapes and paints text: a single Typeface, or a Chain that falls back across faces for runes the primary face lacks. Widgets take a Font, so either works at every text call site.

type GlyphMask

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

GlyphMask is one cached 8bpp coverage mask, immutable once made: a GPU renderer keys its atlas by its ID. ox, oy locate the mask's origin relative to the glyph's integer pen position: the blit's target pixel is (penX + ox, penY + oy).

func (*GlyphMask) Bounds

func (g *GlyphMask) Bounds(penX, penY float64) Rect

Bounds is the device rect the mask covers with its pen at (penX, penY).

func (*GlyphMask) ID

func (i *GlyphMask) ID() ImageID

ID is the raster's identity.

func (*GlyphMask) Pix

func (g *GlyphMask) Pix() []uint8

Pix is the mask's coverage, Size's width bytes per row.

func (*GlyphMask) Size

func (g *GlyphMask) Size() (w, h int)

Size is the mask's size in device pixels.

type Gradient

type Gradient struct {
	Kind   GradientKind
	Stops  []GradientStop
	Extend Extend
	// Angle is the linear direction, or the conic start, in degrees on
	// CSS's compass: 0 up, 90 right, clockwise.
	Angle float64
	// CenterX and CenterY place a radial or conic center as fractions
	// of the box (0.5 is its middle).
	CenterX, CenterY float64
	// Circle makes a radial gradient's ending shape a circle instead
	// of an ellipse.
	Circle bool
	// Size picks the radial ending shape's size; RadiusX and RadiusY
	// are its explicit radii in logical pixels under RadiusExplicit (a
	// circle takes RadiusX).
	Size             RadialSize
	RadiusX, RadiusY float64
}

Gradient is one gradient fill: its geometry, its stops (sorted by position; positions may repeat for a hard stop), and its extend mode. The zero value is a padded linear gradient pointing up; build one with Linear, Radial or Conic.

func Conic

func Conic(from float64, stops ...GradientStop) Gradient

Conic is a centered conic gradient starting at from (CSS degrees).

func Linear

func Linear(angle float64, stops ...GradientStop) Gradient

Linear is a linear gradient at angle (CSS degrees).

func Radial

func Radial(stops ...GradientStop) Gradient

Radial is a centered farthest-corner ellipse.

func (Gradient) DeviceMap

func (g Gradient) DeviceMap(r Rect, radii Corners, num, denom int) (GradientMap, bool)

DeviceMap is g's mapping over the box r at device scale num/denom, as PaintGradient maps it; false when it is degenerate.

func (Gradient) LineLength

func (g Gradient) LineLength(r Rect) float32

LineLength is the length in logical pixels of g's gradient line over the box r — what a stop's length position is measured along: a linear gradient's corner-to-corner line, a radial one's ray (the ending shape's horizontal radius); a conic gradient has none.

func (Gradient) Repeating

func (g Gradient) Repeating() Gradient

Repeating returns g repeating its stop range (CSS repeating-*).

func (Gradient) TileMap

func (g Gradient) TileMap(t Tile, num, denom int) (GradientMap, bool)

TileMap is g's mapping over one tile of t at device scale num/denom: a box at the origin, sampled at a pixel's offset into its tile; false when it is degenerate.

type GradientKind

type GradientKind uint8

GradientKind is a gradient's geometry.

const (
	// GradientLinear runs along a line at an angle (CSS linear-gradient).
	GradientLinear GradientKind = iota
	// GradientRadial grows from a center out to an ellipse or circle
	// (CSS radial-gradient).
	GradientRadial
	// GradientConic sweeps around a center (CSS conic-gradient).
	GradientConic
)

type GradientMap

type GradientMap struct {
	Kind           GradientKind
	CX, CY         float32 // the center (radial, conic, linear's box middle)
	DX, DY, Length float32 // linear direction and line length
	RX, RY         float32 // radial radii
	From           float32 // conic start
	// InvLength, InvRX and InvRY are the reciprocals At multiplies by:
	// a GPU's division may round loosely, its multiplication may not,
	// so both renderers divide by multiplying with the same float32.
	InvLength, InvRX, InvRY float32
}

GradientMap maps device pixel centers to gradient positions for one box: a plain value, so the per-pixel loop allocates nothing. At is the mapping; a GPU renderer evaluates the same one.

func (GradientMap) At

func (m GradientMap) At(x, y float32) float32

At is the gradient position of the device point (px, py). It runs in float32 in the GPU shader's operation order, each product rounded on its own (no fused multiply-add), so the CPU and a GPU place hard stops and repeat boundaries on the same pixels: their float32 add, multiply and divide round alike, leaving only a GPU's looser sqrt and atan.

type GradientStop

type GradientStop struct {
	Pos   float64
	Color Color
}

GradientStop is one color stop of a gradient: Pos is the fraction of the gradient line (or ray, or turn), 0 at its start and 1 at its end.

type HyphensMode

type HyphensMode uint8

HyphensMode selects how WrapOptions treats soft hyphens.

const (
	HyphensOff HyphensMode = iota
	HyphensManual
	HyphensAuto
	// HyphensLegacy leaves soft hyphens untouched: the plain Wrap
	// path, which never read the CSS property and keeps shaping the
	// U+00AD glyph as before.
	HyphensLegacy
)

Hyphen modes: none hides U+00AD entirely, manual breaks at it (the hyphen renders where a break lands), auto also needs a dictionary the engine does not ship and reads as manual.

type Icon

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

Icon is a rasterized icon ready to blend onto a canvas. Its pixels are logical pixels unless AtScale says they were rasterized at a device scale.

func IconFromARGB32

func IconFromARGB32(width, height int, data []byte, w, h int) (*Icon, error)

IconFromARGB32 decodes a width x height raster of 32-bit ARGB pixels in network byte order (A, R, G, B per pixel, straight alpha, rows top to bottom with no padding) and scales it to w x h pixels. This is the StatusNotifierItem IconPixmap wire format (also the _NET_WM_ICON payload once byte-swapped to big-endian). data shorter than width*height*4 is an error, not a partial icon; trailing bytes past the raster are ignored.

func IconFromImage

func IconFromImage(src image.Image, w, h int) (*Icon, error)

IconFromImage scales any decoded image to w x h pixels, the same resampling LoadPNG applies. It is the entry point for pixels that did not come from a file: a decoded image the caller already holds, or a raster protocol payload converted to an image.

func LoadJPEG

func LoadJPEG(data []byte, w, h int) (*Icon, error)

LoadJPEG decodes JPEG icon data and scales it to w x h pixels.

func LoadPNG

func LoadPNG(data []byte, w, h int) (*Icon, error)

LoadPNG decodes PNG icon data and scales it to w x h pixels.

func LoadSVG

func LoadSVG(data []byte, w, h int) (*Icon, error)

LoadSVG rasterizes SVG icon data at w x h pixels. The icon's viewBox is scaled to fit inside that box with its aspect ratio kept and centered; the rest stays transparent. Unsupported SVG elements are an error, not silently dropped.

func (*Icon) At

func (i *Icon) At(x, y int) color.Color

At returns the pixel at (x, y) in icon coordinates.

func (*Icon) AtScale

func (i *Icon) AtScale(num, denom int) *Icon

AtScale returns the icon marked as rasterized at num device pixels per denom logical pixels (an icon drawn crisp on a 1.5x output is rasterized at 1.5 times its logical size). It shares the raster. A draw on a canvas of that scale blits the pixels one to one; at any other scale they resample into the logical box. It panics on a non-positive scale, which is a programming error.

func (*Icon) Draw

func (i *Icon) Draw(cv *Canvas, x, y int)

Draw blends the icon with its top-left corner at the logical point (x, y), covering its logical size: a raster made at the canvas's scale lands one to one at the mapped origin, any other one resamples into the logical box.

func (*Icon) DrawRotated

func (i *Icon) DrawRotated(cv *Canvas, x, y int, deg float64)

DrawRotated blends the icon turned deg degrees clockwise about its center, the center staying where the unrotated draw's center is, sampled as DrawXformed samples.

func (*Icon) DrawXformed

func (i *Icon) DrawXformed(cv *Canvas, x, y int, m Affine)

DrawXformed blends the icon through the affine m, applied about the icon's center (Xform): each destination pixel's center inverse-maps into the icon (Mapped) and samples it bilinearly, so turned edges antialias and a symmetric icon turns about its exact center; past its edges it is transparent. The identity draws straight (Draw), so a recorded opIcon is never the identity.

func (*Icon) Image

func (i *Icon) Image() *image.RGBA

Image is the icon's raster, premultiplied, shared by every draw: read-only.

func (*Icon) LogicalSize

func (i *Icon) LogicalSize() (int, int)

LogicalSize returns the size the icon covers in logical pixels: its pixel size, scaled down by the scale it was rasterized at. A raster made at the ceiling of a logical size times the scale maps back to that size.

func (*Icon) Size

func (i *Icon) Size() (int, int)

Size returns the rasterized icon size in pixels.

func (*Icon) Still

func (i *Icon) Still() StillImage

Still is the icon's raster as the still image its own draws use, of the icon's identity: a GPU renderer keeps one texture for both.

func (*Icon) Tint

func (i *Icon) Tint(tint Color) *Icon

Tint returns a copy of the icon recolored to tint: every pixel keeps its alpha (anti-aliasing, opacity) and takes tint's color, so the source works as a mask. This is how symbolic icons follow the theme accent. The limits are the mask approach's limits: ink comes out one flat color, gradient hue variation collapses to its alpha ramp, and multi-color art goes monochrome - which is the symbolic-icon contract. A translucent tint yields a translucent result.

func (*Icon) Xform

func (i *Icon) Xform(x, y int, m Affine, num, denom int) M3

Xform is the map DrawXformed draws the icon at (x, y) through m with: icon pixels scaled to its logical size, about the icon's center, through m (logical pixels), placed at the unturned draw's center and scaled to device pixels at num/denom.

type ImageID

type ImageID uint64

ImageID is a raster's identity, independent of the memory its pixels live in: NewImageID never hands out the same one twice in a process. A GPU renderer keys the texture or atlas slot it keeps for a raster by it, so memory freed and handed out again for other pixels, at the same address, rect and stride, gets a new ID and never matches the old texture. Zero is no identity.

func NewImageID

func NewImageID() ImageID

NewImageID is a fresh identity for a new raster.

type ImagePos

type ImagePos struct {
	X, Y       float64
	OffX, OffY int
}

ImagePos places an image's concrete object inside its box, CSS's object-position: per axis the object's origin sits at X (or Y) of the free space — the box less the object, negative where the object overflows — plus OffX (or OffY) pixels, in the units of the box.

type ImageScale

type ImageScale uint8

ImageScale picks how an image fills the box its widget was arranged into.

const (
	// ImageFit scales the image to the largest size that fits the box
	// with the aspect ratio kept (contain); the rest of the box stays
	// transparent. The default.
	ImageFit ImageScale = iota
	// ImageCover scales the image until it fills the box completely,
	// aspect ratio kept, cropping the overflow: the largest crop of the
	// source with the box's aspect ratio, centered unless an ImagePos
	// places it, resampled to the full box.
	ImageCover
	// ImageNone draws the image at its natural size, one source pixel
	// per device pixel, placed in the box (centered by default) and
	// clipped to it. Nothing
	// is resampled, so the pixels stay exactly as decoded - at a 2x
	// device scale an image covers half the logical size it would at
	// 1x.
	ImageNone
	// ImageStretch resamples the whole image to exactly the box,
	// ignoring the aspect ratio.
	ImageStretch
	// ImageScaleDown is ImageNone for an image that fits the box and
	// ImageFit for one that does not: never enlarged, only shrunk (aspect
	// kept) until it fits - GTK's ContentFit.SCALE_DOWN, with the natural
	// size measured in device pixels like ImageNone.
	ImageScaleDown
)

type Insets

type Insets struct {
	Top, Right, Bottom, Left int
}

Insets is a per-side length set in logical pixels, in CSS order.

func UniformInsets

func UniformInsets(v int) Insets

UniformInsets returns v on every side.

func (Insets) Grow

func (i Insets) Grow(r Rect) Rect

Grow pushes r out by the insets.

func (Insets) Max

func (i Insets) Max() int

Max is the widest of the four sides.

func (Insets) Shrink

func (i Insets) Shrink(r Rect) Rect

Shrink pulls r in by the insets, clamping at an empty rect.

func (Insets) Zero

func (i Insets) Zero() bool

Zero reports whether every side is zero.

type Layer

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

Layer is an offscreen buffer shaped like a canvas: the same device size and scale, so a widget subtree paints into it exactly as it would onto the canvas, to be drawn back transformed by Composite.

func LayerOf

func LayerOf(c *Canvas) *Layer

LayerOf is a layer whose pixels are c's own, for the layer operations (ApplyFilters, masks, CrossFade, DrawLayer) on pixels a player holds in a canvas of its own.

func (*Layer) ApplyMaskLayer

func (l *Layer) ApplyMaskLayer(mask *Layer, region Rect, luminance bool)

ApplyMaskLayer multiplies l's pixels inside region by the mask layer's pixels: the alpha channel for mask-mode alpha, the luminance (WCAG weights over the straight channels) for mask-mode luminance. The mask is positioned at its own coordinates.

func (*Layer) ApplyPathMask

func (l *Layer) ApplyPathMask(p *Path, region Rect)

ApplyPathMask multiplies l's pixels inside region by the path's coverage, scaled by the layer's device scale: the clip-path and the alpha mask both land here.

func (*Layer) Backing

func (l *Layer) Backing() any

Backing is what the player that last readied l keeps for it: a raster layer for Paint, a GPU image for a GPU player.

func (*Layer) Canvas

func (l *Layer) Canvas() *Canvas

Canvas is the layer's canvas to paint into.

func (*Layer) CrossFade

func (l *Layer) CrossFade(other *Layer, region Rect, t float64)

CrossFade blends other into l over region: each pixel becomes l·(1−t) + other·t, premultiplied channels alike - GSK's cross-fade, exact where drawing one over the other at partial opacity is not.

func (*Layer) Free

func (l *Layer) Free()

Free hands l's buffer back now, for a layer its owner is done with (a transition that landed): l must not be used after. Off the Go heap a dropped layer's buffer otherwise waits for a collection, which its own size no longer brings on. A layer over a canvas's pixels has none to free; a recorded layer drops its backing, a raster one freed with it.

func (*Layer) Release

func (l *Layer) Release()

Release returns a scratch layer to the pool; l must not be used after. A full pool keeps its largest buffers. Releasing a layer that did not come from ScratchLayer is a caller bug.

func (*Layer) SetBacking

func (l *Layer) SetBacking(b any)

SetBacking stores what stands for the recorded layer l.

type LineGeometry

type LineGeometry struct {
	AX, AY, DX, DY, InvLen2, Half float32
}

LineGeometry is Line's segment in device pixels, in the float32 a GPU shader evaluates it in: its start (the first point's pixel center), its direction to the second's, the reciprocal of its squared length (0 for a point) and its half width.

func LineOf

func LineOf(x0, y0, x1, y1, width, num, denom int) LineGeometry

LineOf is the segment Line strokes at device scale num/denom.

func (LineGeometry) Coverage

func (g LineGeometry) Coverage(x, y int) float32

Coverage is the stroke's coverage of pixel (x, y): its center's distance to the segment (round caps), each product rounded on its own, as the shader computes it.

type List

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

List is a frame recorded instead of rasterized: every drawing call a recording canvas (NewRecorder) and the layers made from it received, in order, with the clip, opacity and brightness in force. Play hands the calls to a Player: Paint rasterizes them onto a canvas exactly as painting directly would have, and a GPU renderer draws them on the GPU.

A List refers to what its calls were given (images, paths, filter lists, retained canvases) rather than copying it; it is played before they change, within the frame that recorded it.

func (*List) End

func (l *List) End()

End ends l's recording after its last Play, releasing the frees retired while it was open; neither recording into l nor playing it is allowed afterwards, short of ResetRecorder. A renderer whose canvas repaints rarely ends each frame's List once it is drawn, so it holds no free back while idle. Ending an ended List does nothing.

func (*List) Len

func (l *List) Len() int

Len is the number of recorded calls.

func (*List) Paint

func (l *List) Paint(dst *Canvas)

Paint rasterizes l onto dst, a raster canvas of the recording's size and scale: the pixels painting directly onto dst would have made.

func (*List) Play

func (l *List) Play(p Player)

Play hands l's calls to p in recorded order.

func (*List) Scale

func (l *List) Scale() (num, denom int)

Scale is the recording's device scale: num device pixels per denom logical pixels.

type M3

type M3 [9]float64

M3 is a 3x3 projective matrix acting on plane points: (x, y, 1) maps to (x', y', w') = M·(x, y, 1), then divides by w'. The zero value collapses everything to the origin; Identity3 fixes nothing.

func Affine3

func Affine3(m Affine) M3

Affine3 embeds an affine map into a projective one.

func (M3) Apply

func (m M3) Apply(x, y float64) (float64, float64)

Apply maps the point (x, y) with the perspective divide.

func (M3) Flat

func (m M3) Flat() bool

Flat reports a map whose third row leaves w untouched: the purely affine case, which composites without the divide.

func (M3) Invert

func (m M3) Invert() (M3, bool)

Invert returns the inverse map; false when m collapses the plane.

func (M3) MapBounds

func (m M3) MapBounds(r Rect) Rect

MapBounds is the smallest pixel rect covering r's image.

func (M3) Mul

func (m M3) Mul(n M3) M3

Mul is m∘n: n first, then m.

type Mapped

type Mapped struct {
	Inv [3][3]float32
	Fwd [3]float32
}

Mapped is a projective map from canvas device pixels to a source's, held and evaluated in float32 in a fixed operation order, each product rounded on its own: the CPU's layer composites and turned icons sample through it, and a GPU shader evaluates the same rows in the same order, so both land each pixel center on the same source point. Inv maps a pixel center into the source; Fwd is the forward map's last row, whose sign at the source point rejects points behind the viewer.

func MappedOf

func MappedOf(m M3) (Mapped, bool)

MappedOf is m (source to canvas) as a Mapped; false when m collapses the plane.

func (*Mapped) At

func (m *Mapped) At(x, y int) (float32, float32, bool)

At is the source point the center of canvas pixel (x, y) maps to; false behind the viewer.

type Mat4

type Mat4 [16]float64

Mat4 is a 4x4 transform over (x, y, z, 1) column vectors, the composition space of the 3-D functions.

func Perspective4

func Perspective4(d float64) Mat4

Perspective4 is CSS perspective()'s matrix: the viewer at distance d on the z axis, w shrinking as z approaches it.

func PlaneRotZ

func PlaneRotZ(a Affine) Mat4

PlaneRotZ embeds a screen rotation (about z) into 4x4 space.

func RotateX4

func RotateX4(deg float64) Mat4

RotateX4 rotates about the x axis by deg degrees.

func RotateY4

func RotateY4(deg float64) Mat4

RotateY4 rotates about the y axis by deg degrees.

func TranslateZ4

func TranslateZ4(t float64) Mat4

TranslateZ4 moves t along z.

func (Mat4) Mul

func (m Mat4) Mul(n Mat4) Mat4

Mul is m∘n: n first, then m.

func (Mat4) Plane3

func (m Mat4) Plane3() M3

Plane3 induces m's action on the z=0 plane as a homography: the first two rows' x and y columns with the translation column, and the last row's x, y and w columns as the divide.

type MatrixStep

type MatrixStep struct {
	Identity, Linear bool
	K                [9]int32
	M                [20]float32
}

MatrixStep is one color function of a filter list as both renderers apply it. A Linear step only mixes the color channels, so it runs on the premultiplied pixels in 16.16 fixed point, K row by row, each channel clamped to its pixel's alpha; any other runs the float32 matrix M (4 rows of 4 channel weights and an offset) on the straight color and re-premultiplies. An Identity step changes nothing.

type Path

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

Path is an outline in logical pixels for FillPath: straight and cubic Bézier segments in subpaths, each closed when filled (cairo's move_to / line_to / curve_to / close_path).

func ParsePathData

func ParsePathData(d string) (*Path, bool)

ParsePathData parses an SVG path data string (CSS path()'s argument) into a Path of move, line and cubic segments in the string's own coordinate space — the caller offsets it onto the box. Every command of the d grammar is handled; arcs subdivide into cubics (four spans per quarter turn, within a quarter pixel of the true arc). false for malformed data.

func (*Path) Close

func (p *Path) Close()

Close closes the current subpath back to its start.

func (*Path) Contains

func (p *Path) Contains(x, y float64) bool

Contains reports whether the point (x, y), in logical pixels, lies inside the path under the nonzero winding rule FillPath fills by, every subpath closed. It allocates nothing.

func (*Path) CubeTo

func (p *Path) CubeTo(x1, y1, x2, y2, x, y float64)

CubeTo adds a cubic Bézier to (x, y) through the control points (x1, y1) and (x2, y2).

func (*Path) Empty

func (p *Path) Empty() bool

Empty reports a path with no segments.

func (*Path) LineTo

func (p *Path) LineTo(x, y float64)

LineTo adds a straight segment to (x, y).

func (*Path) MoveTo

func (p *Path) MoveTo(x, y float64)

MoveTo starts a subpath at (x, y).

func (*Path) Offset

func (p *Path) Offset(dx, dy float64) *Path

Offset returns p translated by (dx, dy).

func (*Path) RoundedRect

func (p *Path) RoundedRect(num, denom int) (Rect, Corners, bool)

RoundedRect is the rounded rect p is when RoundedRectPath alone made it and it lands on whole device pixels at num/denom with radii that need no clamping, the cases where a distance field paints the outline's shape: a renderer then fills or masks it without rasterizing.

type PathScratch

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

PathScratch is what rasterizing a path works in, reused from call to call: it allocates only to grow.

func (*PathScratch) PathMask

func (sc *PathScratch) PathMask(p *Path, region Rect, num, denom int) (*image.Alpha, Rect)

PathMask is the path's coverage at device scale num/denom over box, the part of region its bounds reach (nil when they miss it), valid until the next call; the rest of region is uncovered. It is for a path too large for PathCoverageMask.

type Player

type Player interface {
	ClearDevice(s State, r Rect, col Color)
	FillRectDevice(s State, r Rect, col Color)
	DrawCanvasDevice(s State, src *Canvas, x, y int)
	DrawLayerAt(s State, src *Layer, x, y int)
	RoundedRect(s State, r Rect, radius int, col Color)
	Line(s State, x0, y0, x1, y1, width int, col Color)
	Shadow(s State, r Rect, cornerRadius, blur int, col Color)
	DrawImage(s State, img image.Image, x, y int)
	DrawImageCover(s State, img image.Image, r Rect, radii Corners)
	DrawImageDevice(s State, img image.Image, x, y int)
	DrawImageRect(s State, img image.Image, r Rect)
	DrawIcon(s State, ic *Icon, x, y int, m Affine)
	Arc(s State, cx, cy, radius, width, start, sweep float64, col Color)
	BoxShadow(s State, r Rect, radii Corners, sh BoxShadow)
	PaintGrain(s State, r Rect, radii Corners, opacity float64, ox, oy int)
	RoundedBorderSides(s State, r Rect, radii Corners, widths Insets, cols [4]Color)
	RoundedRectCorners(s State, r Rect, radii Corners, col Color)
	PaintGradient(s State, r Rect, radii Corners, g Gradient)
	PaintGradientTiles(s State, g Gradient, t Tile, clip Rect, radii Corners)
	PaintImageTiles(s State, img image.Image, t Tile, clip Rect, radii Corners)
	FillPath(s State, p *Path, col Color)
	// Glyph's mask is its coverage for the pen, resolved at recording; nil
	// for a glyph drawn in color or from a bitmap.
	Glyph(s State, face *Typeface, gid font.GID, scale, penX, penY float64, col Color, mask *GlyphMask)
	// Layer readies l, the size and scale of the canvas s names, with
	// region transparent; ScratchLayer is Layer for a layer Release
	// ends.
	Layer(s State, l *Layer, region Rect)
	ScratchLayer(s State, l *Layer, region Rect)
	// Snapshot copies the region of the canvas s names into l.
	Snapshot(s State, l *Layer, region Rect)
	Release(l *Layer)
	Composite(s State, l *Layer, src Rect, m Affine, alpha float64)
	CompositeProjective(s State, l *Layer, src Rect, m M3, alpha float64)
	DrawLayer(s State, l *Layer, src Rect, mode BlendMode)
	CrossFade(l, other *Layer, region Rect, t float64)
	ApplyMaskLayer(l, mask *Layer, region Rect, luminance bool)
	ApplyPathMask(l *Layer, p *Path, region Rect)
	ApplyFilters(l *Layer, region Rect, f *Filters, shape FilterShape)
}

Player receives a List's calls, each a Canvas (or Layer) method's arguments after the state it ran under. Layers are the recorded ones; a player keeps what stands for each (a raster buffer, a GPU image) with SetBacking, so a layer kept across frames keeps it.

type RadialSize

type RadialSize uint8

RadialSize is a radial gradient's ending-shape size, the CSS keywords plus explicit radii.

const (
	// FarthestCorner reaches the farthest corner (the CSS default).
	FarthestCorner RadialSize = iota
	// ClosestSide touches the nearest side.
	ClosestSide
	// ClosestCorner reaches the nearest corner.
	ClosestCorner
	// FarthestSide touches the farthest side.
	FarthestSide
	// RadiusExplicit uses Gradient.RadiusX and RadiusY.
	RadiusExplicit
)

type Rect

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

Rect is an axis-aligned rectangle in buffer pixel coordinates. A Rect with a non-positive width or height is empty and covers no pixels.

func MapRect

func MapRect(r Rect, num, denom int) Rect

MapRect maps the logical rect r into device pixels at scale num/denom, rounding the origin down and the far edge up so the device rect fully covers everything r spans. Package-level so the frame pipeline can map damage without a canvas instance.

func PlaceImage

func PlaceImage(srcW, srcH, boxW, boxH int, s ImageScale, pos ImagePos) (src image.Rectangle, dst Rect)

PlaceImage resolves a scaling policy for a srcW x srcH image into a boxW x boxH box, the object placed by pos. Both sizes are in the same units - widget.Image feeds device pixels so the result stays crisp at fractional scales. It returns the source rectangle to sample and the destination rect, relative to the box, to resample it into: the part of the placed object the box shows. An empty result means a zero-sized input or an object placed wholly outside the box.

func RoundedRectRegion

func RoundedRectRegion(r Rect, radii Corners) []Rect

RoundedRectRegion decomposes the rounded rect r into the rects a rectangle-only region (a wl_region) can carry: per pixel row, the pixels whose centers lie inside the shape, with consecutive rows of the same span merged. Radii that overlap scale down together, per CSS. A plain rect is one rect.

func UnionAll

func UnionAll(rects []Rect) Rect

UnionAll returns the bounding box of all rects. Nil and empty inputs yield an empty Rect.

func (Rect) Contains

func (r Rect) Contains(x, y int) bool

Contains reports whether the pixel (x, y) lies inside r. Empty rects contain nothing.

func (Rect) Empty

func (r Rect) Empty() bool

Empty reports whether r covers no pixels.

func (Rect) Intersect

func (r Rect) Intersect(o Rect) Rect

Intersect returns the overlap of r and o. Disjoint or empty inputs yield an empty Rect.

func (Rect) Subtract

func (r Rect) Subtract(o Rect) []Rect

Subtract returns r with o cut out, as up to four non-overlapping rects that tile the remainder exactly. Order is unspecified. A non-intersecting or empty o yields [r]; an o that covers r yields nil.

func (Rect) Union

func (r Rect) Union(o Rect) Rect

Union returns the bounding box of r and o. Empty rectangles drop out, so the Union of two empty rects is empty.

type RefractPlan

type RefractPlan struct {
	Box, Radii     [4]float32
	InvBezel, Disp float32
}

RefractPlan is -lys-refract() over a shape at device scale, in the arithmetic both renderers share: the shape's border box and corner radii in float32 device pixels, the bezel's reciprocal and the displacement at the rim. Every step of At is exact in float32, but for the one per-pixel division, which runs in integers.

func RefractPlanOf

func RefractPlanOf(shape FilterShape, bezel, disp float64, num, denom int) (RefractPlan, bool)

RefractPlanOf is the plan for a bezel and displacement in device pixels over shape at device scale num/denom; false when nothing bends.

func (RefractPlan) At

func (p RefractPlan) At(x, y int) (dx, dy int32, ok bool)

At is how far device pixel (x, y) samples off itself, in 1/256 pixels, and whether it bends at all: inside the shape, within the bezel of the edge, it looks outward along the edge normal, by Disp at the edge falling off quadratically to none at the bezel's inner side - the rim of a lens, which shows what lies just beyond it.

type ShadowMask

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

ShadowMask is a box-shadow's coverage field over its core box's span, whose top-left sits at (x0, y0) from the box's, immutable once made: a GPU renderer keys its atlas by its ID.

func (*ShadowMask) Origin

func (r *ShadowMask) Origin() (x0, y0 int)

Origin is the mask's top-left from its core box's.

func (*ShadowMask) Pix

func (r *ShadowMask) Pix() []uint8

Pix is the field's coverage, Size's width bytes per row.

func (*ShadowMask) Size

func (r *ShadowMask) Size() (w, h int)

Size is the field's size in device pixels.

type ShadowPlan

type ShadowPlan struct {
	Margin, DX, DY int
	Boxes          [3]int
	Tint           Color
}

ShadowPlan is how a drop-shadow runs, in device pixels: the region's alpha silhouette is laid into a buffer (Size) at (Margin, Margin) and blurred by box passes of Boxes' radii (a pass of radius 0 is skipped); each region pixel then reads the buffer at (Margin-DX, Margin-DY) from its own place, scales the premultiplied Tint by that alpha (each channel tint*a/255, floored) and goes over the result.

func ShadowPlanOf

func ShadowPlanOf(s DropShadow, scale float64) ShadowPlan

ShadowPlanOf is the plan for s at device scale (device pixels per CSS pixel, scale).

func (ShadowPlan) Size

func (p ShadowPlan) Size(region Rect) (w, h int)

Size is the silhouette buffer's size for region: the margin on every side and twice the offset across.

type ShapedText

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

ShapedText is one line of text shaped at a fixed pixel size: a sequence of runs, each shaped with its own face and embedding direction, sharing one baseline, laid out in visual left-to-right order (the directional runs internal/text resolves). Glyph positions are relative to the line origin. A single face and direction produce a single run; fallback chains produce one run per face change.

ShapedText is immutable once built - the process-wide shaping cache shares one instance between every caller that shapes the same (font, size, string) - so readers may hold and consult it freely but never write it.

func (*ShapedText) Advance

func (s *ShapedText) Advance() float64

Advance returns the line width in pixels: the sum over the runs.

func (*ShapedText) AppendCaretBands

func (s *ShapedText) AppendCaretBands(buf [][2]float64, start, end int) [][2]float64

AppendCaretBands appends the x spans covering the selected rune range [start, end) to buf and returns it: one span per visual run the range touches, left to right, so a selection across mixed-direction text highlights disjoint spans instead of spanning the middle. Spans are line-relative; callers offset them. The buffer is the caller's, kept across frames, so the render path stays allocation-free in the steady state.

func (*ShapedText) Ascent

func (s *ShapedText) Ascent() float64

Ascent returns the line's ascent above the baseline in pixels: the maximum over the runs, so a taller fallback face grows the line.

func (*ShapedText) CaretAt

func (s *ShapedText) CaretAt(x float64) int

CaretAt returns the rune boundary nearest x: the inverse of CaretX for hit-testing clicks in a text field, direction-agnostic because the table already follows the line visually.

func (*ShapedText) CaretPositions

func (s *ShapedText) CaretPositions() []float64

CaretPositions returns the caret x for every rune boundary 0..n at once - the table CaretX indexes, shared with every other reader of this line: read it, never modify it. Callers composing several runs into one line (rich labels) offset each run's table by its line x.

func (*ShapedText) CaretX

func (s *ShapedText) CaretX(caret int) float64

CaretX returns the x offset of the caret placed before rune index caret, clamped to [0, rune count]. The x follows the line visually: before an RTL run's first rune it sits at that run's right edge.

func (*ShapedText) Descent

func (s *ShapedText) Descent() float64

Descent returns the line's descent below the baseline in pixels (positive): the maximum over the runs.

func (*ShapedText) Draw

func (s *ShapedText) Draw(cv *Canvas, x, baselineY int, col Color)

Draw paints the line with its baseline at logical (x, baselineY), clipped to the canvas like every other primitive. Each run draws with its own face; every run was shaped at the logical pixel size and rasterizes at the canvas's device scale, so text stays crisp at any factor no matter which face supplied the glyph.

func (*ShapedText) DrawDecoration

func (s *ShapedText) DrawDecoration(cv *Canvas, x, baseline int, d Decoration, col Color)

DrawDecoration draws d along the line s, drawn with its pen at x and baseline: each line spans the shaped advance - the line's visual extent, whatever its runs' directions - at the font's own underline, strikethrough, and ascent metrics (post and OS/2, variable-font deltas included), in d.Color or else col. Every text widget and a rich label's runs paint decorations through it.

func (*ShapedText) DrawJustified

func (s *ShapedText) DrawJustified(cv *Canvas, x, baselineY int, col Color, gap float64)

DrawJustified paints the line like Draw with gap pixels added after every word separator: the justify distribution's per-space share, which the caller computed from the row's leftover width. Rows without separators draw exactly like Draw.

func (*ShapedText) InkOverhang

func (s *ShapedText) InkOverhang() (reach Insets, ok bool)

InkOverhang is how far the text's glyph outlines reach past its line box, which is Advance wide and Ascent over Descent tall from the pen's start on the baseline: pixels at 1x, rounded out, with one more for antialiasing. ok is false when a glyph's extents are unknown, and the caller must assume any reach.

func (*ShapedText) LineHeight

func (s *ShapedText) LineHeight() int

LineHeight returns the rounded line height: the smallest integer box height that fits the line's ascent and descent. Measure and drawing guards must both use this so a label's natural height is never smaller than the height its own painter requires.

func (*ShapedText) NotDefCount

func (s *ShapedText) NotDefCount() int

NotDefCount returns how many shaped glyphs are the .notdef box (glyph 0), i.e. runes no face in the chain could render. Fallback chains aim for zero on scripts the system covers.

func (*ShapedText) RTL

func (s *ShapedText) RTL() bool

RTL reports whether the line lays out right to left: the resolved base direction it was shaped under.

func (*ShapedText) Runs

func (s *ShapedText) Runs() int

Runs returns how many faces the line was shaped across. A single typeface always returns 1.

func (*ShapedText) SeparatorCount

func (s *ShapedText) SeparatorCount() int

SeparatorCount reports how many word separators the line holds: the justify distribution divides the leftover width across them.

func (*ShapedText) Text

func (s *ShapedText) Text() string

Text returns the string the run was shaped from.

type State

type State struct {
	Layer         *Layer
	Clip          Rect
	Bounds        Rect
	Alpha, Bright float64
}

State is the canvas state a recorded call ran under. Layer is the recorded layer whose canvas the call drew on, nil for the frame's canvas. Bounds is the device rect the call can touch, within Clip; for a layer's lifecycle or an in-place layer call, its region.

type StillImage

type StillImage struct {
	*image.RGBA
	ID ImageID
}

StillImage is an *image.RGBA its owner never changes once wrapped: a decoded picture, a cached raster, an icon. A GPU renderer uploads it once and keeps the texture while it is drawn; a VersionedImage it uploads again when its version moves, and any other image it draws from its visible pixels each time. Its sub-images are still too.

ID is the raster's identity (NewStillImage), shared by its sub-images and kept by its owner with the raster. A still image without one is identified by its pixels' address, which is sound only for pixels the Go heap owns: the renderer's key keeps them reachable, so the address cannot carry other pixels while the texture lives. Pixels freed deterministically (off the heap, back to a pool) need an ID, and their owner frees them through Retire.

func NewStillImage

func NewStillImage(rgba *image.RGBA) StillImage

NewStillImage wraps rgba, which its owner never changes again, as a still image with a fresh identity. The owner keeps the result and draws it, rather than wrapping the raster anew for every draw.

func Still

func Still(img image.Image) StillImage

Still is img's pixels as they are now as a still image: img itself when it is one, otherwise a copy with a fresh identity, so changes to img never reach it.

func (StillImage) SubImage

func (s StillImage) SubImage(r image.Rectangle) image.Image

SubImage is the still image's part within r, of the same identity.

type Tile

type Tile struct {
	X, Y, W, H       float64
	GapX, GapY       float64
	RepeatX, RepeatY bool
}

Tile is one image layer's tiling (the CSS background and mask painting model): the rect of the tile at the layer's position in logical pixels, the gap between neighboring tiles along each axis, and whether the tiles repeat there. A non-repeating axis paints the one tile.

type TileGeometry

type TileGeometry struct {
	Box, Radii                               [4]float32
	X0, Y0, W, H                             float32
	PeriodX, PeriodY, InvPeriodX, InvPeriodY float32
	RepeatX, RepeatY                         bool
}

TileGeometry is a tiling laid out in device pixels, in the float32 a GPU shader evaluates it in: the clip's box and corner radii, and per axis the positioned tile's start and size, the repeat period (tile and gap) with its reciprocal, and whether the axis repeats.

func TileGeometryOf

func TileGeometryOf(t Tile, clip Rect, radii Corners, num, denom int) (TileGeometry, bool)

TileGeometryOf lays t out over clip's rounded outline (radii in logical pixels) at device scale num/denom; false for an empty tile.

func (TileGeometry) At

func (g TileGeometry) At(px, py float32) (u, v float32, ok bool)

At is the offset (u, v) of device pixel center (px, py) within the tile it falls in, and whether one covers it: false in a gap between repeated tiles, or outside the lone tile of a non-repeating axis.

type Typeface

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

Typeface is a loaded font plus the machinery to shape and rasterize it. One instance per font family; it is not safe for concurrent use.

func LoadFont

func LoadFont(data []byte) (*Typeface, error)

LoadFont parses font data (TTF or OTF), which must stay valid and unchanged for as long as the typeface is used: its tables are read in place.

func NewFixtureHebrewTypeface

func NewFixtureHebrewTypeface() (*Typeface, error)

NewFixtureHebrewTypeface parses the bundled Hebrew fixture into a fresh Typeface, one per caller like NewFixtureTypeface.

func NewFixtureTypeface

func NewFixtureTypeface() (*Typeface, error)

NewFixtureTypeface parses the bundled fixture font into a fresh Typeface. One per caller: a Typeface is stateful and not safe for concurrent use, so tests never share one.

func NewTypeface

func NewTypeface(face *font.Face) (*Typeface, error)

NewTypeface wraps an already-resolved face, as returned by a font matcher.

func (*Typeface) Covers

func (t *Typeface) Covers(r rune) bool

Covers reports whether the face has a glyph for r. Fallback chains consult it per rune to decide where a glyph comes from.

func (*Typeface) Describe

func (t *Typeface) Describe() font.Description

Describe returns the face's font description: family, style, weight, and stretch. Callers compare it to pin which variant a request resolved to.

func (*Typeface) Draw

func (t *Typeface) Draw(cv *Canvas, s *ShapedText, x, baselineY int, col Color)

Draw paints a shaped line; see ShapedText.Draw.

func (*Typeface) DrawAligned

func (t *Typeface) DrawAligned(cv *Canvas, s string, box Rect, px float64, col Color, h Alignment) *ShapedText

DrawAligned draws text inside box with the given alignment, skipping it entirely when the box cannot hold one line of the font. The guard uses the same rounded LineHeight the measurement reports.

func (*Typeface) DrawAlignedDir

func (t *Typeface) DrawAlignedDir(cv *Canvas, s string, box Rect, px float64, col Color, h Alignment, d text.Direction) *ShapedText

DrawAlignedDir draws text inside box under base direction d; start and end mirror for a right-to-left base. See text.Direction.

func (*Typeface) Ellipsize

func (t *Typeface) Ellipsize(text string, maxWidth, px float64) string

Ellipsize shortens text to fit maxWidth, replacing the cut remainder with an ellipsis. Text that already fits is returned unchanged. For the other cut points use EllipsizeText.

func (*Typeface) Family

func (t *Typeface) Family() string

Family returns the resolved face's family name.

func (*Typeface) HasAxis

func (t *Typeface) HasAxis(tag string) bool

HasAxis reports whether the face is variable along tag: setting the axis to its two extremes yields different coordinates.

func (*Typeface) IsMonospace

func (t *Typeface) IsMonospace() bool

IsMonospace reports whether the face's glyphs are fixed-width (its post table's flag), what a monospace filter asks.

func (*Typeface) Metrics

func (t *Typeface) Metrics() FaceMetrics

Metrics returns the face's metrics, memoized after the first call.

func (*Typeface) Oblique

func (t *Typeface) Oblique() *Typeface

Oblique returns the face slanted as a synthetic italic, for a family that has no italic face of its own: the same glyphs and advances, the outlines sheared. Memoized, a distinct face to every cache.

func (*Typeface) Shape

func (t *Typeface) Shape(s string, px float64) *ShapedText

Shape lays text out at the given pixel size, resolving the base direction from the text's first strong character. Results are served from the process-wide shaping cache: the second Shape of the same (face, size, string) is a map hit returning the identical ShapedText, so per-frame re-shapes - Entry's selection band, text, and caret, or a per-event click mapping - cost a lookup.

func (*Typeface) ShapeDir

func (t *Typeface) ShapeDir(s string, px float64, d text.Direction) *ShapedText

ShapeDir lays text out under base direction d; see Shape and text.Direction.

func (*Typeface) ShapeDirRunes

func (t *Typeface) ShapeDirRunes(rs []rune, px float64, d text.Direction) *ShapedText

ShapeDirRunes shapes a rune slice under d; see Font.ShapeDirRunes.

func (*Typeface) ShapeRune

func (t *Typeface) ShapeRune(r rune, px float64) *ShapedText

ShapeRune shapes one rune; see Font.ShapeRune. Identical result to Shape(string(r)) - the fill goes through the same uncached path - but the cache keys on the rune, so per-rune probes (wrap measurement walks one rune at a time) stay allocation-free in the steady state.

func (*Typeface) ShapeRunes

func (t *Typeface) ShapeRunes(rs []rune, px float64) *ShapedText

ShapeRunes shapes a rune slice; see Font.ShapeRunes.

func (*Typeface) Slanted

func (t *Typeface) Slanted() bool

Slanted reports whether the face is a synthetic oblique.

func (*Typeface) Spaced

func (t *Typeface) Spaced(px float64) *Typeface

Spaced returns the face shaping with px of letter spacing after every cluster (CSS letter-spacing): the advances themselves carry it, so measuring, caret placement, and painting agree. Memoized; zero returns the face itself.

func (*Typeface) Tabular

func (t *Typeface) Tabular() *Typeface

Tabular returns the face shaping with the tnum OpenType feature on: digits on a uniform advance grid, what a clock or a numeric column wants. Memoized; the twin shares nothing the lazy caches fill, so the two entries never contend.

func (*Typeface) Variations

func (t *Typeface) Variations() []Variation

Variations reports the settings this face was instantiated at; nil for a face at its default instance.

func (*Typeface) Weighted

func (t *Typeface) Weighted(w int) *Typeface

Weighted is the face at CSS weight w along its wght axis - a variable family's real weight rather than its default instance; a face without the axis returns itself.

func (*Typeface) WithFeatureSpec

func (t *Typeface) WithFeatureSpec(spec string) *Typeface

WithFeatureSpec returns the face shaping with the OpenType features in spec on: the canonical `tag=value` list, semicolon separated, the form font-feature-settings and the font-variant properties compute to. Tags the face lacks are ignored by the shaper. Memoized, so the shaping cache keeps hitting; the empty spec returns the face itself.

func (*Typeface) WithVariations

func (t *Typeface) WithVariations(vs ...Variation) *Typeface

WithVariations returns the face instantiated at vs (CSS font-variation-settings, a named instance's coordinates): axes the font lacks are ignored, values clamp to each axis's range, and unnamed axes keep their defaults - settings apply over the default instance, not over t's own. A face with none of the axes, or empty vs, returns the default face. Instances are memoized per setting.

func (*Typeface) WordSpaced

func (t *Typeface) WordSpaced(px float64) *Typeface

WordSpaced returns the face shaping with px of word spacing added after every word separator (CSS word-spacing): like letter spacing, the advances themselves carry it, so measuring, wrapping, and painting agree. Memoized; zero returns the face itself.

func (*Typeface) Wrap

func (t *Typeface) Wrap(text string, maxWidth, px float64) []string

Wrap breaks text into lines of at most maxWidth pixels, filling greedily along Unicode UAX #14 break opportunities: each line takes as much as fits before the first opportunity that overflows. Breaks land where real typesetting puts them - at spaces, after hyphens, inside CJK runs - not only at ASCII spaces. A run with no break opportunity before the width, an unbreakable token, stays whole on its own line and overflows. Hard newlines split unconditionally; trailing spaces at a break and leading spaces of a continuation are dropped.

type Variation

type Variation struct {
	Tag   string
	Value float32
}

Variation is one setting of a variable font's design axis: an OpenType axis tag ("wght", "wdth", "slnt", "ital", "opsz", or a font's own) and a value in that axis's design units (wght 100-900).

func ParseVariations

func ParseVariations(s string) ([]Variation, error)

ParseVariations parses a CSS font-variation-settings value - "normal", or comma-separated quoted four-letter tags and numbers ("wght" 650, "wdth" 80).

type VersionedImage

type VersionedImage struct {
	// Dirty, when not empty, is all that changed since version DirtySince,
	// in the raster's coordinates: a device holding that version uploads
	// only it.
	Dirty      image.Rectangle
	DirtySince uint64
	*image.RGBA
	ID      ImageID
	Version uint64
}

VersionedImage is an *image.RGBA whose owner changes its pixels and bumps Version with every change: a video frame resampled into the same raster. A GPU renderer keeps its texture and uploads the pixels again only when the version moves. Its sub-images carry the version and the identity.

ID is the raster's identity, allocated once with NewImageID and kept with the raster; without one the raster is identified by its pixels' address, as a StillImage without one is.

func (VersionedImage) SubImage

func (v VersionedImage) SubImage(r image.Rectangle) image.Image

SubImage is the image's part within r, at the same version.

type WrapOptions

type WrapOptions struct {
	Break          WrapWordMode
	Hyphens        HyphensMode
	Anywhere       bool
	PreserveSpaces bool
	// BreakSpaces is white-space: break-spaces: preserved spaces take
	// their advance at a row's end instead of hanging past it, and a
	// row may break after any one of them.
	BreakSpaces bool
	// BreakWords is overflow-wrap break-word and anywhere: a word that
	// overflows a row on its own breaks between grapheme clusters.
	BreakWords bool
	// Indent narrows the text's first row by that many pixels
	// (text-indent).
	Indent float64
}

WrapOptions selects how WrapTextOpts breaks lines beyond the default UAX #14 fill: word-break, hyphens, line-break anywhere, and the white-space family's space preservation. The zero value is the plain WrapText behavior.

type WrapWordMode

type WrapWordMode uint8

WrapWordMode selects word-break.

const (
	WrapWordNormal WrapWordMode = iota
	WrapWordBreakAll
	WrapWordKeepAll
)

Word-break modes.

Jump to

Keyboard shortcuts

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