purecairo

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 26 Imported by: 0

README

purecairo

Pure-Go re-implementation of the cairo 2D graphics API, with zero CGO dependencies. Builds on every platform Go supports — macOS, Linux, Windows, BSD — without libcairo, libpng, libfreetype, or fontconfig.

Status

API surface Implementation
Image surface image.RGBA backed, BGRA mirror for GL upload
Path (M/L/C/Z + Arc + Rectangle/RoundRect) full
Fill / FillPreserve golang.org/x/image/vector AA rasteriser
Stroke / StrokePreserve transformed outlines, dashes, round cap / join
Save / Restore stack full (matrix, source, line attrs, clip, font)
Transform stack cairo column-vector semantics
Clip / ClipBounds AABB approximation, cairo_clip_extents user-space
Operators OPERATOR_CLEAR, _SOURCE, _OVER
Patterns solid, surface, linear, radial
Text OpenType via golang.org/x/image/font/opentype
Font discovery per-OS system font walk + bundled Go fallback
CJK fallback PingFang (macOS), Noto-CJK (Linux), MS YaHei (Windows)
Glyph rendering font.Face.Glyph + draw.DrawMask
Group / mask / push pop nested device-space groups and alpha masks
Path-shaped clip not yet (AABB only)
PDF / PS / SVG export not in scope (silk has dedicated packages)
Native platform surfaces not in scope

Cross-platform usage

The package itself is universal — go build works on every Go target. The only platform-aware code is font.go, which probes per-OS font directories:

OS Probed paths
darwin /System/Library/Fonts, /System/Library/Fonts/Supplemental, /Library/Fonts, ~/Library/Fonts
linux /usr/share/fonts, /usr/share/fonts/truetype/{dejavu,noto}, /usr/share/fonts/{TTF,opentype}, /usr/local/share/fonts, ~/.fonts, ~/.local/share/fonts
windows %SystemRoot%\Fonts, C:\Windows\Fonts

If the platform walk misses the requested family, the bundled golang.org/x/image/font/gofont/goregular TrueType is used — every binary that imports this package always has a face.

Algorithm references

The implementation cites the cairo C source where the algorithm is non-trivial. Files referenced:

  • cairo/src/cairo-path-stroke.c — offset-line stroke flattening
  • cairo/src/cairo-arc.c — arc → cubic flatten step count
  • cairo/src/cairo-pattern.c — gradient stop interpolation
  • cairo/src/cairo-image-surface.c — ARGB32 pixel layout

Where the C source uses approaches that don't translate naturally to Go (e.g. cairo's trapezoid rasteriser), the Go side substitutes golang.org/x/image/vector — same coverage-based AA result, but backed by the standard image/draw composition pipeline instead of a custom pixman fallback.

Use as a standalone library

import "silk/purecairo"

func main() {
    s := purecairo.NewImageSurface(purecairo.FORMAT_ARGB32, 400, 300)
    c := s.NewContext()

    c.SetSourceRGB(1, 1, 1)
    c.Paint()

    c.SetSourceRGB(0.2, 0.4, 0.9)
    c.Rectangle(50, 50, 300, 200)
    c.Fill()

    s.WritePNG("out.png")
}

Use through silk's cairo package

silk's existing cairo package re-exports this one when built with -tags silk_pure_go. silk's own callers don't need to change anything:

go build -tags silk_pure_go ./cmd/silkide

The resulting binary has no native libcairo linkage:

otool -L /tmp/silkide      # macOS
ldd     /tmp/silkide       # linux

shows only system frameworks and libSystem.B.dylib / libc.so — no libcairo.dylib, no libpng, no libfreetype.

License

Same license as silk.

Ownership and rendering limits

Each context, surface, and scaled font is single-owner; do not mutate or render through the same instance from multiple goroutines. Independent contexts with independent scaled fonts may render concurrently: only immutable parsed font tables are shared, never OpenType scratch buffers or reusable glyph masks. Silk widget trees and the paint package caches remain UI-thread-owned; workers must use gui.Post for UI changes.

The pure-Go backend is not full Cairo parity. Clipping is still AABB-only, curves/stroke joins are approximations, and only the documented compositing operators are supported. Dash expansion is bounded to 65,536 pieces per stroke to avoid runaway work on extremely small periods; invalid patterns fall back to solid strokes. PushGroupWidthContent uses an ARGB32 intermediate regardless of the requested content hint. These limits are separate from the native Cairo backend used by release desktop binaries.

Documentation

Overview

Package purecairo is a pure-Go implementation of the Cairo 2D graphics API silk uses, with zero CGO dependencies. The package builds on every platform Go supports — macOS, Linux, Windows, BSD — without libcairo, libpng, libfreetype, or fontconfig.

API surface mirrors `cairo_*` and silk's `_hack` extensions, so silk can swap libcairo for purecairo by re-exporting the types and functions through a thin alias layer.

Algorithm references: where the C source uses a non-trivial algorithm (path stroking, arc → cubic flatten, two-circle radial gradients), the Go side either ports the same approach or substitutes a published equivalent. The cairo C source under `cairo/src/` is the reference; specific functions are cited in per-section comments.

Cross-platform parity:

  • Image surface backed by image.RGBA (every platform).
  • Text via golang.org/x/image/font/opentype with a per-OS system font discovery walk (font.go). Bundled Go-Regular TrueType is the universal fallback so the binary always has a face.
  • Window upload: silk's window code reads DataPtr() as cairo ARGB32 (BGRA byte order on little-endian) and passes it to gl.TexImage2D — Surface.Flush() rebuilds that mirror buffer.

Implemented:

  • Path: MoveTo, LineTo, CurveTo, Arc / ArcNegative, Rectangle, Line, RoundRect, NewPath, ClosePath.
  • Fill / FillPreserve: anti-aliased via golang.org/x/image/vector. Solid + surface + linear/radial gradient sources.
  • Stroke / StrokePreserve: per-segment thin-quad rasterisation (caps default to butt, joins to miter).
  • Save / Restore + transform stack with cairo column-vector semantics.
  • Clip / ClipPreserve / ResetClip / ClipBounds: AABB approximation. ClipBounds returns user-space rect via CTM inverse.
  • Paint / PaintWithAlpha: OPERATOR_CLEAR, SOURCE, OVER respected.
  • ShowGlyphs / ShowGlyphs_hack via opentype faces with CJK fallback chain.

Not implemented:

  • PDF / SVG / PostScript export surfaces.
  • Platform-native surfaces (xlib, quartz, win32).
  • Path-shaped clipping (AABB only for now).

Index

Constants

View Source
const FORMAT_ARGB = FORMAT_ARGB32

FORMAT_ARGB is the ARGB32 alias used throughout silk/paint.

Variables

This section is empty.

Functions

func Multiplygeom_Mat3x2

func Multiplygeom_Mat3x2(result, a, b *geom.Mat3x2)

Multiplygeom.Mat3x2 mirrors the original cairo.go helper used by silk (the misnamed "Multiplygeom.Mat3x2" function).

Types

type Antialias

type Antialias int
const (
	ANTIALIAS_DEFAULT Antialias = iota
	ANTIALIAS_NONE
	ANTIALIAS_GRAY
	ANTIALIAS_SUBPIXEL
)

type Content

type Content int
const (
	CONTENT_COLOR       Content = 0x1000
	CONTENT_ALPHA       Content = 0x2000
	CONTENT_COLOR_ALPHA Content = 0x3000
)

type Context

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

func (*Context) Antialias

func (this *Context) Antialias() Antialias

func (*Context) AppendPath

func (this *Context) AppendPath(p *Path)

func (*Context) Arc

func (this *Context) Arc(xc, yc, radius, a0, a1 float64)

func (*Context) ArcNegative

func (this *Context) ArcNegative(xc, yc, radius, a0, a1 float64)

func (*Context) Clip

func (this *Context) Clip()

func (*Context) ClipBounds

func (this *Context) ClipBounds() (x, y, w, h float64)

ClipBounds returns the clip extents in USER (post-CTM-inverse) space — matching libcairo's cairo_clip_extents semantics. silk's drawWidgetChildren intersects these with child Bounds(), which are also in user space, so returning device coords here would inflate the per-widget viewport by the HiDPI scale and overflow children.

We compute the user-space AABB by transforming the four device-clip corners through the inverse CTM. For pure scale+translate (the common case) this collapses to the obvious axis-aligned answer; the matrix path also handles rotated CTMs correctly.

func (*Context) ClipPreserve

func (this *Context) ClipPreserve()

func (*Context) ClosePath

func (this *Context) ClosePath()

func (*Context) CopyPage

func (this *Context) CopyPage()

func (*Context) CopyPath

func (this *Context) CopyPath() *Path

func (*Context) CopyPathFlat

func (this *Context) CopyPathFlat() *Path

func (*Context) CurrentPoint

func (this *Context) CurrentPoint() (x, y float64)

func (*Context) CurveTo

func (this *Context) CurveTo(x1, y1, x2, y2, x3, y3 float64)

func (*Context) Dash

func (this *Context) Dash() Dash

func (*Context) Destroy

func (this *Context) Destroy()

func (*Context) DeviceToUser

func (this *Context) DeviceToUser(x, y *float64)

DeviceToUser inverts the CTM at (*x, *y). Mirrors cairo's cairo_device_to_user.

func (*Context) DeviceToUserDistance

func (this *Context) DeviceToUserDistance(x, y *float64)

DeviceToUserDistance inverts the linear part of the CTM (no translation). Used for distance / size conversions where the origin shouldn't matter.

func (*Context) Fill

func (this *Context) Fill()

func (*Context) FillExtens

func (this *Context) FillExtens() (x1, y1, x2, y2 float64)

func (*Context) FillPreserve

func (this *Context) FillPreserve()

func (*Context) FillRule

func (this *Context) FillRule() FillRule

func (*Context) FontExtents

func (this *Context) FontExtents() *FontExtents

func (*Context) FontFace

func (this *Context) FontFace() *FontFace

func (*Context) FontMatrix

func (this *Context) FontMatrix(m *geom.Mat3x2)

func (*Context) FontOptions

func (this *Context) FontOptions(o *FontOptions)

func (*Context) GetMatrix

func (this *Context) GetMatrix(m *geom.Mat3x2)

func (*Context) GlyphExtents

func (this *Context) GlyphExtents(glyphs []Glyph) *TextExtents

func (*Context) GroupTarget

func (this *Context) GroupTarget() *Surface

func (*Context) HasCurrentPoint

func (this *Context) HasCurrentPoint() bool

func (*Context) InClip

func (this *Context) InClip(x, y float64) bool

func (*Context) InFill

func (this *Context) InFill(x, y float64) bool

func (*Context) InStroke

func (this *Context) InStroke(x, y float64) bool

func (*Context) Line

func (this *Context) Line(x0, y0, x1, y1 float64)

func (*Context) LineCap

func (this *Context) LineCap() LineCap

func (*Context) LineJoin

func (this *Context) LineJoin() LineJoin

func (*Context) LineTo

func (this *Context) LineTo(x, y float64)

func (*Context) LineWidth

func (this *Context) LineWidth() float64

func (*Context) Mask

func (this *Context) Mask(p *Pattern)

func (*Context) MaskSurface

func (this *Context) MaskSurface(s *Surface, x, y float64)

func (*Context) MiterLimit

func (this *Context) MiterLimit() float64

func (*Context) MoveTo

func (this *Context) MoveTo(x, y float64)

func (*Context) NewPath

func (this *Context) NewPath()

func (*Context) NewSubPath

func (this *Context) NewSubPath()

func (*Context) Operator

func (this *Context) Operator() Operator

func (*Context) Paint

func (this *Context) Paint()

func (*Context) PaintWithAlpha

func (this *Context) PaintWithAlpha(alpha float64)

PaintWithAlpha fills the active clip region with the current source. Honours the active Porter-Duff operator — most importantly OpClear (zeroes the destination) and OpOver (alpha-blends source over dest).

The clear case is critical: silk's Window.paint() begins each frame with `SetOperator(OpClear); Paint(); SetOperator(OpOver)` to wipe the back buffer. If we ignored the operator and painted with the source colour instead, every frame would inherit the previous frame's last source — visible as huge coloured panels under the rest of the UI.

func (*Context) PathExtens

func (this *Context) PathExtens() (x1, y1, x2, y2 float64)

func (*Context) PopGroup

func (this *Context) PopGroup() *Pattern

func (*Context) PopGroupToSource

func (this *Context) PopGroupToSource()

func (*Context) PushGroup

func (this *Context) PushGroup()

func (*Context) PushGroupWidthContent

func (this *Context) PushGroupWidthContent(c Content)

func (*Context) Rectangle

func (this *Context) Rectangle(x, y, w, h float64)

func (*Context) RelCurveTo

func (this *Context) RelCurveTo(x1, y1, x2, y2, x3, y3 float64)

func (*Context) RelLineTo

func (this *Context) RelLineTo(dx, dy float64)

func (*Context) RelMoveTo

func (this *Context) RelMoveTo(dx, dy float64)

func (*Context) ResetClip

func (this *Context) ResetClip()

func (*Context) ResetMatrix

func (this *Context) ResetMatrix()

func (*Context) Restore

func (this *Context) Restore()

func (*Context) Rotate

func (this *Context) Rotate(r float64)

Rotate concatenates a rotation onto the CTM. cairo_rotate semantics: rotates user space, so CTM_new = CTM * Rotate(theta).

func (*Context) RoundRect

func (this *Context) RoundRect(x, y, w, h, r float64)

func (*Context) Save

func (this *Context) Save()

func (*Context) Scale

func (this *Context) Scale(sx, sy float64)

Scale concatenates a user-space scale. Scaling user space by (sx, sy) means a unit user vector now maps to (sx, sy) user → applied to existing CTM that already maps user→device. So Xx, Xy multiply by sx; Yx, Yy multiply by sy.

func (*Context) ScaledFont

func (this *Context) ScaledFont() *ScaledFont

func (*Context) SelectFontFace

func (this *Context) SelectFontFace(family string, slant FontSlant, weight FontWeight)

func (*Context) SetAntialias

func (this *Context) SetAntialias(a Antialias)

func (*Context) SetDash

func (this *Context) SetDash(d Dash)

func (*Context) SetFillRule

func (this *Context) SetFillRule(r FillRule)

func (*Context) SetFontFace

func (this *Context) SetFontFace(f *FontFace)

func (*Context) SetFontMatrix

func (this *Context) SetFontMatrix(m *geom.Mat3x2)

func (*Context) SetFontOptions

func (this *Context) SetFontOptions(o *FontOptions)

func (*Context) SetFontSize

func (this *Context) SetFontSize(s float64)

func (*Context) SetLineCap

func (this *Context) SetLineCap(c LineCap)

func (*Context) SetLineJoin

func (this *Context) SetLineJoin(j LineJoin)

func (*Context) SetLineWidth

func (this *Context) SetLineWidth(w float64)

func (*Context) SetMatrix

func (this *Context) SetMatrix(m *geom.Mat3x2)

func (*Context) SetMiterLimit

func (this *Context) SetMiterLimit(m float64)

func (*Context) SetOperator

func (this *Context) SetOperator(o Operator)

func (*Context) SetScaledFont

func (this *Context) SetScaledFont(sf *ScaledFont)

func (*Context) SetSource

func (this *Context) SetSource(p *Pattern)

SetSource binds a pattern as the active fill / paint source. Solid colours stay on state.source; surfaces feed state.sourceSurf; gradients build a per-pixel image.Image on state.sourceImage.

func (*Context) SetSourceRGB

func (this *Context) SetSourceRGB(r, g, b float64)

func (*Context) SetSourceRGBA

func (this *Context) SetSourceRGBA(r, g, b, a float64)

func (*Context) SetSourceSurface

func (this *Context) SetSourceSurface(s *Surface, x, y float64)

SetSourceSurface mirrors cairo_set_source_surface: subsequent fill / paint draws sample pixels from `s`, with the surface's pixel (0, 0) anchored at user (x, y).

func (*Context) SetTolerance

func (this *Context) SetTolerance(v float64)

func (*Context) ShowGlyphs

func (this *Context) ShowGlyphs(glyphs []Glyph)

ShowGlyphs renders an explicit glyph slice. Same code path as ShowGlyphs_hack but takes a typed slice — used by silk's higher-level helpers that don't go through the unsafe-pointer dance.

func (*Context) ShowGlyphs_hack

func (this *Context) ShowGlyphs_hack(p unsafe.Pointer, n int)

ShowGlyphs_hack rasterises the glyph array at p (length n) using the active scaled font. CTM applies to each glyph's (X, Y) — that's the cairo convention, glyph positions live in user space and the rasteriser pushes them through the matrix.

Glyphs whose rune isn't in the primary face flow through the CJK fallback face, matching libcairo's substitution behaviour.

func (*Context) ShowPage

func (this *Context) ShowPage()

func (*Context) ShowText

func (this *Context) ShowText(text string)

ShowText renders `text` starting at the current point. Each rune's advance moves the current point so consecutive ShowText calls concatenate. CTM applies to glyph positions identically to ShowGlyphs.

func (*Context) Source

func (this *Context) Source() *Pattern

func (*Context) Status

func (this *Context) Status() Status

func (*Context) Stroke

func (this *Context) Stroke()

func (*Context) StrokeExtens

func (this *Context) StrokeExtens() (x1, y1, x2, y2 float64)

func (*Context) StrokePreserve

func (this *Context) StrokePreserve()

func (*Context) Target

func (this *Context) Target() *Surface

func (*Context) TextExtents

func (this *Context) TextExtents(text string) *TextExtents

func (*Context) TextPath

func (this *Context) TextPath(s string)

func (*Context) Tolerance

func (this *Context) Tolerance() float64

func (*Context) Transform

func (this *Context) Transform(m *geom.Mat3x2)

Transform applies a user-space matrix m onto the CTM. The composition is CTM_new = CTM * m, mirroring cairo_transform.

func (*Context) Translate

func (this *Context) Translate(tx, ty float64)

Translate concatenates a user-space translation onto the CTM. The device shift equals (Xx*tx + Xy*ty, Yx*tx + Yy*ty) — under a 2x HiDPI scale, Translate(10, 0) shifts device by 20 pixels. silk's geom.Mat3x2.Translate would shift by 10, breaking the coord match between Rectangle (which scales) and Translate (which doesn't).

func (*Context) UserToDevice

func (this *Context) UserToDevice(x, y *float64)

func (*Context) UserToDeviceDistance

func (this *Context) UserToDeviceDistance(x, y *float64)

type Dash

type Dash struct {
	Dashes []float64
	Offset float64
}

type Device

type Device struct{}

func (*Device) Destroy

func (this *Device) Destroy()

func (*Device) Status

func (this *Device) Status() Status

func (*Device) Type

func (this *Device) Type() int

type Extend

type Extend int
const (
	EXTEND_NONE Extend = iota
	EXTEND_REPEAT
	EXTEND_REFLECT
	EXTEND_PAD
)

type FillRule

type FillRule int
const (
	FILL_RULE_WINDING FillRule = iota
	FILL_RULE_EVEN_ODD
)

type Filter

type Filter int
const (
	FILTER_FAST Filter = iota
	FILTER_GOOD
	FILTER_BEST
	FILTER_NEAREST
	FILTER_BILINEAR
	FILTER_GAUSSIAN
)

type FontExtents

type FontExtents struct {
	Ascent      float64
	Descent     float64
	Height      float64
	MaxXAdvance float64
	MaxYAdvance float64
}

type FontFace

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

func NewToyFontFace

func NewToyFontFace(family string, slant FontSlant, weight FontWeight) *FontFace

func (*FontFace) Destroy

func (this *FontFace) Destroy()

func (*FontFace) Status

func (this *FontFace) Status() Status

func (*FontFace) ToyFamily

func (this *FontFace) ToyFamily() string

func (*FontFace) ToySlant

func (this *FontFace) ToySlant() FontSlant

func (*FontFace) ToyWeight

func (this *FontFace) ToyWeight() FontWeight

func (*FontFace) Type

func (this *FontFace) Type() int

type FontOptions

type FontOptions struct{}

func NewFontOptions

func NewFontOptions() *FontOptions

func (*FontOptions) Antialias

func (this *FontOptions) Antialias() Antialias

func (*FontOptions) Copy

func (this *FontOptions) Copy() *FontOptions

func (*FontOptions) Destroy

func (this *FontOptions) Destroy()

func (*FontOptions) Equal

func (this *FontOptions) Equal(other *FontOptions) bool

func (*FontOptions) Hash

func (this *FontOptions) Hash() uint32

func (*FontOptions) HintMetrics

func (this *FontOptions) HintMetrics() int

func (*FontOptions) HintStyle

func (this *FontOptions) HintStyle() int

func (*FontOptions) Merge

func (this *FontOptions) Merge(other *FontOptions)

func (*FontOptions) SetAntialias

func (this *FontOptions) SetAntialias(a Antialias)

func (*FontOptions) SetHintMetrics

func (this *FontOptions) SetHintMetrics(int)

func (*FontOptions) SetHintStyle

func (this *FontOptions) SetHintStyle(int)

func (*FontOptions) SetSubpixelOrder

func (this *FontOptions) SetSubpixelOrder(int)

func (*FontOptions) Status

func (this *FontOptions) Status() Status

func (*FontOptions) SubpixelOrder

func (this *FontOptions) SubpixelOrder() int

type FontSlant

type FontSlant int
const (
	FONT_SLANT_NORMAL FontSlant = iota
	FONT_SLANT_ITALIC
	FONT_SLANT_OBLIQUE
)

type FontWeight

type FontWeight int
const (
	FONT_WEIGHT_NORMAL FontWeight = iota
	FONT_WEIGHT_BOLD
)

type Format

type Format int
const (
	FORMAT_INVALID   Format = -1
	FORMAT_ARGB32    Format = 0
	FORMAT_RGB24     Format = 1
	FORMAT_A8        Format = 2
	FORMAT_A1        Format = 3
	FORMAT_RGB16_565 Format = 4
)

type Glyph

type Glyph struct {
	A uint32 // unused for cairo, but use in lib/gui
	X float64
	Y float64
	// contains filtered or unexported fields
}

func (Glyph) Index

func (g Glyph) Index() uint32

Index returns this backend's glyph identifier (a Unicode scalar value).

type Image

type Image interface {
	Format() Format
	Width() int
	Height() int
	Stride() int
}

Image is the high-level interface silk uses for surfaces; ImageSurface is just a *Surface alias.

type LineCap

type LineCap int
const (
	LINE_CAP_BUTT LineCap = iota
	LINE_CAP_ROUND
	LINE_CAP_SQUARE
)

type LineJoin

type LineJoin int
const (
	LINE_JOIN_MITER LineJoin = iota
	LINE_JOIN_ROUND
	LINE_JOIN_BEVEL
)

type MappedImage

type MappedImage struct {
	Surface *Surface
}

MappedImage is a lightweight handle returned by MapToImage — purecairo only ever maps to the current surface, so the type is a pass-through.

type Operator

type Operator int
const (
	OPERATOR_CLEAR Operator = iota
	OPERATOR_SOURCE
	OPERATOR_OVER
	OPERATOR_IN
	OPERATOR_OUT
	OPERATOR_ATOP
	OPERATOR_DEST
	OPERATOR_DEST_OVER
	OPERATOR_DEST_IN
	OPERATOR_DEST_OUT
	OPERATOR_DEST_ATOP
	OPERATOR_XOR
	OPERATOR_ADD
	OPERATOR_SATURATE
	OPERATOR_MULTIPLY
	OPERATOR_SCREEN
	OPERATOR_OVERLAY
	OPERATOR_DARKEN
	OPERATOR_LIGHTEN
	OPERATOR_COLOR_DODGE
	OPERATOR_COLOR_BURN
	OPERATOR_HARD_LIGHT
	OPERATOR_SOFT_LIGHT
	OPERATOR_DIFFERENCE
	OPERATOR_EXCLUSION
	OPERATOR_HSL_HUE
	OPERATOR_HSL_SATURATION
	OPERATOR_HSL_COLOR
	OPERATOR_HSL_LUMINOSITY
)

type Path

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

func (*Path) Destroy

func (this *Path) Destroy()

type PathDataType

type PathDataType int

type Pattern

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

Pattern is the source for fill/stroke. silk uses solid colour patterns most of the time, surface patterns for image brushes, and gradients for theme buttons / cards / radial avatars.

func NewLinearPattern

func NewLinearPattern(x0, y0, x1, y1 float64) *Pattern

NewLinearPattern creates a linear gradient between (x0, y0) and (x1, y1) in user space. Add stops with AddColorStopRGBA.

func NewPatternForSurface

func NewPatternForSurface(s *Surface) *Pattern

func NewRGBAPattern

func NewRGBAPattern(r, g, b, a float64) *Pattern

func NewRGBPattern

func NewRGBPattern(r, g, b float64) *Pattern

func NewRadialPattern

func NewRadialPattern(cx0, cy0, r0, cx1, cy1, r1 float64) *Pattern

NewRadialPattern creates a radial gradient between two circles. Stops interpolate from the inner (r0) to the outer (r1) circle — silk's avatar / card highlights typically pass r0 = 0.

func (*Pattern) AddColorStopRGB

func (this *Pattern) AddColorStopRGB(off, r, g, b float64)

AddColorStopRGB / AddColorStopRGBA push a stop onto the gradient stop list. Stops stay sorted by offset because silk's callers add them in order; if a future caller breaks that, sampling still yields a sensible (clamped) colour for any t.

func (*Pattern) AddColorStopRGBA

func (this *Pattern) AddColorStopRGBA(off, r, g, b, a float64)

func (*Pattern) ColorStopCount

func (this *Pattern) ColorStopCount() int

func (*Pattern) ColorStopRGBA

func (this *Pattern) ColorStopRGBA(idx int) (off, r, g, b, a float64)

func (*Pattern) Destroy

func (this *Pattern) Destroy()

func (*Pattern) Extend

func (this *Pattern) Extend() Extend

func (*Pattern) Filter

func (this *Pattern) Filter() Filter

func (*Pattern) GetMatrix

func (this *Pattern) GetMatrix(m *geom.Mat3x2)

func (*Pattern) RGBA

func (this *Pattern) RGBA() (r, g, b, a float64)

func (*Pattern) SetExtend

func (this *Pattern) SetExtend(e Extend)

func (*Pattern) SetFilter

func (this *Pattern) SetFilter(f Filter)

func (*Pattern) SetMatrix

func (this *Pattern) SetMatrix(m *geom.Mat3x2)

func (*Pattern) Status

func (this *Pattern) Status() Status

func (*Pattern) Surface

func (this *Pattern) Surface() *Surface

func (*Pattern) Type

func (this *Pattern) Type() int

type Rectangle

type Rectangle struct {
	X, Y, Width, Height float64
}

type RectangleInt

type RectangleInt struct {
	X, Y, Width, Height int32
}

type RectangleList

type RectangleList struct {
	Status     Status
	Rectangles []Rectangle
}

type ScaledFont

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

func NewScaledFont

func NewScaledFont(face *FontFace, matrix, ctm *geom.Mat3x2, options *FontOptions) *ScaledFont

func (*ScaledFont) Ctm

func (this *ScaledFont) Ctm(m *geom.Mat3x2)

func (*ScaledFont) Destroy

func (this *ScaledFont) Destroy()

func (*ScaledFont) FontExtents

func (this *ScaledFont) FontExtents() *FontExtents

FontExtents reports ascent / descent / line-height in pixels. Drives silk's text alignment math; needs to be a real number (not the placeholder constants the bitmap stub returned) so labels position vertically the same as on the libcairo build.

func (*ScaledFont) FontFace

func (this *ScaledFont) FontFace() *FontFace

func (*ScaledFont) FontMatrix

func (this *ScaledFont) FontMatrix(m *geom.Mat3x2)

func (*ScaledFont) FontOptions

func (this *ScaledFont) FontOptions() *FontOptions

func (*ScaledFont) GlyphExtents

func (this *ScaledFont) GlyphExtents(glyphs []Glyph) *TextExtents

GlyphExtents totals the advance width of glyphs[] using the real face. Heights come from font metrics. Cairo uses this for hit tests and selection rectangles.

func (*ScaledFont) GlyphExtents_hack

func (this *ScaledFont) GlyphExtents_hack(p unsafe.Pointer, n int) *TextExtents

GlyphExtents_hack reads `n` Glyphs from raw memory and delegates to GlyphExtents. silk's CGO bypass passes an unsafe pointer; same 24-byte stride as the libcairo build.

func (*ScaledFont) GlyphPath

func (this *ScaledFont) GlyphPath(glyphs []Glyph)

func (*ScaledFont) ScaleMatrix

func (this *ScaledFont) ScaleMatrix(m *geom.Mat3x2)

func (*ScaledFont) Status

func (this *ScaledFont) Status() Status

func (*ScaledFont) TextExtents

func (this *ScaledFont) TextExtents(text string) *TextExtents

TextExtents measures width/height of a text string at this font's scale. Used by silk's alignment + ellipsis logic.

func (*ScaledFont) TextToGlyphs_hack

func (this *ScaledFont) TextToGlyphs_hack(x, y float64, text string, out func(buf unsafe.Pointer, num int)) error

func (*ScaledFont) Type

func (this *ScaledFont) Type() int

type Status

type Status int32
const (
	STATUS_SUCCESS Status = 0
)

type Surface

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

Surface mirrors cairo_surface_t. silk uses image surfaces almost exclusively (window back-buffer, off-screen pixmaps); we back it with image.RGBA for the rasteriser to write into.

Byte-order bridge: silk's window upload path reads DataPtr() as Cairo ARGB32 — which on little-endian machines lands as BGRA in memory. Go's image.RGBA stores RGBA. To keep Window.paint() unchanged we maintain a parallel `dataBGRA` slice that mirrors img.Pix with R↔B swapped; Flush() rebuilds it. DataPtr() returns dataBGRA, which Window.paint() then ships to gl.TexImage2D as gl.BGRA without converting per-channel.

Reference: cairo/src/cairo-image-surface.c (CAIRO_FORMAT_ARGB32 pixel layout). cairo's native format on little-endian platforms is already BGRA byte order, so the byte-swap loop here matches what libcairo would have produced internally.

func NewImageSurface

func NewImageSurface(format Format, width, height int) *Surface

NewImageSurface creates an image-backed surface of the given format. FORMAT_ARGB32 is the dominant case in silk.

func NewImageSurfaceFromPNG

func NewImageSurfaceFromPNG(filename string) (*Surface, error)

NewImageSurfaceFromPNG decodes a PNG from disk into a fresh surface.

func NewImageSurfaceFromPNGStream

func NewImageSurfaceFromPNGStream(r io.Reader) (*Surface, error)

NewImageSurfaceFromPNGStream decodes a PNG from any reader.

func NewWin

func NewWin(unused unsafe.Pointer, w, h int) *Surface

NewWin is a no-op stub for windows-specific window surfaces — silk's glfw path doesn't use it under silk_pure_go.

func (*Surface) Content

func (this *Surface) Content() Content

func (*Surface) CopyPage

func (this *Surface) CopyPage()

func (*Surface) CreateForRectangle

func (this *Surface) CreateForRectangle(r Rectangle) *Surface

func (*Surface) CreateSimilar

func (this *Surface) CreateSimilar(c Content, w, h int) *Surface

func (*Surface) CreateSimilarImage

func (this *Surface) CreateSimilarImage(f Format, w, h int) *Surface

func (*Surface) DataPtr

func (this *Surface) DataPtr() unsafe.Pointer

DataPtr returns the Cairo-compatible BGRA byte buffer for GL upload. Lazy-rebuilt by Flush — call Flush before DataPtr if Drawing has happened since the last frame.

func (*Surface) Destroy

func (this *Surface) Destroy()

func (*Surface) Device

func (this *Surface) Device() *Device

func (*Surface) DeviceOffset

func (this *Surface) DeviceOffset() (x, y float64)

func (*Surface) FallbackResolution

func (this *Surface) FallbackResolution() (xppi, yppi float64)

func (*Surface) Finish

func (this *Surface) Finish()

Finish matches cairo_surface_finish: after it the surface accepts no further drawing. A pure-Go surface owns only Go memory that the collector reclaims, so there is nothing to release — but the method must exist, because callers selected by filename on Windows (gui/window_windows.go) call it on every build, cgo or not.

func (*Surface) Flush

func (this *Surface) Flush()

Flush rebuilds dataBGRA from img.Pix (R↔B swapped). Called every frame by Window.paint() right before DataPtr() / TexImage2D, so the GL upload sees Cairo-compatible BGRA byte order. Rebuilding is O(W*H) but a 1400×900 frame is ~5MB — well below the GPU's per-frame texture upload bandwidth.

func (*Surface) FontOptions

func (this *Surface) FontOptions() *FontOptions

func (*Surface) Format

func (this *Surface) Format() Format

func (*Surface) GetMimeData

func (this *Surface) GetMimeData(mimeType string) ([]byte, bool)

func (*Surface) HasShowTextGlyphs

func (this *Surface) HasShowTextGlyphs() bool

func (*Surface) Height

func (this *Surface) Height() int

func (*Surface) Image

func (this *Surface) Image() (image.Image, error)

Image returns the surface as a Go image.Image. Match Pixmap interface signature expected by silk/paint: (image.Image, error).

func (*Surface) MapToImage

func (this *Surface) MapToImage(extents *RectangleInt) *MappedImage

func (*Surface) MarkDirty

func (this *Surface) MarkDirty()

func (*Surface) NewContext

func (this *Surface) NewContext() *Context

NewContext allocates a drawing context for this surface. The Context holds rasteriser state + transform stack.

func (*Surface) RGBA

func (this *Surface) RGBA() *image.RGBA

RGBA returns the underlying *image.RGBA directly. Used by purego rasteriser internals.

func (*Surface) SetData

func (this *Surface) SetData(src []uint8) error

SetData copies the raw pixel byte stream into the surface backing store. silk uses this to wrap caller-allocated framebuffers.

func (*Surface) SetDeviceOffset

func (this *Surface) SetDeviceOffset(x, y float64)

func (*Surface) SetFallbackResolution

func (this *Surface) SetFallbackResolution(xppi, yppi float64)

func (*Surface) SetImage

func (this *Surface) SetImage(img image.Image) error

SetImage copies an image.Image into the surface. Used by silk's TextToPixmap / IconTextToPixmap helpers.

func (*Surface) SetMimeData

func (this *Surface) SetMimeData(mimeType string, data []byte)

func (*Surface) ShowPage

func (this *Surface) ShowPage()

func (*Surface) Status

func (this *Surface) Status() Status

func (*Surface) Stride

func (this *Surface) Stride() int

func (*Surface) Type

func (this *Surface) Type() SurfaceType

func (*Surface) UnmapImage

func (this *Surface) UnmapImage(im *MappedImage)

func (*Surface) Width

func (this *Surface) Width() int

func (*Surface) WritePNG

func (this *Surface) WritePNG(filename string) error

WritePNG saves the surface as PNG. Standard library png.Encode is the obvious choice — no need for libcairo's writer.

func (*Surface) WritePNGToStream

func (this *Surface) WritePNGToStream(w io.Writer) error

WritePNGToStream writes the surface as PNG to any io.Writer.

type SurfaceType

type SurfaceType int
const (
	SURFACE_TYPE_IMAGE SurfaceType = iota
	SURFACE_TYPE_PDF
	SURFACE_TYPE_PS
	SURFACE_TYPE_XLIB
	SURFACE_TYPE_XCB
	SURFACE_TYPE_GLITZ
	SURFACE_TYPE_QUARTZ
	SURFACE_TYPE_WIN32
)

type TextExtents

type TextExtents struct {
	XBearing float64
	YBearing float64
	Width    float64
	Height   float64
	XAdvance float64
	YAdvance float64
}

Jump to

Keyboard shortcuts

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