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
- Variables
- func AlignedPen(sh *ShapedText, box Rect, h Alignment, d text.Direction) (x, baseline int)
- func ApplyFilters(l *Layer, region Rect, f *Filters, shape FilterShape)
- func BorderRing(r Rect, radii Corners, widths Insets, num, denom int) (outer, oradii, inner, iradii, w [4]float32)
- func BoxDivisor(n int) (half, recip uint32)
- func BoxShadowMask(r Rect, radii Corners, s BoxShadow, num, denom int) (m *ShadowMask, box Rect, coreW, coreH int)
- func CollapseWhiteSpace(s string, newlines bool) string
- func DecodeImage(data []byte) (image.Image, error)
- func DeviceBox(r Rect, radii Corners, num, denom int) (box, rc [4]float32)
- func EllipsePath(p *Path, cx, cy, rx, ry float64)
- func EllipsizeText(f Font, text string, mode EllipsizeMode, maxWidth, px float64) string
- func FixtureFontData() []byte
- func FixtureHebrewFontData() []byte
- func GlyphCoverage(face *Typeface, gid font.GID, scale, penX, penY float64, col Color) (*GlyphMask, Rect, bool)
- func GrainStrength(opacity float64) uint32
- func NRGBA(data []byte, stride, width, height int) *image.NRGBA
- func PathCoverage(p *Path, box Rect, scale float32) *image.Alpha
- func Reciprocal[F float32 | float64](v F) F
- func RectShadow(r Rect, cornerRadius, blur, num, denom int) (CoverageMask, Rect, bool)
- func Resample(src image.Image, srcRect image.Rectangle, dstW, dstH int) *image.RGBA
- func ResampleInto(dst, src *image.RGBA, srcRect image.Rectangle)
- func RoundedRadius(full Rect, radius, num, denom int) float32
- func RoundedRectPath(p *Path, r Rect, radii Corners)
- func SideReciprocals(w [4]float32) [4]float32
- func Stride(widthPx int) int
- func TexelScale(n int, size float32) float32
- func WordSep(r rune) bool
- func WrapText(f Font, text string, maxWidth, px float64) []string
- func WrapTextOpts(f Font, s string, maxWidth, px float64, o WrapOptions) []string
- type Affine
- type Alignment
- type Animation
- type ArcGeometry
- type BlendMode
- type BlurPlan
- type BoxShadow
- type Canvas
- func (c *Canvas) ApplyState(s State)
- func (c *Canvas) Arc(cx, cy, radius, width, start, sweep float64, col Color)
- func (c *Canvas) BeginOverlays()
- func (c *Canvas) BorderRect(r Rect, width int, col Color)
- func (c *Canvas) BoxShadow(r Rect, radii Corners, s BoxShadow)
- func (c *Canvas) Clear(r Rect, col Color)
- func (c *Canvas) ClearDevice(r Rect, col Color)
- func (c *Canvas) Composite(l *Layer, src Rect, m Affine, alpha float64)
- func (c *Canvas) CompositeProjective(l *Layer, src Rect, m M3, alpha float64)
- func (c *Canvas) DeviceScale() (num, denom int)
- func (c *Canvas) DrawCanvasDevice(src *Canvas, x, y int)
- func (c *Canvas) DrawGlyph(face *Typeface, gid font.GID, scale, penX, penY float64, col Color)
- func (c *Canvas) DrawImage(img image.Image, x, y int)
- func (c *Canvas) DrawImageCover(img image.Image, r Rect, radii Corners)
- func (c *Canvas) DrawImageCoverImage(ic *Icon, r Rect, radii Corners)
- func (c *Canvas) DrawImageDevice(img image.Image, x, y int)
- func (c *Canvas) DrawImageRect(img image.Image, r Rect)
- func (c *Canvas) DrawLayer(l *Layer, src Rect, mode BlendMode)
- func (c *Canvas) FillPath(p *Path, col Color)
- func (c *Canvas) FillRect(r Rect, col Color)
- func (c *Canvas) FillRectDevice(r Rect, col Color)
- func (c *Canvas) FinishFocus()
- func (c *Canvas) FlushOverlays()
- func (c *Canvas) Layer(old *Layer, region Rect) *Layer
- func (c *Canvas) Line(x0, y0, x1, y1, width int, col Color)
- func (c *Canvas) MapRect(r Rect) Rect
- func (c *Canvas) MarkFocus(key any, paint func(*Canvas))
- func (c *Canvas) Overlay(paint func(*Canvas))
- func (c *Canvas) PaintGradient(r Rect, radii Corners, g Gradient)
- func (c *Canvas) PaintGradientTiles(g Gradient, t Tile, clip Rect, radii Corners)
- func (c *Canvas) PaintGrain(r Rect, radii Corners, opacity float64, ox, oy int)
- func (c *Canvas) PaintImageTiles(img image.Image, t Tile, clip Rect, radii Corners)
- func (c *Canvas) Painted(w any)
- func (c *Canvas) PopAlpha(prev float64)
- func (c *Canvas) PopBrightness(prev float64)
- func (c *Canvas) PopClip(prev Rect)
- func (c *Canvas) PushAlpha(a float64) float64
- func (c *Canvas) PushBrightness(f float64) float64
- func (c *Canvas) PushClip(r Rect) Rect
- func (c *Canvas) PushClipDevice(r Rect) Rect
- func (c *Canvas) Recording() *List
- func (c *Canvas) Rect() Rect
- func (c *Canvas) Reset(data []byte, stride, width, height, num, denom int) *Canvas
- func (c *Canvas) ResetRecorder(width, height, num, denom int) *Canvas
- func (c *Canvas) ResetTouched() int
- func (c *Canvas) RoundedBorder(r Rect, radii Corners, widths Insets, col Color)
- func (c *Canvas) RoundedBorderSides(r Rect, radii Corners, widths Insets, cols [4]Color)
- func (c *Canvas) RoundedRect(r Rect, radius int, col Color)
- func (c *Canvas) RoundedRectCorners(r Rect, radii Corners, col Color)
- func (c *Canvas) ScratchLayer(region Rect) *Layer
- func (c *Canvas) ScratchSnapshot(region Rect) *Layer
- func (c *Canvas) Shadow(r Rect, cornerRadius, blur int, col Color)
- func (c *Canvas) Snapshot(old *Layer, region Rect) *Layer
- func (c *Canvas) Touched() int
- type Chain
- func (c *Chain) Draw(cv *Canvas, s *ShapedText, x, baselineY int, col Color)
- func (c *Chain) DrawAligned(cv *Canvas, s string, box Rect, px float64, col Color, h Alignment) *ShapedText
- func (c *Chain) DrawAlignedDir(cv *Canvas, s string, box Rect, px float64, col Color, h Alignment, ...) *ShapedText
- func (c *Chain) Ellipsize(text string, maxWidth, px float64) string
- func (c *Chain) Face(r rune) *Typeface
- func (c *Chain) Metrics() FaceMetrics
- func (c *Chain) Primary() *Typeface
- func (c *Chain) Shape(s string, px float64) *ShapedText
- func (c *Chain) ShapeDir(s string, px float64, d text.Direction) *ShapedText
- func (c *Chain) ShapeDirRunes(rs []rune, px float64, d text.Direction) *ShapedText
- func (c *Chain) ShapeRune(r rune, px float64) *ShapedText
- func (c *Chain) ShapeRunes(rs []rune, px float64) *ShapedText
- func (c *Chain) Spaced(px float64) *Chain
- func (c *Chain) Tabular() *Chain
- func (c *Chain) Weighted(w int) *Chain
- func (c *Chain) WithFeatureSpec(spec string) *Chain
- func (c *Chain) WithResolver(resolve func(rune) *Typeface) *Chain
- func (c *Chain) WithVariations(vs ...Variation) *Chain
- func (c *Chain) WordSpaced(px float64) *Chain
- func (c *Chain) Wrap(text string, maxWidth, px float64) []string
- type Color
- type Corners
- type CoverGeometry
- type CoverageMask
- type Decoration
- type DecorationLine
- type DecorationStyle
- type DropShadow
- type EllipsizeMode
- type Extend
- type FaceMetrics
- type FilterKind
- type FilterOp
- type FilterShape
- type FilterStep
- type FilterStepKind
- type Filters
- type Font
- type GlyphMask
- type Gradient
- type GradientKind
- type GradientMap
- type GradientStop
- type HyphensMode
- type Icon
- func (i *Icon) At(x, y int) color.Color
- func (i *Icon) Draw(cv *Canvas, x, y int)
- func (i *Icon) DrawRotated(cv *Canvas, x, y int, deg float64)
- func (i *Icon) DrawXformed(cv *Canvas, x, y int, m Affine)
- func (i *Icon) Image() *image.RGBA
- func (i *Icon) Size() (int, int)
- func (i *Icon) Tint(tint Color) *Icon
- func (i *Icon) Xform(x, y int, m Affine, num, denom int) M3
- type ImagePos
- type ImageScale
- type Insets
- type Layer
- func (l *Layer) ApplyMaskLayer(mask *Layer, region Rect, luminance bool)
- func (l *Layer) ApplyPathMask(p *Path, region Rect)
- func (l *Layer) Backing() any
- func (l *Layer) Canvas() *Canvas
- func (l *Layer) CrossFade(other *Layer, region Rect, t float64)
- func (l *Layer) Release()
- func (l *Layer) SetBacking(b any)
- type LineGeometry
- type List
- type M3
- type Mapped
- type Mat4
- type MatrixStep
- type Path
- type Player
- type RadialSize
- type Rect
- func MapRect(r Rect, num, denom int) Rect
- func PathMask(p *Path, region Rect, num, denom int) (*image.Alpha, Rect)
- func PlaceImage(srcW, srcH, boxW, boxH int, s ImageScale, pos ImagePos) (src image.Rectangle, dst Rect)
- func RoundedRectRegion(r Rect, radii Corners) []Rect
- func UnionAll(rects []Rect) Rect
- type RefractPlan
- type ShadowMask
- type ShadowPlan
- type ShapedText
- func (s *ShapedText) Advance() float64
- func (s *ShapedText) AppendCaretBands(buf [][2]float64, start, end int) [][2]float64
- func (s *ShapedText) Ascent() float64
- func (s *ShapedText) CaretAt(x float64) int
- func (s *ShapedText) CaretPositions() []float64
- func (s *ShapedText) CaretX(caret int) float64
- func (s *ShapedText) Descent() float64
- func (s *ShapedText) Draw(cv *Canvas, x, baselineY int, col Color)
- func (s *ShapedText) DrawDecoration(cv *Canvas, x, baseline int, d Decoration, col Color)
- func (s *ShapedText) DrawJustified(cv *Canvas, x, baselineY int, col Color, gap float64)
- func (s *ShapedText) LineHeight() int
- func (s *ShapedText) NotDefCount() int
- func (s *ShapedText) RTL() bool
- func (s *ShapedText) Runs() int
- func (s *ShapedText) SeparatorCount() int
- func (s *ShapedText) Text() string
- type State
- type StillImage
- type Tile
- type TileGeometry
- type Typeface
- func (t *Typeface) Covers(r rune) bool
- func (t *Typeface) Describe() font.Description
- func (t *Typeface) Draw(cv *Canvas, s *ShapedText, x, baselineY int, col Color)
- func (t *Typeface) DrawAligned(cv *Canvas, s string, box Rect, px float64, col Color, h Alignment) *ShapedText
- func (t *Typeface) DrawAlignedDir(cv *Canvas, s string, box Rect, px float64, col Color, h Alignment, ...) *ShapedText
- func (t *Typeface) Ellipsize(text string, maxWidth, px float64) string
- func (t *Typeface) Family() string
- func (t *Typeface) HasAxis(tag string) bool
- func (t *Typeface) IsMonospace() bool
- func (t *Typeface) Metrics() FaceMetrics
- func (t *Typeface) Oblique() *Typeface
- func (t *Typeface) Shape(s string, px float64) *ShapedText
- func (t *Typeface) ShapeDir(s string, px float64, d text.Direction) *ShapedText
- func (t *Typeface) ShapeDirRunes(rs []rune, px float64, d text.Direction) *ShapedText
- func (t *Typeface) ShapeRune(r rune, px float64) *ShapedText
- func (t *Typeface) ShapeRunes(rs []rune, px float64) *ShapedText
- func (t *Typeface) Slanted() bool
- func (t *Typeface) Spaced(px float64) *Typeface
- func (t *Typeface) Tabular() *Typeface
- func (t *Typeface) Variations() []Variation
- func (t *Typeface) Weighted(w int) *Typeface
- func (t *Typeface) WithFeatureSpec(spec string) *Typeface
- func (t *Typeface) WithVariations(vs ...Variation) *Typeface
- func (t *Typeface) WordSpaced(px float64) *Typeface
- func (t *Typeface) Wrap(text string, maxWidth, px float64) []string
- type Variation
- type VersionedImage
- type WrapOptions
- type WrapWordMode
Constants ¶
const Ellipsis = "…"
Ellipsis is the mark a truncated text carries where it was cut.
const MaxFilters = 8
MaxFilters bounds a filter list; later functions past it are dropped with a parse warning.
Variables ¶
var Identity = Affine{A: 1, D: 1}
Identity is the affine map that moves nothing.
var Identity3 = M3{1, 0, 0, 0, 1, 0, 0, 0, 1}
Identity3 is the projective map that moves nothing.
var Identity4 = Mat4{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
}
Identity4 moves nothing.
var ImageCentered = ImagePos{X: 0.5, Y: 0.5}
ImageCentered is the default placement, 50% 50%.
var Inv255 = Reciprocal(float32(255))
Inv255 is 1/255 in float32, what re-premultiplying scales by.
var SoftLightTable = func() (t [256]int32) { for b := range t { x := float64(b) / 255 d := math.Sqrt(x) if x <= 0.25 { d = ((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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
GrainStrength is PaintGrain's opacity as the 0..255 factor its noise scales by.
func 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 PathCoverage ¶
PathCoverage rasterizes p's fill coverage over box (device pixels, p scaled by the device scale) into a fresh alpha image; nil when nothing covers.
func Reciprocal ¶
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) (CoverageMask, Rect, bool)
RectShadow is how Shadow paints a shadow of blur around the logical rect r with cornerRadius at device scale num/denom: the cached mask, immutable once made, blended in the shadow's color over the device rect at; false when there is none to paint.
func Resample ¶
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 ¶
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 RoundedRadius ¶
RoundedRadius is RoundedRect's corner radius over its device rect full at num/denom: radius scaled, at most half the shorter side.
func RoundedRectPath ¶
RoundedRectPath appends the rounded rect r (logical pixels, radii clockwise from top-left) to p as one closed subpath.
func SideReciprocals ¶
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 TexelScale ¶
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 WordSep ¶
WordSep reports whether r is a CSS word separator: the characters word-spacing widens and justify distributes space across.
func WrapText ¶
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 ¶
Rotate is the map rotating about the origin by deg degrees, clockwise on screen (y grows downward), as a GSK snapshot rotation does.
type Alignment ¶
type Alignment uint8
Alignment selects how a drawn run is positioned inside its box.
type Animation ¶
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.
func (*Animation) ColorModel ¶
ColorModel implements image.Image (the first frame's).
func (*Animation) PixelBytes ¶
PixelBytes is the frames' combined pixel cost, what a byte-budget cache charges for the animation.
type ArcGeometry ¶
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 ¶
BlendModeNamed resolves a CSS keyword; false for anything else.
type BlurPlan ¶
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 ¶
BlurPlanOf is the plan for a blur of device radius radius; false for none.
type BoxShadow ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
BorderRect blends col over a hollow rect of the given logical thickness. The stroke grows inward from the rect edges.
func (*Canvas) 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
DeviceScale returns the canvas's device scale as a rational: num device pixels per denom logical pixels.
func (*Canvas) DrawCanvasDevice ¶
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 ¶
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 ¶
DrawImage blends img onto the canvas, scaled from its natural (logical) size to the device rect its logical placement spans.
func (*Canvas) DrawImageCover ¶
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 ¶
DrawImageCoverImage is DrawImageCover for an Icon's pixels.
func (*Canvas) DrawImageDevice ¶
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 ¶
DrawImageRect blends img onto the canvas scaled into the logical rect r: nearest-neighbor sampling, the mask-image rasterizer's own.
func (*Canvas) DrawLayer ¶
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 ¶
FillPath fills the path's subpaths with col, anti-aliased, under the clip and the pushed opacity. Overlapping subpaths fill once.
func (*Canvas) FillRectDevice ¶
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 ¶
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 ¶
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) MarkFocus ¶
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 ¶
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 ¶
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 ¶
PaintGradientTiles paints g over every tile t lays out, each tile its own gradient box, clipped to clip's rounded outline.
func (*Canvas) PaintGrain ¶
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 ¶
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 ¶
Painted reports that w finished painting: the containers call it after each child, drawing the armed focus ring after its widget.
func (*Canvas) PopBrightness ¶
PopBrightness restores a factor returned by PushBrightness.
func (*Canvas) PushAlpha ¶
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 ¶
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 ¶
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 ¶
PushClipDevice is PushClip for a rect already in device pixels (a damage region, a layer's rect).
func (*Canvas) Reset ¶
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 ¶
ResetRecorder readies a recording canvas for the next frame, as Reset does a raster one: its List empties and the canvas takes the given size and scale.
func (*Canvas) ResetTouched ¶
ResetTouched zeroes the drawn-pixel counter and returns the previous value.
func (*Canvas) RoundedBorder ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ScratchSnapshot is Snapshot into a scratch layer.
func (*Canvas) Shadow ¶
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 (rect size, radius, blur, device scale) in shadowRasterFor, 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.
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 ¶
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 ¶
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) Face ¶
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) 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 ¶
ShapeDir shapes under base direction d; see Chain.Shape and text.Direction.
func (*Chain) ShapeDirRunes ¶
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 ¶
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 ¶
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) WithFeatureSpec ¶
WithFeatureSpec returns the chain shaping with the OpenType features in spec on, whichever face a rune lands on (see Typeface.WithFeatureSpec).
func (*Chain) WithResolver ¶
WithResolver installs a store-backed face picker consulted for runes neither the primary nor the fallback list covers, and returns the chain. internal/sysfont.Fallback wires one to the system font store.
func (*Chain) WithVariations ¶
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 ¶
WordSpaced returns the chain shaping with px of word spacing after every word separator, whichever face a rune lands on (see Typeface.WordSpaced).
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 ¶
ColorFromBytes decodes a premultiplied color from the wl_shm byte order: little-endian ARGB8888, that is bytes B, G, R, A.
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.
type CoverGeometry ¶
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).
type CoverageMask ¶
CoverageMask is an immutable 8bpp coverage mask render caches and blends a color through: a glyph's (GlyphMask), a box-shadow core's (ShadowMask), a rect shadow's (RectShadow). A GPU renderer keys its mask atlas by it.
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 ¶
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 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 ¶
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) BrightnessOnly ¶
BrightnessOnly reports a list made solely of brightness() factors and their product: the PushBrightness fast path paints those without an offscreen layer.
func (*Filters) Extent ¶
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(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 it. 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).
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 ¶
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 ¶
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.
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 ¶
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.
func IconFromARGB32 ¶
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 ¶
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 LoadSVG ¶
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) DrawRotated ¶
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 ¶
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.
func (*Icon) Tint ¶
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.
type ImagePos ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
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) CrossFade ¶
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) 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 ¶
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.
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 (M3) Flat ¶
Flat reports a map whose third row leaves w untouched: the purely affine case, which composites without the divide.
type Mapped ¶
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.
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 ¶
Perspective4 is CSS perspective()'s matrix: the viewer at distance d on the z axis, w shrinking as z approaches it.
type MatrixStep ¶
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 ¶
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) Contains ¶
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.
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 State, face *Typeface, gid font.GID, scale, penX, penY float64, col Color)
// 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 ¶
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 PathMask ¶
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); the rest of region is uncovered. FillPath blends its color by it, and ApplyPathMask multiplies a layer's region by it.
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 ¶
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 ¶
UnionAll returns the bounding box of all rects. Nil and empty inputs yield an empty Rect.
func (Rect) Contains ¶
Contains reports whether the pixel (x, y) lies inside r. Empty rects contain nothing.
func (Rect) Intersect ¶
Intersect returns the overlap of r and o. Disjoint or empty inputs yield an empty Rect.
type RefractPlan ¶
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 it.
func (*ShadowMask) Origin ¶
func (r *ShadowMask) Origin() (x0, y0 int)
Origin is the mask's top-left from its core box's.
type ShadowPlan ¶
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) 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 ¶
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 ¶
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.
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, so changes to img never reach it.
type Tile ¶
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 ¶
TileGeometryOf lays t out over clip's rounded outline (radii in logical pixels) at device scale num/denom; false for an empty tile.
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 NewFixtureHebrewTypeface ¶
NewFixtureHebrewTypeface parses the bundled Hebrew fixture into a fresh Typeface, one per caller like NewFixtureTypeface.
func NewFixtureTypeface ¶
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 ¶
NewTypeface wraps an already-resolved face, as returned by a font matcher.
func (*Typeface) Covers ¶
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 ¶
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) HasAxis ¶
HasAxis reports whether the face is variable along tag: setting the axis to its two extremes yields different coordinates.
func (*Typeface) IsMonospace ¶
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 ¶
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 ¶
ShapeDir lays text out under base direction d; see Shape and text.Direction.
func (*Typeface) ShapeDirRunes ¶
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) Spaced ¶
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 ¶
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 ¶
Variations reports the settings this face was instantiated at; nil for a face at its default instance.
func (*Typeface) Weighted ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ParseVariations parses a CSS font-variation-settings value - "normal", or comma-separated quoted four-letter tags and numbers ("wght" 650, "wdth" 80).
type VersionedImage ¶
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.
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.
Source Files
¶
- animation.go
- arc.go
- blendmode.go
- bounds.go
- box.go
- canvas.go
- clipmask.go
- color.go
- colorglyph.go
- colr.go
- damage.go
- decoration.go
- filter.go
- glyphcache.go
- golden.go
- gradient.go
- icon.go
- image.go
- layer.go
- layerops.go
- layerpool.go
- list.go
- mapped.go
- path.go
- projective.go
- resample.go
- shadowcache.go
- shapecache.go
- svgdoc.go
- svgpath.go
- svgscan.go
- svgtransform.go
- text.go
- textcss.go
- tiles.go
- variation.go