cairoon

MoonBit native bindings for the Cairo graphics library.

cairo
graphics
ffi
moon add CAIMEOX/cairoon@0.2.0
Download zip
Author
Version
0.2.0
License
LGPL-2.1-only OR MPL-1.1
Last updated
28 days ago
Downloads
27

Dependencies

README

#cairoon

cairoon is a native MoonBit binding for the Cairo graphics library.

cairoon is temporarily unstable. The current 0.x series is intended for experimentation and light Cairo-dependent MoonBit projects. The public API, package layout, native link configuration, and release process may change before 1.0; pin the exact cairoon version or commit in downstream projects.

cairoon is inspired by pycairo: it tries to stay close to Cairo's C API, while using MoonBit-native value types, checked CairoError suberrors, explicit stream callbacks, and GC-managed external objects for Cairo handles.

#Requirements

  • MoonBit with native target support.
  • Cairo 1.15.10 or newer development headers and library. Cairo 1.18.4 is the recommended production version.
  • pkg-config that can resolve cairo.
  • Python 3 for cairoon's MoonBit pre-build configuration and repository checks.

cairoon is native-only. Its module metadata declares native as both the preferred and sole supported target, so WebAssembly, WasmGC, JavaScript, and LLVM builds stop at the module boundary instead of compiling partial FFI packages. The binding depends on Cairo C FFI.

The local release matrix covers exact Cairo 1.15.10 and 1.18.4 source builds plus Ubuntu 24.04's stock Cairo 1.18.0. APIs introduced after the lower bound are compile-time feature-gated; availability still depends on the Cairo library installed by the consumer.

#Installation

Install and pin the current release candidate from Mooncakes after it is published:

moon add CAIMEOX/cairoon@0.2.0

The published 0.1.0 preview predates dependency-side Cairo discovery and is not recommended for downstream use. Until 0.2.0 is uploaded, depend on this exact checkout or commit through a MoonBit workspace. Do not run moon publish; the repository release checklist requires the remaining hosted CI evidence first.

#Quick Start

For a local checkout:

moon check --target native moon test --target native ./scripts/check-downstream-consumer.sh

moon.mod runs scripts/build/cairo_config.py before native builds. It asks pkg-config for this machine's Cairo headers and library, supplies C-stub flags to the native package, and propagates linker flags to downstream packages. This uses MoonBit's experimental pre-build config protocol, which is one reason the project remains unstable; depend only on trusted cairoon releases.

CAIRO_VERSION* and HAS_* are generated release-source snapshots because MoonBit does not currently provide dependency-side generated MoonBit source. An unchanged archive can therefore retain the producer's constant values when compiled against different Cairo headers. Use cairo_version() and cairo_version_string() for runtime version decisions.

When using cairoon from another MoonBit package, import CAIMEOX/cairoon in the consumer package's moon.pkg. Do not repeat Cairo compiler or linker flags in the consumer; the native package propagates them:

import {
"CAIMEOX/cairoon",
}

Example:

fn draw_example() -> Unit raise @cairoon.CairoError {
let surface = @cairoon.Surface::image(@cairoon.Argb32, 200, 200)
let ctx = @cairoon.Context::new(surface)
ctx.scale(200.0, 200.0)
ctx.set_line_width(0.04)
ctx.move_to(0.1, 0.5)
ctx.curve_to(0.4, 0.9, 0.6, 0.1, 0.9, 0.5)
ctx.stroke()
ctx.set_source_rgba(1.0, 0.2, 0.2, 0.6)
ctx.set_line_width(0.02)
ctx.move_to(0.1, 0.5)
ctx.line_to(0.4, 0.9)
ctx.move_to(0.6, 0.1)
ctx.line_to(0.9, 0.5)
ctx.stroke()
surface.write_to_png("example.png")
}

#Features

  • Object-oriented MoonBit wrappers for Cairo surfaces, contexts, patterns, paths, fonts, regions, and devices.
  • Checked status handling through Status and CairoError suberrors instead of unchecked integer status returns.
  • Image surfaces, buffer-backed image surfaces, PNG file/stream I/O, MIME data, mapped images, and mutable image-data views.
  • PDF, PS, SVG, recording, tee, and script backend helpers for portable Cairo builds.
  • Solid, surface, gradient, mesh, and raster-source patterns.
  • Toy font faces, font options, scaled fonts, text extents, glyph extents, text_to_glyphs, and show_text_glyphs.
  • Executable MoonBit reference examples in src/README.mbt.md and src/docs/*.mbt.md.
  • Native and ASan/LSan/UBSan verification gates with direct C Cairo oracle tests for the migrated rendering slices.

#Current Stability

cairoon is suitable for light native use when the required inventory rows are marked Done, the automated six-workflow downstream contract passes, and the project is pinned. The contract exercises image/path/pattern rendering, scoped mapped images, Matrix/Region values, typed errors, PNG callbacks, and a PDF stream against both source and extracted archives. The complete portable API scope and all 20 pinned pycairo test-source families are covered, and all 579 published declarations have substantive API documentation. Raw text-to-glyph result fallback is exercised by a 1000-iteration finalizer-only stress package whose ledger forbids explicit release. The sole global Partial inventory row is test/release-platform evidence: GitHub Actions run 29678818105 passed macOS native but failed both Ubuntu jobs on the prior release commit. The local fixes and expanded consumer contract now pass 226 script tests, all 841 native tests, the byte-identical 695-member publication contract, and every package under ASan/LSan/UBSan in the first-class Ubuntu 24.04 system-Cairo lane on both local arm64 and Rosetta-backed x86_64. That fix commit still needs passing Ubuntu and macOS native jobs plus the Ubuntu ASan/LSan/UBSan job. Platform-specific backends remain out of scope, and no source-compatibility promise exists before 1.0.

Linux ASan/LSan/UBSan runs each MoonBit package in a separate process. Cairo 1.15.10 and 1.18.4 both have two reproducible upstream error-path leaks covered by this suite: an SVG recording-surface snapshot and PDF finalization after a missing JBIG2 global segment. Standalone pure-C probes must reproduce exact allocation signatures before the gate enables narrow LSan suppressions for only the vector oracle and PDF backend test packages. Suppression counts and bytes must match the probes exactly; every other package remains unsuppressed. This does not change runtime behavior.

Platform-specific Xlib, XCB, and Win32 surfaces are outside the first portable scope. Python-specific pycairo APIs such as CAPI, get_include(), Python file objects, pickle behavior, and legacy uppercase enum aliases are not part of the MoonBit API.

#Documentation

  • src/README.mbt.md: executable package overview and smoke examples.
  • src/docs/status_and_version.mbt.md: Cairo versions, feature constants, statuses, and checked suberror mapping.
  • src/docs/enums.mbt.md: typed enum families, raw compatibility boundaries, and state round trips.
  • src/docs/value_types.mbt.md: rectangles, glyphs, text clusters, and extents.
  • src/docs/matrix.mbt.md: affine transforms.
  • src/docs/surface.mbt.md: image surfaces, PNG, MIME, mapped images, and surface errors.
  • src/docs/backend_surfaces.mbt.md: PDF, PS, SVG, recording, tee, and script backends.
  • src/docs/context.mbt.md: drawing state, transforms, paths, clips, groups, text, glyphs, PDF tags, links, destinations, and content references.
  • src/docs/font.mbt.md: font options, toy font faces, scaled fonts, and text conversion.
  • src/docs/path.mbt.md, src/docs/pattern.mbt.md, and src/docs/region.mbt.md: the remaining public API families.
  • PORTING_FROM_PYCAIRO.md: pycairo migration notes.
  • API_INVENTORY.md: authoritative API and product status ledger.
  • AUDIT.md: concise current architecture, product, and release audit.
  • TESTING.md: current reliability strategy, test tiers, and evidence summary.
  • docs/api-audit/README.md, docs/audit/README.md, and docs/testing/README.md: bounded historical reports; old counts there are traceability records, not current release claims.
  • PACKAGING.md: native dependency and release checklist.
  • CHANGELOG.md: versioned release and compatibility notes.

#Testing

Run the local reliability gate before depending on a checkout or cutting a release:

./scripts/verify.sh

The gate checks formatting, generated Cairo-constant drift, the pre-build configuration protocol, project layout, FFI ownership annotations and borrowed return references, the exact external-owner/finalizer/stress ledger, complete pycairo API-shape inventory, and public-documentation coverage, the reliability and public-coverage ledgers, native type checking, all 20 pinned pycairo test-file families (288 upstream tests), the complete in-module MoonBit native suite, six isolated downstream-module public workflows against both the checkout and extracted publication zip, publication-archive isolation, version/changelog/install consistency, executable docs, direct C Cairo oracle tests, moon info, and ASan/LSan/UBSan when a sanitizer-capable compiler is available. Exact counts for the current audited revision are recorded in API_INVENTORY.md, AUDIT.md, and TESTING.md; older per-slice transcripts are indexed under docs/. The parity gate rejects an unclaimed or multiply claimed upstream tests/test_*.py file.

Run the instrumented public-package coverage audit after implementation or test changes and before a release candidate:

python3 ./scripts/check-public-coverage.py --analyze

It queries the linked Cairo version, selects exact semver-scoped exceptions, and rejects newly uncovered public-facade branches or stale exceptions. Scopes use <, >=, ==, and !=, comma for AND, and | for OR. Every remaining linked-version, platform, native-invariant, and defensive branch requires an exact entry in scripts/public-coverage-exceptions.tsv. All three local Cairo lanes below run this instrumented analysis automatically. Each lane also consumes the same unmodified host-generated publication zip, so host-specific include or library paths cannot hide in a release artifact.

Before a release candidate, run all Linux compatibility lanes locally:

./scripts/test-cairo-matrix.sh ubuntu-24.04-system ./scripts/test-cairo-matrix.sh cairo-1.15.10 ./scripts/test-cairo-matrix.sh cairo-1.18.4

To replay the Ubuntu lane as x86_64 from Apple Silicon without using hosted CI, select a Rosetta-backed Docker context explicitly:

./scripts/test-cairo-matrix.sh ubuntu-24.04-system \ --platform linux/amd64 \ --docker-context colima-cairoon-rosetta

The selected platform is passed to both image build and execution and is part of the local image tag. Pinned downloads retry and resume partial transfers.

#License

cairoon uses the same license expression as pycairo:

LGPL-2.1-only OR MPL-1.1

The distribution includes the project notice in COPYING and the complete license texts in COPYING-LGPL-2.1 and COPYING-MPL-1.1.

#cairoon

cairoon is a native MoonBit binding for the Cairo graphics library.

This project is temporarily unstable. It is useful for experiments and for light Cairo-dependent MoonBit projects, but the public API, package layout, native link configuration, and release process may still change before a stable release. Treat versions before 1.0 as beta releases and pin them deliberately.

cairoon is inspired by pycairo: it tries to stay close to Cairo's C API, while using MoonBit-native value types, checked CairoError suberrors, explicit stream callbacks, and GC-managed external objects for Cairo handles.

The package is intentionally native-only while the binding depends on Cairo C FFI. Module metadata declares native as the sole supported target; WebAssembly, WasmGC, JavaScript, and LLVM backends are not supported.

#Requirements

  • MoonBit with native target support.
  • Cairo 1.15.10 or newer development headers and library.
  • pkg-config that can resolve cairo.
  • Python 3 for native pre-build configuration and repository verification.

#Installation

After publication, pin it with moon add CAIMEOX/cairoon@0.2.0. The published 0.1.0 preview predates dependency-side Cairo discovery and is not recommended; until 0.2.0 is uploaded, use this exact checkout or commit in a workspace.

moon.mod registers scripts/build/cairo_config.py with MoonBit's experimental pre-build config protocol. Native builds resolve this machine's Cairo compiler and linker flags through pkg-config; the native package propagates linking to all downstream packages, so consumers must not duplicate cc-link-flags. Because dependencies execute this script, use only trusted cairoon releases.

#Example

///|
test "README quick start draws a curve" {
let surface = Surface::image(Argb32, 200, 200)
let context = Context::new(surface)
context.scale(200.0, 200.0)
context.set_line_width(0.04)
context.move_to(0.1, 0.5)
context.curve_to(0.4, 0.9, 0.6, 0.1, 0.9, 0.5)
context.stroke()
context.set_source_rgba(1.0, 0.2, 0.2, 0.6)
context.set_line_width(0.02)
context.move_to(0.1, 0.5)
context.line_to(0.4, 0.9)
context.move_to(0.6, 0.1)
context.line_to(0.9, 0.5)
context.stroke()
inspect(surface.copy_data().length() > 0, content="true")
}

#Features

  • Object-oriented MoonBit wrappers for Cairo surfaces, contexts, patterns, paths, fonts, regions, and devices.
  • Checked status handling through Status and CairoError suberrors instead of unchecked integer status returns.
  • Image surfaces, buffer-backed image surfaces, PNG file/stream I/O, MIME data, mapped images, and mutable image-data views.
  • PDF, PS, SVG, recording, tee, and script backend helpers for portable Cairo builds.
  • Solid, surface, gradient, mesh, and raster-source patterns.
  • Toy font faces, font options, scaled fonts, text extents, glyph extents, text_to_glyphs, and show_text_glyphs.
  • Executable MoonBit reference examples in this file and in the family *.mbt.md documents listed below.

#Current Stability

cairoon is suitable for light native use when the required inventory rows are marked Done, ./scripts/check-downstream-consumer.sh passes, and the exact version or commit is pinned. The complete portable API scope and all 20 pinned pycairo test families are covered, and all 579 published declarations have substantive API documentation.

Local release-candidate matrices on exact Cairo 1.15.10 and 1.18.4 pass 226/226 script tests, 841/841 native tests, 63/63 executable docs, 12/12 raw external owners with exact finalizer and 1000-iteration stress evidence, including one raw-result stress path that bans explicit release, 6/6 borrowed-reference helpers and 9/9 borrowed producer paths, 6/6 source, extracted, and unmodified cross-host archive consumer runs, all 695 byte-identical publication members, and every package under ASan/LSan/UBSan. Ubuntu 24.04 system Cairo 1.18.0 independently passes 841/841 native tests and every package under ASan/LSan/UBSan on both local arm64 and Rosetta-backed x86_64. The sole global Partial row is shipped test/release-platform evidence: GitHub run 29678818105 passed macOS native but failed both Ubuntu jobs on the prior release commit. The local fix commit still needs passing Ubuntu and macOS native jobs plus the Ubuntu ASan/LSan/UBSan job. It does not represent an unimplemented portable API family, but it must close before a full-product claim. There is still no source-compatibility promise before 1.0.

Run ./scripts/test-cairo-matrix.sh ubuntu-24.04-system without hosted CI. On Apple Silicon, use ./scripts/test-cairo-matrix.sh ubuntu-24.04-system --platform linux/amd64 --docker-context colima-cairoon-rosetta with an isolated Rosetta-backed Docker daemon.

The uppercase CAIRO_VERSION* and HAS_* constants are generated release source snapshots. When consuming the same source archive with different Cairo headers, use cairo_version() and cairo_version_string() for runtime version decisions. This build-tool limitation is part of the pre-1.0 instability contract.

Platform-specific Xlib, XCB, and Win32 surfaces are outside the first portable scope. Python-specific pycairo APIs such as CAPI, get_include(), Python file objects, pickle behavior, and legacy uppercase enum aliases are not part of the MoonBit API.

#Documentation

Additional executable reference notes are split by API family:

  • src/docs/status_and_version.mbt.md: Cairo versions, feature constants, status diagnostics, and checked suberrors.
  • src/docs/enums.mbt.md: typed enum families and raw compatibility boundaries.
  • src/docs/value_types.mbt.md: rectangles, glyphs, text clusters, and extents.
  • src/docs/matrix.mbt.md: pure-value affine transforms.
  • src/docs/surface.mbt.md: image surfaces, buffer-backed data, mapped images, PNG/MIME helpers, and checked surface errors.
  • src/docs/backend_surfaces.mbt.md: PDF/PS/SVG, recording, tee, and script backends.
  • src/docs/context.mbt.md: drawing state, transforms, paths, clips, groups, text, and checked context errors.
  • src/docs/font.mbt.md: FontOptions, FontFace, ScaledFont, text-to-glyphs, and checked font errors.
  • src/docs/path.mbt.md: typed path segments and path ownership.
  • src/docs/pattern.mbt.md: solid, surface, gradient, mesh, and raster-source patterns.
  • src/docs/region.mbt.md: Region construction, rectangle queries, boolean operations, and checked error mapping.

Packaging, CI, and release rules live in the repository PACKAGING.md. pycairo migration notes live in PORTING_FROM_PYCAIRO.md.

#Executable Smoke Tests

///|
test {
inspect(cairo_version() > 0, content="true")
inspect(cairo_version_string().contains("."), content="true")
inspect(CAIRO_VERSION > 0, content="true")
inspect(HAS_IMAGE_SURFACE, content="true")
inspect(MIME_TYPE_JPEG, content="image/jpeg")
}

///|
test {
let surface = Surface::image(Argb32, 16, 16)
let ctx = Context::new(surface)
ctx.translate(5.0, 7.0)
ctx.scale(2.0, 3.0)
ctx.set_dash([2.0, 1.0], offset=0.5)
inspect(ctx.get_dash_count(), content="2")
if CAIRO_VERSION >= 11800 {
ctx.set_hairline(true)
inspect(ctx.get_hairline(), content="true")
} else {
match run_cairo(() => ctx.set_hairline(true)) {
Err(CairoError(InvalidStatus, _)) => ()
_ => fail("expected hairline API to require Cairo 1.18")
}
}
debug_inspect(ctx.user_to_device(1.0, 1.0), content="(7, 10)")
ctx.identity_matrix()
ctx.move_to(1.0, 1.0)
ctx.rel_line_to(4.0, 0.0)
inspect(ctx.has_current_point(), content="true")
debug_inspect(ctx.get_current_point(), content="(5, 1)")
ctx.new_path()
ctx.rectangle(2.0, 2.0, 4.0, 4.0)
debug_inspect(ctx.path_extents(), content="(2, 2, 6, 6)")
debug_inspect(ctx.fill_extents(), content="(2, 2, 6, 6)")
inspect(ctx.in_fill(3.0, 3.0), content="true")
ctx.clip()
inspect(ctx.in_clip(3.0, 3.0), content="true")
inspect(ctx.in_clip(0.0, 0.0), content="false")
inspect(ctx.copy_clip_rectangle_list().length(), content="1")
}

///|
test {
let mask = Surface::image(Argb32, 1, 1)
let mask_ctx = Context::new(mask)
mask_ctx.set_source_rgba(1.0, 1.0, 1.0, 1.0)
mask_ctx.paint()

let surface = Surface::image(Argb32, 1, 1)
let ctx = Context::new(surface)
ctx.set_source_rgba(1.0, 0.0, 0.0, 1.0)
let source = ctx.get_source()
inspect(source.status().is_success(), content="true")
ctx.paint_with_alpha(0.5)
ctx.mask_surface(mask)
ctx.set_source_surface(mask)
ctx.paint()
ctx.copy_page()
ctx.show_page()
inspect(ctx.get_target().get_width(), content="1")
inspect(ctx.status().is_success(), content="true")
}

///|
test {
let surface = Surface::image(Argb32, 1, 1)
let ctx = Context::new(surface)
ctx.push_group()
ctx.set_source_rgb(1.0, 0.0, 0.0)
ctx.paint()
ctx.pop_group_to_source()
ctx.paint()
inspect(surface.copy_data()[2].to_int(), content="255")
}

///|
test {
let ctx = Context::new(Surface::image(Argb32, 1, 1))
ctx.tag_begin("foo", "")
ctx.tag_end("foo")
inspect(TAG_DEST, content="cairo.dest")
}

///|
test {
let path = "/tmp/cairoon_readme_png_roundtrip.png"
let surface = Surface::image(Argb32, 1, 1)
let ctx = Context::new(surface)
ctx.set_source_rgba(0.0, 1.0, 0.0, 0.5)
ctx.paint()
surface.write_to_png(path)
let loaded = Surface::image_from_png(path)
inspect(loaded.get_width(), content="1")
inspect(loaded.copy_data() == surface.copy_data(), content="true")
}

///|
test {
let surface = Surface::image(Argb32, 1, 1)
let jpeg = @utf8.encode("encoded-bytes")
surface.set_mime_data("image/jpeg", Some(jpeg))
match surface.get_mime_data("image/jpeg") {
Some(bytes) => inspect(bytes == jpeg, content="true")
None => fail("expected image/jpeg MIME data")
}
surface.set_mime_data("image/jpeg", None)
inspect(surface.get_mime_data("image/jpeg") is None, content="true")
}

///|
test {
let data : FixedArray[Byte] = FixedArray::make(4, b'\x00')
let surface = Surface::image_for_data(data, Argb32, 1, 1)
let ctx = Context::new(surface)
ctx.set_source_rgba(0.0, 0.0, 1.0, 1.0)
ctx.paint()
surface.flush()
inspect(data[0].to_int(), content="255")
inspect(data[1].to_int(), content="0")
inspect(data[2].to_int(), content="0")
inspect(data[3].to_int(), content="255")
}

///|
test {
let surface = Surface::image(Argb32, 4, 4)
debug_inspect(surface.get_type(), content="SurfaceTypeImage")
debug_inspect(surface.get_content(), content="ContentColorAlpha")
surface.set_device_offset(2.0, -1.0)
debug_inspect(surface.get_device_offset(), content="(2, -1)")
surface.set_device_scale(2.0, 3.0)
debug_inspect(surface.get_device_scale(), content="(2, 3)")
surface.mark_dirty_rectangle(0, 0, 2, 2)

let similar = surface.create_similar(ContentColor, 2, 2)
debug_inspect(similar.get_content(), content="ContentColor")

let image = surface.create_similar_image(Rgb24, 2, 3)
debug_inspect(image.get_type(), content="SurfaceTypeImage")
debug_inspect(image.get_format(), content="Rgb24")
inspect(image.get_height(), content="3")

let child = surface.create_for_rectangle(1.0, 1.0, 2.0, 2.0)
inspect(child.status().is_success(), content="true")
}

///|
test {
let device = Device::script("/tmp/cairoon_readme_script.cs")
debug_inspect(device.get_type(), content="DeviceTypeScript")
let acquired_type = device.with_acquired(() => device.get_type())
debug_inspect(acquired_type, content="DeviceTypeScript")

let surface = Surface::script(device, ContentColorAlpha, 4.0, 4.0)
match surface.get_device() {
Some(other) => inspect(device.equal(other), content="true")
None => fail("expected script surface device")
}
device.script_write_comment("README smoke")
device.flush()
}

///|
test {
let recording = Surface::recording(
ContentColorAlpha,
extents=Some(Rectangle::new(0.0, 0.0, 1.0, 1.0)),
)
let recorder = Context::new(recording)
recorder.set_source_rgba(1.0, 0.0, 0.0, 1.0)
recorder.paint()
match recording.recording_get_extents() {
Some(rect) => debug_inspect(rect.components(), content="(0, 0, 1, 1)")
None => fail("expected recording extents")
}
inspect(recording.recording_ink_extents().width > 0.0, content="true")

let target = Surface::image(Argb32, 1, 1)
let ctx = Context::new(target)
ctx.set_source(Pattern::for_surface(recording))
ctx.paint()
inspect(target.copy_data()[2].to_int(), content="255")
}

///|
test {
let version : SVGVersion = SvgVersion1_2
inspect(SVGVersion::supported().any(item => item == version), content="true")
inspect(version.to_string().contains("SVG"), content="true")

let surface = Surface::svg(12.0, 12.0)
surface.svg_set_document_unit(SvgUnitPx)
debug_inspect(surface.svg_get_document_unit(), content="SvgUnitPx")
surface.svg_restrict_to_version(version)
let ctx = Context::new(surface)
ctx.set_source_rgb(0.0, 0.0, 1.0)
ctx.paint()
surface.finish()
}

///|
test {
let version : PDFVersion = PdfVersion1_4
inspect(PDFVersion::supported().any(item => item == version), content="true")
inspect(version.to_string().contains("PDF"), content="true")

let surface = Surface::pdf(12.0, 12.0)
surface.pdf_restrict_to_version(version)
surface.pdf_set_metadata(PdfMetadataTitle, "Cairoon PDF")
surface.pdf_set_page_label("page one")
surface.pdf_set_thumbnail_size(2, 2)
let outline_kinds : Array[PDFOutlineFlags] = [PdfOutlineOpen, PdfOutlineBold]
let outline_flags = PDFOutlineFlagSet::combine(outline_kinds[:])
let outline_id = surface.pdf_add_outline_with_flags(
PDF_OUTLINE_ROOT,
"chapter",
"page=1",
outline_flags,
)
inspect(outline_id > PDF_OUTLINE_ROOT, content="true")
let ctx = Context::new(surface)
ctx.set_source_rgb(0.0, 0.0, 1.0)
ctx.paint()
surface.finish()
}

///|
test {
let level : PSLevel = PsLevel3
inspect(PSLevel::supported().any(item => item == level), content="true")
inspect(level.to_string().contains("PS"), content="true")

let surface = Surface::ps(12.0, 12.0)
surface.ps_set_eps(true)
inspect(surface.ps_get_eps(), content="true")
surface.ps_restrict_to_level(PsLevel2)
surface.ps_dsc_comment("%%Title: Cairoon PS")
let ctx = Context::new(surface)
ctx.set_source_rgb(0.0, 0.0, 1.0)
ctx.paint()
surface.finish()
}

///|
test {
let surface = Surface::image(Rgb24, 2, 1)
let mapped = surface.map_to_image(
extents=Some(RectangleInt::new(x=0, y=0, width=1, height=1)),
)
let ctx = Context::new_for_mapped_image(mapped)
ctx.set_source_rgb(1.0, 1.0, 1.0)
ctx.paint()
mapped.unmap()
let data = surface.copy_data()
inspect(data[0].to_int(), content="255")
inspect(data[4].to_int(), content="0")
}

///|
test {
let gradient = Pattern::linear(0.0, 0.0, 10.0, 0.0)
gradient.add_color_stop_rgb(0.0, 1.0, 0.0, 0.0)
gradient.add_color_stop_rgba(1.0, 0.0, 0.0, 1.0, 0.5)
inspect(gradient.get_color_stop_count(), content="2")
if CAIRO_VERSION >= 11800 {
gradient.set_dither(DitherGood)
debug_inspect(gradient.get_dither(), content="DitherGood")
} else {
match run_cairo(() => gradient.set_dither(DitherGood)) {
Err(CairoError(InvalidStatus, _)) => ()
_ => fail("expected dither API to require Cairo 1.18")
}
}
debug_inspect(gradient.get_linear_points(), content="(0, 0, 10, 0)")
let surface_pattern = Pattern::for_surface(Surface::image(Argb32, 2, 3))
inspect(surface_pattern.get_surface().get_height(), content="3")
}

///|
test {
let source = Surface::image(Argb32, 1, 1)
let source_ctx = Context::new(source)
source_ctx.set_source_rgba(1.0, 0.0, 0.0, 1.0)
source_ctx.paint()

let pattern = Pattern::raster_source(ContentColorAlpha, 1, 1)
pattern.raster_set_acquire(fn(_, _) { source })
match pattern.raster_get_acquire() {
Some((_, None)) => ()
_ => fail("expected raster acquire callback")
}

let target = Surface::image(Argb32, 1, 1)
let ctx = Context::new(target)
ctx.set_source(pattern)
ctx.paint()
inspect(target.copy_data()[2].to_int(), content="255")
}

///|
test {
let pattern = Pattern::mesh()
pattern.mesh_begin_patch()
pattern.mesh_move_to(0.0, 0.0)
pattern.mesh_line_to(2.0, 0.0)
pattern.mesh_line_to(0.0, 2.0)
pattern.mesh_set_corner_color_rgba(0, 1.0, 0.0, 0.0, 1.0)
pattern.mesh_set_corner_color_rgba(1, 1.0, 0.0, 0.0, 1.0)
pattern.mesh_set_corner_color_rgba(2, 1.0, 0.0, 0.0, 1.0)
pattern.mesh_end_patch()

inspect(pattern.mesh_get_patch_count(), content="1")
let path = pattern.mesh_get_path(0)
inspect(path.length() > 0, content="true")
}

///|
test {
let surface = Surface::image(Argb32, 8, 8)
let ctx = Context::new(surface)
ctx.line_to(1.0, 2.0)
ctx.line_to(2.0, 3.0)
ctx.curve_to(0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
ctx.close_path()
let path = ctx.copy_path()
inspect(path.length(), content="5")
debug_inspect(path.segments()[0].data_type(), content="PathMoveTo")
inspect(path.segments()[2].coordinates().length(), content="6")
inspect(path.to_string().contains("curve_to"), content="true")
}

///|
test {
let region = Region::from_rectangles([
RectangleInt::new(x=0, y=0, width=2, height=2),
RectangleInt::new(x=10, y=0, width=3, height=2),
])
inspect(region.num_rectangles(), content="2")
debug_inspect(
region.get_extents(),
content="{ x: 0, y: 0, width: 13, height: 2 }",
)
inspect(region.contains_point(10, 1), content="true")
}

///|
test {
let options = FontOptions::new()
options.set_antialias(AntialiasGray)
options.set_hint_style(HintStyleSlight)
debug_inspect(options.get_antialias(), content="AntialiasGray")
if CAIRO_VERSION >= 11600 {
options.set_variations(Some("wght=200"))
match options.get_variations() {
Some(variations) => inspect(variations, content="wght=200")
None => fail("expected font variations")
}
} else {
match run_cairo(() => options.set_variations(Some("wght=200"))) {
Err(CairoError(InvalidStatus, _)) => ()
_ => fail("expected variations API to require Cairo 1.16")
}
}
let copied = options.copy()
inspect(options.equal(copied), content="true")
}

///|
test {
let face = FontFace::toy(
"serif",
slant=FontSlantItalic,
weight=FontWeightBold,
)
inspect(face.get_family(), content="serif")
debug_inspect(face.get_slant(), content="FontSlantItalic")
debug_inspect(face.get_weight(), content="FontWeightBold")

let surface = Surface::image(Rgb24, 8, 8)
let ctx = Context::new(surface)
ctx.set_font_face(Some(face))
inspect(ctx.get_font_face().equal(face), content="true")
ctx.select_font_face("sans-serif")
inspect(ctx.get_font_face().get_family(), content="sans-serif")
ctx.set_font_face(None)
inspect(ctx.get_font_face().status().is_success(), content="true")
}

///|
test {
let surface = Surface::image(Rgb24, 32, 16)
let ctx = Context::new(surface)
ctx.select_font_face("serif")
ctx.set_font_size(12.0)
ctx.move_to(2.0, 12.0)
let extents = ctx.text_extents("foo")
inspect(extents.x_advance > 0.0, content="true")
ctx.show_text("foo")
let (x, _) = ctx.get_current_point()
inspect(x > 2.0, content="true")
ctx.text_path("bar")
let (x1, _, x2, _) = ctx.path_extents()
inspect(x2 > x1, content="true")
}

///|
test {
let surface = Surface::image(Rgb24, 32, 16)
let ctx = Context::new(surface)
ctx.select_font_face("serif")
ctx.set_font_size(12.0)
let glyphs = [Glyph::new(0UL, 2.0, 12.0)]
inspect(
ctx.glyph_extents(glyphs) == ctx.get_scaled_font().glyph_extents(glyphs),
content="true",
)
ctx.glyph_path(glyphs)
ctx.show_glyphs(glyphs)
let run = ctx.get_scaled_font().text_to_glyphs(2.0, 12.0, "a")
inspect(run.glyphs.length(), content="1")
let glyphs_only = ctx.get_scaled_font().text_to_glyphs_only(2.0, 12.0, "a")
inspect(glyphs_only.length(), content="1")
ctx.show_text_glyphs("a", run.glyphs, run.clusters, flags=run.flags)
}

///|
test {
let face = FontFace::toy("serif", weight=FontWeightBold)
let options = FontOptions::new()
options.set_antialias(AntialiasGray)
let scaled = ScaledFont::new(
face,
Matrix::new(xx=12.0, yy=12.0),
Matrix::new(),
options,
)
inspect(scaled.extents().height > 0.0, content="true")
inspect(scaled.text_extents("foo").x_advance > 0.0, content="true")

let surface = Surface::image(Rgb24, 8, 8)
let ctx = Context::new(surface)
ctx.set_scaled_font(scaled)
inspect(ctx.font_extents().height > 0.0, content="true")
inspect(ctx.get_scaled_font().status().is_success(), content="true")
}

#License

cairoon is available under LGPL-2.1-only OR MPL-1.1. Publication archives include COPYING, COPYING-LGPL-2.1, and COPYING-MPL-1.1 at their root.

#
Glyph

The canonical Cairo glyph value re-exported from its owning package.

This alias is the same type used by Context and ScaledFont glyph APIs.

#
CairoError

pub suberror CairoError {
CairoError(Status, String)
CairoMemoryError(Status, String)
CairoIOError(Status, String)
CairoInvalidArgument(Status, String)
} derive(
Debug
)

The checked error hierarchy raised by cairoon operations.

Every variant carries the originating Cairo status and its diagnostic message. Memory, I/O, and invalid-argument failures have dedicated variants so callers can handle those classes without inspecting strings.

#
Antialias

pub(all) enum Antialias {
AntialiasDefault
AntialiasNone
AntialiasGray
AntialiasSubpixel
AntialiasFast
AntialiasGood
AntialiasBest
} derive(Eq,
Debug
)

Controls how Cairo antialiases rasterized shapes and text.

#
ColorMode

pub(all) enum ColorMode {
ColorModeDefault
ColorModeNoColor
ColorModeColor
} derive(Eq,
Debug
)

Controls whether color glyph data may be rendered.

Color-mode support requires Cairo 1.18 or newer.

#
Content

pub(all) enum Content {
ContentColor
ContentAlpha
ContentColorAlpha
} derive(Eq,
Debug
)

Describes which color and alpha channels a surface stores.

#
Context

type Context

Owned, mutable Cairo drawing context.

Assigning this wrapper shares the same cairo_t; all aliases observe the same path and graphics state. The context retains its target wrapper and releases both the Cairo context and that retained owner when its final MoonBit wrapper becomes unreachable. Equality and hashing use Cairo pointer identity rather than drawing-state contents.
impl Eq for Context
impl Hash for Context

#
Context::append_path

fn Context::append_path(self : Context, path : Path) -> Unit raise CairoError

Append every segment of path to this context's current path.

The supplied owned snapshot is borrowed for the call: it is neither consumed nor mutated and may be reused after this method returns. The appended data updates the current point according to its final segment. Raises either the path's status or the checked context status.

#
Context::arc

fn Context::arc(self : Context, xc : Double, yc : Double, radius : Double, angle1 : Double, angle2 : Double) -> Unit raise CairoError

Add a circular arc in the direction of increasing angles.

Angles are radians in user space: zero points along positive X and, under the default transform, increasing angles run clockwise. When angle2 is below angle1, Cairo adds whole turns until it is above it. An existing current point is joined to the arc start by a line; call new_sub_path() first to avoid that join. Raises the checked context status.

#
Context::arc_negative

fn Context::arc_negative(self : Context, xc : Double, yc : Double, radius : Double, angle1 : Double, angle2 : Double) -> Unit raise CairoError

Add a circular arc in the direction of decreasing angles.

This follows the same user-space and current-point rules as arc(), but subtracts whole turns from angle2 when needed and traverses toward smaller angles. Call new_sub_path() first when the arc must not connect to the current point. Raises the checked context status.

#
Context::clip

fn Context::clip(self : Context) -> Unit raise CairoError

Intersect the current clip with the fill area of the current path.

Cairo uses the current fill rule, clears the path afterward, and can only make the clip smaller. The clip is graphics state, so pair save() and restore() for temporary restrictions. An empty path produces an empty clip. Raises the checked context status.

#
Context::clip_extents

fn Context::clip_extents(self : Context) -> (Double, Double, Double, Double) raise CairoError

Return a user-space bounding box for the area inside the current clip.

The tuple is (x1, y1, x2, y2) for the left, top, right, and bottom bounds; it bounds the clip but does not describe non-rectangular clip geometry. This query does not change the clip or path and raises the checked context status.

#
Context::clip_preserve

fn Context::clip_preserve(self : Context) -> Unit raise CairoError

Intersect the current clip with the current path while preserving the path.

Fill-rule, narrowing, and graphics-state behavior match clip(), but the path and current point remain available for later drawing or queries. Raises the checked context status.

#
Context::close_path

fn Context::close_path(self : Context) -> Unit raise CairoError

Close the current subpath with a line back to its starting point.

The resulting stroke uses a line join rather than two end caps, and the start becomes current. Cairo also exposes an explicit move segment after the close in copied paths. If no current point exists, this is a no-op. Raises the checked context status.

#
Context::copy_clip_rectangle_list

fn Context::copy_clip_rectangle_list(self : Context) -> Array[Rectangle] raise CairoError

Copy the current clip into independent user-space rectangles.

The returned array and Rectangle values are pure MoonBit data and retain no Cairo object. An empty clip returns []. If the clip cannot be expressed exactly as user-space rectangles, raises CairoError(ClipNotRepresentable, _); other Cairo failures are checked too.

#
Context::copy_page

fn Context::copy_page(self : Context) -> Unit raise CairoError

Emit the current page while retaining its contents for the next page.

This is the context convenience form of Surface::copy_page() on the target and has visible effect on backends that support multiple pages. Use show_page() to begin the next page empty. Raises the checked target/context status.

#
Context::copy_path

fn Context::copy_path(self : Context) -> Path raise CairoError

Copy the current path into an independently owned Path snapshot.

Cubic curves remain curve segments and an empty context yields a valid empty path. The result neither retains nor aliases this context and remains usable after the context leaves scope or its path changes. Raises the context or returned path status, including allocation failure.

#
Context::copy_path_flat

fn Context::copy_path_flat(self : Context) -> Path raise CairoError

Copy a line-segment approximation of the current path.

Cairo replaces every cubic curve with line segments accurate to the current tolerance; the owned result contains no curve segments. It remains usable independently of this context. Raises the context or returned path status, including allocation failure.

#
Context::curve_to

fn Context::curve_to(self : Context, x1 : Double, y1 : Double, x2 : Double, y2 : Double, x3 : Double, y3 : Double) -> Unit raise CairoError

Add a cubic Bezier segment in absolute user-space coordinates.

(x1, y1) and (x2, y2) are control points; (x3, y3) is the endpoint and becomes current. With no current point, Cairo first behaves as though move_to(x1, y1) had been called. Raises the checked context status.

#
Context::device_to_user

fn Context::device_to_user(self : Context, x : Double, y : Double) -> (Double, Double) raise CairoError

Transform device-space point (x, y) into user-space coordinates.

Cairo applies the inverse CTM, including its translation. This query does not mutate the context and raises any existing checked context status.

#
Context::device_to_user_distance

fn Context::device_to_user_distance(self : Context, dx : Double, dy : Double) -> (Double, Double) raise CairoError

Transform a device-space distance vector into user space.

Cairo applies the inverse CTM's scale, rotation, and shear while ignoring inverse translation. Use device_to_user() for positions. This query does not mutate the context and raises any existing checked context status.

#
Context::equal

fn Context::equal(self : Context, other : Context) -> Bool

Return whether two wrappers refer to the same Cairo context.

Contexts created separately for the same target are not equal. This matches the public Eq implementation and does not compare mutable drawing state.

#
Context::fill

fn Context::fill(self : Context) -> Unit raise CairoError

Fill the current path using the current fill rule and source.

Cairo implicitly closes each subpath for filling, applies the current clip and compositing operator, then clears the path and current point. Use fill_preserve() when the path is needed afterward. Raises the checked context status.

#
Context::fill_extents

fn Context::fill_extents(self : Context) -> (Double, Double, Double, Double) raise CairoError

Return the fill-ink bounds of the current path in user space.

The tuple is (x1, y1, x2, y2). Cairo applies the current fill rule, but ignores the clip and target dimensions. An empty or non-inking path returns (0.0, 0.0, 0.0, 0.0). The path is preserved. Raises the checked context status.

#
Context::fill_preserve

fn Context::fill_preserve(self : Context) -> Unit raise CairoError

Fill the current path without clearing it.

Rendering is identical to fill(), including implicit subpath closure and the current fill rule, clip, source, and operator. The path and current point remain available for later operations. Raises the checked context status.

#
Context::font_extents

fn Context::font_extents(self : Context) -> FontExtents raise CairoError

Return metrics for the context's current realized font.

The result reports ascent, descent, line height, and maximum X/Y advances in user-space units. It matches get_scaled_font().extents() for the same graphics state and does not mutate the current point. Raises the checked context status.

#
Context::get_antialias

fn Context::get_antialias(self : Context) -> Antialias raise CairoError

Return the current typed shape-antialiasing mode.

An unknown value installed through the raw API raises CairoInvalidArgument(InvalidStatus, _).

#
Context::get_antialias_raw

fn Context::get_antialias_raw(self : Context) -> Int raise CairoError

Return the exact Cairo C integer stored for shape antialiasing.

Unlike get_antialias, this preserves unknown values. Raises the checked context status before reading the value.

#
Context::get_current_point

fn Context::get_current_point(self : Context) -> (Double, Double) raise CairoError

Return the current point in user-space coordinates.

This is the final point reached by the current path. It returns (0.0, 0.0) when no point is defined; use has_current_point() to distinguish that case from a real origin. Unlike Cairo's raw C getter, this wrapper raises any existing checked context error instead of returning fallback zeros.

#
Context::get_dash

fn Context::get_dash(self : Context) -> (Array[Double], Double) raise CairoError

Return a copy of the current dash pattern and Cairo's normalized offset.

Mutating the returned array does not change the context. The array is empty when dashing is disabled. Raises the checked context status.

#
Context::get_dash_count

fn Context::get_dash_count(self : Context) -> Int raise CairoError

Return the number of entries in the current dash pattern.

Returns zero when dashing is disabled. Raises the checked context status.

#
Context::get_fill_rule

fn Context::get_fill_rule(self : Context) -> FillRule raise CairoError

Return the current typed fill rule.

The Cairo default is FillWinding. An unknown value installed through the raw API raises CairoInvalidArgument(InvalidStatus, _).

#
Context::get_fill_rule_raw

fn Context::get_fill_rule_raw(self : Context) -> Int raise CairoError

Return the exact Cairo C integer stored for the fill rule.

Unlike get_fill_rule, this preserves unknown values. Raises the checked context status before reading the value.

#
Context::get_font_face

fn Context::get_font_face(self : Context) -> FontFace raise CairoError

Return an owning wrapper for the context's current font face.

Cairo owns the borrowed result internally; cairoon acquires a reference so the returned FontFace remains valid after this context leaves scope. Raises the checked context or font-face status.

#
Context::get_font_matrix

fn Context::get_font_matrix(self : Context) -> Matrix raise CairoError

Return a pure snapshot of the current font matrix.

The matrix maps the font's unit em square from design space into user space. Later context changes do not modify the returned value. Raises the checked context status.

#
Context::get_font_options

fn Context::get_font_options(self : Context) -> FontOptions raise CairoError

Return a fresh copy of the context's explicitly configured font options.

The snapshot contains values supplied through set_font_options() but not options later derived from the target surface. Mutating the returned FontOptions does not change this context. Raises the checked context or allocation status.

#
Context::get_group_target

fn Context::get_group_target(self : Context) -> Surface raise CairoError

Return an independently retained wrapper for the current destination.

Inside a pushed group this is that group's intermediate surface; outside a group it is the original target. The wrapper retains the context as its owner and remains usable after the context binding leaves scope. Raises the checked context or surface status.

#
Context::get_hairline

fn Context::get_hairline(self : Context) -> Bool raise CairoError

Return whether hairline stroking is enabled in the current graphics state.

Requires Cairo 1.18 or newer. Older versions, or an invalid context, raise the corresponding checked CairoError.

#
Context::get_line_cap

fn Context::get_line_cap(self : Context) -> LineCap raise CairoError

Return the current typed line-cap mode.

The Cairo default is LineCapButt. An unknown value installed through the raw compatibility API raises CairoInvalidArgument(InvalidStatus, _).

#
Context::get_line_cap_raw

fn Context::get_line_cap_raw(self : Context) -> Int raise CairoError

Return the exact Cairo C integer stored for the line-cap mode.

Unlike get_line_cap, this preserves unknown values. Raises the checked context status before reading the value.

#
Context::get_line_join

fn Context::get_line_join(self : Context) -> LineJoin raise CairoError

Return the current typed line-join mode.

The Cairo default is LineJoinMiter. An unknown value installed through the raw API raises CairoInvalidArgument(InvalidStatus, _).

#
Context::get_line_join_raw

fn Context::get_line_join_raw(self : Context) -> Int raise CairoError

Return the exact Cairo C integer stored for the line-join mode.

Unlike get_line_join, this preserves unknown values. Raises the checked context status before reading the value.

#
Context::get_line_width

fn Context::get_line_width(self : Context) -> Double raise CairoError

Return the current stroke width in user-space units.

This is the stored value supplied to set_line_width; changing the current transformation does not rescale the value returned here. Raises the checked context status.

#
Context::get_matrix

fn Context::get_matrix(self : Context) -> Matrix raise CairoError

Return a pure snapshot of the current user-to-device matrix.

The returned Matrix shares no mutable state with this context. CTM changes made after the call do not alter it. Raises any existing checked context status.

#
Context::get_miter_limit

fn Context::get_miter_limit(self : Context) -> Double raise CairoError

Return the current miter-length to line-width ratio limit.

Cairo's default is 10.0. Raises the checked context status.

#
Context::get_operator

fn Context::get_operator(self : Context) -> Operator raise CairoError

Return the current typed compositing operator.

The Cairo default is OperatorOver. An unknown value installed through the raw API raises CairoInvalidArgument(InvalidStatus, _).

#
Context::get_operator_raw

fn Context::get_operator_raw(self : Context) -> Int raise CairoError

Return the exact Cairo C integer stored for the compositing operator.

Unlike get_operator, this preserves unknown values. Raises the checked context status before reading the value.

#
Context::get_scaled_font

fn Context::get_scaled_font(self : Context) -> ScaledFont raise CairoError

Return an owning wrapper for the context's current realized scaled font.

The result captures the active font face, font matrix, CTM, and font options used for rendering. cairoon acquires a Cairo reference so it remains valid after the context leaves scope. Raises the checked context or scaled-font status.

#
Context::get_source

fn Context::get_source(self : Context) -> Pattern raise CairoError

Return an owned wrapper around the current source pattern reference.

This is not a deep copy: it refers to the same Cairo pattern currently used by the context. The wrapper remains usable after the context leaves scope or a different source is installed. Raises the checked context/pattern status.

#
Context::get_target

fn Context::get_target(self : Context) -> Surface raise CairoError

Return an independently retained wrapper for the original target surface.

Group redirection does not change this result; use get_group_target() for the current destination. The returned wrapper remains usable after the original surface binding or this context leaves scope. Raises the checked context or target status.

#
Context::get_tolerance

fn Context::get_tolerance(self : Context) -> Double raise CairoError

Return the current curve-flattening tolerance in device-space units.

Cairo's default is 0.1. Raises the checked context status.

#
Context::glyph_extents

Measure explicitly positioned glyphs with the current font state.

The result bounds the ink in user space and reports glyph-run advances; whitespace glyphs may advance without adding ink. An empty view returns zero extents. cairoon copies the fields into temporary C storage for the call and retains no array data. Raises the checked context status.

#
Context::glyph_path

fn Context::glyph_path(self : Context, glyphs : ArrayView[
Glyph
]) -> Unit raise CairoError

Append closed outlines for explicitly positioned glyphs to the path.

Filling the outlines produces an effect similar to show_glyphs(). An empty view is a no-op. Glyph fields are copied into temporary C storage and are not retained after the call. Raises the checked context status.

#
Context::has_current_point

fn Context::has_current_point(self : Context) -> Bool raise CairoError

Return whether the current path has a defined current point.

new_path() and new_sub_path() make this false; most path construction methods define a new point. Raises any existing checked context status.

#
Context::hash

fn Context::hash(self : Context) -> UInt64

Return the pointer-identity hash of this Cairo context.

Equal contexts produce the same value, which remains stable for the context's lifetime. This is the value used by the public Hash trait.

#
Context::identity_matrix

fn Context::identity_matrix(self : Context) -> Unit raise CairoError

Reset the CTM so user space and device space coincide.

Afterward one user-space unit maps to one device-space unit and the origins align. This CTM change can be undone by a matching restore() when made inside saved graphics state. Raises the checked context status.

#
Context::in_clip

fn Context::in_clip(self : Context, x : Double, y : Double) -> Bool raise CairoError

Test whether (x, y) lies in the current visible clip area.

Coordinates are in current user space. A true result means a full-surface paint() could affect that point; it does not inspect the current path. This query has no side effects and raises the checked context status.

#
Context::in_fill

fn Context::in_fill(self : Context, x : Double, y : Double) -> Bool raise CairoError

Test whether (x, y) lies in the current path's fill area.

Cairo applies the current fill rule but deliberately ignores the clip and target dimensions. Coordinates are in user space. The path is preserved and any existing context error is raised.

#
Context::in_stroke

fn Context::in_stroke(self : Context, x : Double, y : Double) -> Bool raise CairoError

Test whether (x, y) lies in the current path's stroke area.

Cairo applies current line width, joins, caps, dashes, and related stroke state, but ignores the clip and target dimensions. Coordinates are in user space. The path is preserved and any existing context error is raised.

#
Context::line_to

fn Context::line_to(self : Context, x : Double, y : Double) -> Unit raise CairoError

Add a straight segment from the current point to (x, y).

Coordinates are in the current user space and the endpoint becomes current. If no current point exists, Cairo treats this as move_to(x, y). Raises the checked context status.

#
Context::mask

fn Context::mask(self : Context, pattern : Pattern) -> Unit raise CairoError

Paint the current source through the alpha channel of pattern.

Opaque mask locations receive the source and transparent locations do not; the mask's color channels are ignored. The current path is unaffected. Raises a checked status from either the context or mask pattern.

#
Context::mask_surface

fn Context::mask_surface(self : Context, surface : Surface, x? : Double, y? : Double) -> Unit raise CairoError

Paint the current source through surface as an alpha mask.

The mask surface origin appears at user-space (x, y), with both coordinates defaulting to 0.0. This is the immediate drawing equivalent of masking with a temporary surface pattern and does not consume the current path. Raises a checked status from either object.

#
Context::move_to

fn Context::move_to(self : Context, x : Double, y : Double) -> Unit raise CairoError

Begin a new subpath at (x, y) in the current user space.

No segment connects the previous current point to this one. On success the new point is available from get_current_point(). Raises the checked context status.

#
Context::new

fn Context::new(target : Surface) -> Context raise CairoError

Create a fresh context that draws to target.

Cairo initializes the graphics state to its defaults. The new context retains target, including any MoonBit buffers or stream callbacks owned by it, so the original surface binding may leave scope first. Raises the target or newly created context status, including allocation failures.

#
Context::new_for_mapped_image

fn Context::new_for_mapped_image(target : MappedImageSurface) -> Context raise CairoError

Create a context that draws into a currently mapped image view.

The context retains target, preventing implicit finalizer unmapping while it is live. Finish all drawing before explicitly unmapping the view; using this constructor inside MappedImageSurface::with_unmapped is the scoped form. Raises CairoError(SurfaceFinished, _) if the view was already unmapped, or the mapped surface/context status on other failures.

#
Context::new_path

fn Context::new_path(self : Context) -> Unit raise CairoError

Clear every subpath and unset the current point.

This does not draw anything. It is also unnecessary after non-preserving fill() or stroke(), which clear the path themselves. Raises the checked context status.

#
Context::new_sub_path

fn Context::new_sub_path(self : Context) -> Unit raise CairoError

End the current subpath without clearing existing path geometry.

The current point becomes undefined, so the next absolute path operation starts a disconnected subpath. This is especially useful before arc() or arc_negative() when no connecting line is wanted. Raises the checked context status.

#
Context::paint

fn Context::paint(self : Context) -> Unit raise CairoError

Paint the current source everywhere inside the current clip.

Compositing uses the current operator and source attributes. This operation does not consume the current path. Raises the checked context status.

#
Context::paint_with_alpha

fn Context::paint_with_alpha(self : Context, alpha : Double) -> Unit raise CairoError

Paint the current source inside the clip through a constant-alpha mask.

alpha ranges from 0.0 for fully transparent to 1.0 for fully opaque; the effect otherwise matches paint(). The source and current path remain installed. Raises the checked context status.

#
Context::path_extents

fn Context::path_extents(self : Context) -> (Double, Double, Double, Double) raise CairoError

Return geometric bounds for points on the current path in user space.

Stroke state, fill rule, clipping, and target dimensions are ignored. An empty path or lone move_to returns zero extents, while even a degenerate line segment contributes. This is generally cheaper than precise fill or stroke bounds and preserves the path. Raises the checked context status.

#
Context::pop_group

fn Context::pop_group(self : Context) -> Pattern raise CairoError

Finish the current group and return its pixels as an owned surface pattern.

Cairo restores the graphics state saved by the matching push. This method does not install the pattern as the source; use set_source or call pop_group_to_source() instead. An unmatched pop raises CairoError(InvalidPopGroup, _).

#
Context::pop_group_to_source

fn Context::pop_group_to_source(self : Context) -> Unit raise CairoError

Finish the current group and install its result as the current source.

This is equivalent to pop_group(), set_source(pattern), and releasing the temporary pattern. Cairo restores the state saved by the matching push before installing that source. An unmatched pop raises CairoError(InvalidPopGroup, _).

#
Context::push_group

fn Context::push_group(self : Context) -> Unit raise CairoError

Redirect subsequent drawing to a color-and-alpha intermediate group.

Groups may be nested. Cairo implicitly saves the graphics state here; a matching pop_group() or pop_group_to_source() restores it and exposes the rendered group as a pattern. Raises the checked context status.

#
Context::push_group_with_content

fn Context::push_group_with_content(self : Context, content : Content) -> Unit raise CairoError

Redirect drawing to an intermediate group with typed content.

This has the same nesting and implicit save/restore behavior as push_group(), but controls whether the intermediate surface stores color, alpha, or both. Raises the checked context status.

#
Context::push_group_with_content_raw

fn Context::push_group_with_content_raw(self : Context, content : Int) -> Unit raise CairoError

Push a group using a Cairo C integer content value.

This pycairo compatibility entry point accepts exactly 0x1000 (color), 0x2000 (alpha), or 0x3000 (color and alpha). Any other value raises CairoInvalidArgument(InvalidContent, _) before entering Cairo.

#
Context::rectangle

fn Context::rectangle(self : Context, x : Double, y : Double, width : Double, height : Double) -> Unit raise CairoError

Add a closed rectangular subpath in user-space coordinates.

Its opposite corners are (x, y) and (x + width, y + height); signed widths and heights therefore select direction as well as size. Cairo closes the subpath and leaves (x, y) as the current point. Raises the checked context status.

#
Context::rel_curve_to

fn Context::rel_curve_to(self : Context, dx1 : Double, dy1 : Double, dx2 : Double, dy2 : Double, dx3 : Double, dy3 : Double) -> Unit raise CairoError

Add a cubic Bezier segment using offsets from the current point.

The two control points and endpoint are respectively offset by (dx1, dy1), (dx2, dy2), and (dx3, dy3). If no current point exists, raises CairoError(NoCurrentPoint, _) and makes that status sticky.

#
Context::rel_line_to

fn Context::rel_line_to(self : Context, dx : Double, dy : Double) -> Unit raise CairoError

Add a straight segment ending at an offset from the current point.

Given current point (x, y), the endpoint is (x + dx, y + dy) in user space. If no current point exists, raises CairoError(NoCurrentPoint, _) and makes that status sticky.

#
Context::rel_move_to

fn Context::rel_move_to(self : Context, dx : Double, dy : Double) -> Unit raise CairoError

Begin a new subpath at an offset from the current point.

Given current point (x, y), this is move_to(x + dx, y + dy) in user space. If no current point exists, raises CairoError(NoCurrentPoint, _) and puts the context into Cairo's sticky error state.

#
Context::reset_clip

fn Context::reset_clip(self : Context) -> Unit raise CairoError

Replace the current clip with Cairo's original unrestricted target clip.

This can discard restrictions installed by callers. Reusable drawing code should normally put temporary clips inside save()/restore() instead. The current path is unchanged. Raises the checked context status.

#
Context::restore

fn Context::restore(self : Context) -> Unit raise CairoError

Restore and remove the most recently saved graphics state.

The current path is unchanged. Calling this without a matching save() raises CairoError(InvalidRestore, _) and leaves the context in Cairo's sticky error state.

#
Context::rotate

fn Context::rotate(self : Context, radians : Double) -> Unit raise CairoError

Rotate the user-space axes by radians.

Positive angles rotate from positive X toward positive Y, which appears clockwise with Cairo's default downward-pointing Y axis. Rotation is added after the existing user-space transformation. Raises the checked context status.

#
Context::save

fn Context::save(self : Context) -> Unit raise CairoError

Push a copy of the current graphics state onto Cairo's save stack.

Saves can be nested and are paired with restore(). The current path is not part of the graphics state and is therefore not copied. Raises the checked context status.

#
Context::scale

fn Context::scale(self : Context, sx : Double, sy : Double) -> Unit raise CairoError

Scale the user-space X and Y axes by sx and sy.

The scale is added after the context's existing user-space transformation; the CTM remains part of save/restore graphics state. A scale that makes the CTM non-invertible raises CairoInvalidArgument(InvalidMatrix, _) and makes that Cairo status sticky.

#
Context::select_font_face

fn Context::select_font_face(self : Context, family : String, slant? : FontSlant, weight? : FontWeight) -> Unit raise CairoError

Select a font through Cairo's simplified toy-text API.

slant and weight default to their normal typed variants. This is useful for simple text but does not perform application-grade font discovery or shaping. family is encoded as UTF-8; an embedded NUL raises CairoInvalidArgument(InvalidString, _). Other failures raise the checked context status.

#
Context::select_font_face_raw

fn Context::select_font_face_raw(self : Context, family : String, slant? : Int, weight? : Int) -> Unit raise CairoError

Select a toy font using pycairo-compatible raw C enum integers.

Prefer select_font_face() for typed code. Known values match FontSlant and FontWeight; Cairo maps unsupported values to InvalidSlant or InvalidWeight. The UTF-8 family name rejects embedded NUL bytes before the FFI call. Raises the checked context status.

#
Context::set_antialias

fn Context::set_antialias(self : Context, antialias : Antialias) -> Unit raise CairoError

Set the typed antialiasing mode for shapes drawn by this context.

This does not configure text-specific antialiasing in FontOptions. The mode is part of the current graphics state. Raises the checked context status.

#
Context::set_antialias_raw

fn Context::set_antialias_raw(self : Context, antialias : Int) -> Unit raise CairoError

Set shape antialiasing from an unvalidated Cairo C integer.

Unknown values remain observable through get_antialias_raw; the typed getter rejects them with CairoInvalidArgument(InvalidStatus, _). Raises the checked context status.

#
Context::set_dash

fn Context::set_dash(self : Context, dashes : ArrayView[Double], offset? : Double) -> Unit raise CairoError

Set the alternating on/off pattern used by later stroke operations.

Cairo copies dashes; it does not retain the MoonBit view. Lengths are user-space values interpreted at stroke time. An empty view disables dashing, and one value produces equal on/off lengths. In a non-empty pattern, values must be non-negative with at least one positive value; otherwise this raises CairoInvalidArgument(InvalidDash, _). Cairo normalizes offset.

#
Context::set_fill_rule

fn Context::set_fill_rule(self : Context, fill_rule : FillRule) -> Unit raise CairoError

Set the typed rule used to determine which path regions are inside.

The rule affects both fill operations and clipping and is stored in the current graphics state. Raises the checked context status.

#
Context::set_fill_rule_raw

fn Context::set_fill_rule_raw(self : Context, fill_rule : Int) -> Unit raise CairoError

Set the fill rule from an unvalidated Cairo C integer.

Unknown values remain observable through get_fill_rule_raw; the typed getter rejects them with CairoInvalidArgument(InvalidStatus, _). Raises the checked context status.

#
Context::set_font_face

fn Context::set_font_face(self : Context, font_face : FontFace?) -> Unit raise CairoError

Replace the current font face, or restore Cairo's default with None.

For Some(face), the context retains its own Cairo reference and the caller may release its wrapper independently. Installing a face invalidates the previously realized scaled-font state. Raises a checked status from either object.

#
Context::set_font_matrix

fn Context::set_font_matrix(self : Context, matrix : Matrix) -> Unit raise CairoError

Replace the design-space-to-user-space transformation for the current font.

The matrix is copied. It may express scaling, shear, rotation, translation, or non-uniform stretching; set_font_size() is the simple uniform-scale form. Raises the checked context status.

#
Context::set_font_options

fn Context::set_font_options(self : Context, options : FontOptions) -> Unit raise CairoError

Set the custom font rendering options used by this context.

Cairo copies the values at this call. Later mutations of options do not affect the context. Default-valued fields are merged with target-surface options when a scaled font is realized. Raises a checked status from either object.

#
Context::set_font_size

fn Context::set_font_size(self : Context, size : Double) -> Unit raise CairoError

Set a uniform font size in user-space units.

This replaces the current font matrix with an X/Y scale by size; it does not compose with a matrix installed earlier. Use set_font_matrix() for non-uniform or sheared text. Raises the checked context status.

#
Context::set_hairline

fn Context::set_hairline(self : Context, set_hairline : Bool) -> Unit raise CairoError

Enable or disable Cairo hairline stroking.

A hairline uses the thinnest stroke the target can represent, including a native hairline where a vector backend supports one. It is a graphics-state setting distinct from choosing a small line width. Requires Cairo 1.18 or newer; older versions raise CairoError(InvalidStatus, _).

#
Context::set_line_cap

fn Context::set_line_cap(self : Context, cap : LineCap) -> Unit raise CairoError

Set the typed shape used at the ends of open subpaths when stroking.

Cairo reads this graphics-state value at stroke time, not while the path is constructed. Raises the checked context status.

#
Context::set_line_cap_raw

fn Context::set_line_cap_raw(self : Context, cap : Int) -> Unit raise CairoError

Set the line-cap mode from an unvalidated Cairo C integer.

This pycairo compatibility entry point preserves unknown values; a later typed getter rejects them with CairoInvalidArgument(InvalidStatus, _). Raises the checked context status.

#
Context::set_line_join

fn Context::set_line_join(self : Context, join : LineJoin) -> Unit raise CairoError

Set the typed shape used to join connected stroke segments.

Cairo reads this graphics-state value at stroke time. Miter joins are also constrained by set_miter_limit. Raises the checked context status.

#
Context::set_line_join_raw

fn Context::set_line_join_raw(self : Context, join : Int) -> Unit raise CairoError

Set the line-join mode from an unvalidated Cairo C integer.

Unknown values remain observable through get_line_join_raw; the typed getter rejects them with CairoInvalidArgument(InvalidStatus, _). Raises the checked context status.

#
Context::set_line_width

fn Context::set_line_width(self : Context, width : Double) -> Unit raise CairoError

Set the diameter of the pen used by later stroke operations.

width is measured in user-space units and interpreted with the current transformation at stroke time. It is part of the current graphics state, so save() and restore() preserve it. Raises the checked context status.

#
Context::set_matrix

fn Context::set_matrix(self : Context, matrix : Matrix) -> Unit raise CairoError

Replace the current user-to-device transformation with matrix.

No composition with the previous CTM occurs. The value is copied, so later use of the pure Matrix cannot change this context. A non-invertible matrix raises CairoInvalidArgument(InvalidMatrix, _) and makes that status sticky.

#
Context::set_miter_limit

fn Context::set_miter_limit(self : Context, limit : Double) -> Unit raise CairoError

Set the maximum miter-length to line-width ratio for miter joins.

When the ratio needed by a join exceeds limit, Cairo uses a bevel join instead. This setting matters only with LineJoinMiter and is stored in the current graphics state. Raises the checked context status.

#
Context::set_operator

fn Context::set_operator(self : Context, operator : Operator) -> Unit raise CairoError

Set the typed compositing operator used by subsequent drawing operations.

The operator controls how source and destination pixels are combined and is part of the current graphics state. Raises the checked context status.

#
Context::set_operator_raw

fn Context::set_operator_raw(self : Context, operator : Int) -> Unit raise CairoError

Set the compositing operator from an unvalidated Cairo C integer.

Unknown values remain observable through get_operator_raw; the typed getter rejects them with CairoInvalidArgument(InvalidStatus, _). Raises the checked context status.

#
Context::set_scaled_font

fn Context::set_scaled_font(self : Context, scaled_font : ScaledFont) -> Unit raise CairoError

Install scaled_font as the complete current font state.

This replaces the context's font face, font matrix, and font options, and the context retains its own Cairo reference. Except for translation, the context CTM should match scaled_font.get_ctm() for consistent rendering. Raises a checked status from either object.

#
Context::set_source

fn Context::set_source(self : Context, pattern : Pattern) -> Unit raise CairoError

Install pattern as the source for subsequent drawing operations.

The context retains its own Cairo reference to the pattern. Its transformation is locked to the user space in effect at this call, so later CTM changes do not move the source. Raises a checked status from either the context or pattern.

#
Context::set_source_rgb

fn Context::set_source_rgb(self : Context, red : Double, green : Double, blue : Double) -> Unit raise CairoError

Set the current source to the opaque color (red, green, blue).

Each component is clamped to the inclusive range from 0.0 to 1.0. The resulting solid pattern remains the source for later drawing operations until another source is installed. Raises the checked context status.

#
Context::set_source_rgba

fn Context::set_source_rgba(self : Context, red : Double, green : Double, blue : Double, alpha : Double) -> Unit raise CairoError

Set the current source to the color (red, green, blue, alpha).

All four components are clamped to the inclusive range from 0.0 to 1.0. The resulting solid pattern remains the source for later drawing operations until another source is installed. Raises the checked context status.

#
Context::set_source_surface

fn Context::set_source_surface(self : Context, surface : Surface, x? : Double, y? : Double) -> Unit raise CairoError

Use surface as a source whose origin appears at user-space (x, y).

Both coordinates default to 0.0. This creates and installs a surface pattern with Cairo's default pattern attributes; retrieve it with get_source() to adjust those attributes. The context keeps the source surface alive and locks it to the current user space. Raises a checked status from either object.

#
Context::set_tolerance

fn Context::set_tolerance(self : Context, tolerance : Double) -> Unit raise CairoError

Set Cairo's curve-flattening tolerance in device-space units.

The tolerance bounds the permitted error when curves are approximated for rendering: larger values can be faster and less accurate, while smaller values can be slower and more accurate. Raises the checked context status.

#
Context::show_glyphs

fn Context::show_glyphs(self : Context, glyphs : ArrayView[
Glyph
]) -> Unit raise CairoError

Draw explicitly positioned glyphs using the current font and paint state.

Unlike the toy show_text() API, each Glyph supplies its own glyph index and user-space position. The current path and current point are unaffected; an empty view is accepted. Input fields are copied for the call and not retained. Raises the checked context status.

#
Context::show_page

fn Context::show_page(self : Context) -> Unit raise CairoError

Emit the current page and clear it before the next page begins.

This is the context convenience form of Surface::show_page() on the target and has visible effect on backends that support multiple pages. Use copy_page() when page contents should carry forward. Raises the checked target/context status.

#
Context::show_text

fn Context::show_text(self : Context, text : String) -> Unit raise CairoError

Draw UTF-8 text with Cairo's toy-text shaping and advance the current point.

The first glyph starts at the current point; afterward that point moves to where the next glyph would begin. The current path is otherwise unchanged. Embedded NUL bytes raise CairoInvalidArgument(InvalidString, _) before the FFI call. Raises other checked drawing statuses normally.

#
Context::show_text_glyphs

fn Context::show_text_glyphs(self : Context, text : String, glyphs : ArrayView[
Glyph
], clusters : ArrayView[TextCluster], flags? : TextClusterFlags) -> Unit raise CairoError

Draw glyphs while associating them with their original UTF-8 text.

Rendering matches show_glyphs(). Targets with text-glyph support can also embed selectable/searchable text using clusters; otherwise Cairo ignores the metadata. Clusters must collectively cover every UTF-8 byte and glyph, with TextClusterBackward mapping glyphs from end to start. Invalid coverage raises CairoError(InvalidClusters, _), and embedded NUL bytes raise CairoInvalidArgument(InvalidString, _). Input arrays are not retained.

#
Context::status

fn Context::status(self : Context) -> Status

Return this context's sticky Cairo status without raising it.

Public operations normally check and raise their resulting status, but backends can report some errors later, such as when a page is committed. Once Cairo records an error, later checked operations report that error too.

#
Context::stroke

fn Context::stroke(self : Context) -> Unit raise CairoError

Stroke the current path using the active stroke and source state.

Line width, joins, caps, dashes, clip, and compositing operator all participate. After rendering, Cairo clears the path and current point. Use stroke_preserve() to keep them. Raises the checked context status.

#
Context::stroke_extents

fn Context::stroke_extents(self : Context) -> (Double, Double, Double, Double) raise CairoError

Return the stroke-ink bounds of the current path in user space.

The tuple is (x1, y1, x2, y2). Line width, joins, caps, dashes, and other stroke state are applied, while clipping and target dimensions are ignored. An empty path yields (0.0, 0.0, 0.0, 0.0). The path is preserved. Raises the checked context status.

#
Context::stroke_preserve

fn Context::stroke_preserve(self : Context) -> Unit raise CairoError

Stroke the current path without clearing it.

Rendering is identical to stroke(), using the active line, source, clip, and compositing state, while preserving the path and current point for later operations. Raises the checked context status.

#
Context::tag_begin

fn Context::tag_begin(self : Context, tag_name : String, attributes : String) -> Unit raise CairoError

Begin a tagged drawing range for links or document structure.

attributes uses Cairo's key=value syntax; pass "" when none are needed. Close the range with tag_end using the same name. Both strings are UTF-8 encoded, and embedded NUL bytes raise CairoInvalidArgument(InvalidString, _) before FFI. Invalid attributes or nesting can raise CairoError(TagError, _) immediately or on a later page commit, depending on the Cairo backend and version.

#
Context::tag_end

fn Context::tag_end(self : Context, tag_name : String) -> Unit raise CairoError

End the innermost tagged range with matching tag_name.

The name is UTF-8 encoded; an embedded NUL raises CairoInvalidArgument(InvalidString, _) before FFI. Invalid or mismatched nesting can surface as CairoError(TagError, _) here or during a later page commit.

#
Context::text_extents

fn Context::text_extents(self : Context, text : String) -> TextExtents raise CairoError

Measure UTF-8 text using the current font state.

The returned TextExtents bounds the ink in user space and separately reports the advance that show_text() would apply. Whitespace can affect advances without contributing ink. This query does not move the current point. Embedded NUL bytes raise CairoInvalidArgument(InvalidString, _).

#
Context::text_path

fn Context::text_path(self : Context, text : String) -> Unit raise CairoError

Append closed outlines for UTF-8 toy-text glyphs to the current path.

Filling the resulting path approximates show_text() while allowing normal path transforms and paint operations. The current point advances as it does for show_text(). Embedded NUL bytes raise CairoInvalidArgument(InvalidString, _); other failures use the checked context status.

#
Context::transform

fn Context::transform(self : Context, matrix : Matrix) -> Unit raise CairoError

Apply matrix as an additional transformation of user space.

Unlike set_matrix(), this composes with the current CTM; Cairo applies the new transformation after the existing one. If the result is not invertible, raises CairoInvalidArgument(InvalidMatrix, _) and makes that status sticky.

#
Context::translate

fn Context::translate(self : Context, tx : Double, ty : Double) -> Unit raise CairoError

Translate the user-space origin by (tx, ty).

The offset is interpreted through the CTM that existed before this call, so translation is added after the existing user-space transformation. The CTM is part of save/restore graphics state. Raises the checked context status.

#
Context::user_to_device

fn Context::user_to_device(self : Context, x : Double, y : Double) -> (Double, Double) raise CairoError

Transform user-space point (x, y) into device-space coordinates.

The full CTM is applied, including translation. This query does not mutate the input values or context and raises any existing checked context status.

#
Context::user_to_device_distance

fn Context::user_to_device_distance(self : Context, dx : Double, dy : Double) -> (Double, Double) raise CairoError

Transform a user-space distance vector into device space.

Scale, rotation, and shear are applied, but CTM translation is deliberately ignored. Use user_to_device() for positions. This query does not mutate the context and raises any existing checked context status.

#
Device

type Device

An owning facade for a Cairo rendering device.

A Device has pointer identity and holds one internal RawDevice owner. The raw owner's finalizer calls cairo_device_destroy; this facade adds no second finalizer. Devices obtained independently for the same native object compare equal and may outlive the surface from which they were obtained.
impl Eq for Device
impl Hash for Device

#
Device::acquire

fn Device::acquire(self : Device) -> Unit raise CairoError

Acquire exclusive access to the device for the current thread.

The call blocks while another thread owns the device. Recursive acquisition by the same thread is allowed, but every successful call requires exactly one matching release(). Do not hold two different devices unless their backends explicitly permit it, and do not call Cairo operations that may acquire a device while this lock is held. Acquisition failures raise their checked Cairo status.

#
Device::equal

fn Device::equal(self : Device, other : Device) -> Bool

Test whether two wrappers refer to the same native Cairo device.

This is pointer identity, not structural or output-content equality. It is consistent with the Eq implementation and with hash().

#
Device::finish

fn Device::finish(self : Device) -> Unit raise CairoError

Finish the device and release all external resources it controls.

Cairo also finishes surfaces, fonts, and other objects created for this device. Later operations have no effect and can report DeviceFinished. The wrapper remains owned and its finalizer will still destroy the native reference. Cairoon always attempts the native finish even after a sticky device error, then raises the resulting checked status. This call may acquire the device and must not be made while it is manually acquired.

#
Device::flush

fn Device::flush(self : Device) -> Unit raise CairoError

Complete pending Cairo work and restore the underlying device state.

Call this before switching from Cairo rendering to direct backend-native access; it is a no-op for devices without such access. Failures raise the checked device status. Cairo may acquire the device internally, so do not call this while holding a manual acquisition.

#
Device::get_type

fn Device::get_type(self : Device) -> DeviceType raise CairoError

Return the backend type of this device.

Script constructors return DeviceTypeScript; devices obtained from other surfaces may report another supported backend. A device error is raised through CairoError, and an unknown future raw type raises CairoInvalidArgument(InvalidStatus, _) rather than being guessed.

#
Device::hash

fn Device::hash(self : Device) -> UInt64

Return a stable identity hash for this native device.

Wrappers that compare equal produce the same hash. The value identifies the native pointer only for its lifetime and must not be persisted as a resource identifier.

#
Device::release

fn Device::release(self : Device) -> Unit raise CairoError

Release one successful acquisition made by the current thread.

Calling this without a matching acquire() violates Cairo's contract. Cairoon invokes the native release even when the device has a sticky error, so lock cleanup cannot be skipped, and then raises that current status if it is not Success.

#
Device::script

fn Device::script(path : String) -> Device raise CairoError

Create a script device that writes Cairo's replayable script to path.

The returned device owns the native handle. Call finish() to complete the output deterministically; eventual finalization also destroys the handle. path is UTF-8 and an embedded NUL raises CairoInvalidArgument(InvalidString, _). A missing script backend or file creation failure raises the corresponding checked Cairo status.

#
Device::script_from_recording_surface

fn Device::script_from_recording_surface(self : Device, surface : Surface) -> Unit raise CairoError

Convert all recorded operations in surface into this device's script.

surface must have SurfaceTypeRecording; another valid surface raises CairoError(SurfaceTypeMismatch, _). Both arguments are borrowed only for this synchronous replay. Device, surface, stream, and allocation failures use the normal checked CairoError mapping.

#
Device::script_get_mode

fn Device::script_get_mode(self : Device) -> ScriptMode raise CairoError

Return the current output mode of a script device.

Newly created script devices default to ScriptModeAscii. Calling this on another backend raises CairoError(DeviceTypeMismatch, _); other device failures are mapped through the checked status hierarchy.

#
Device::script_set_mode

fn Device::script_set_mode(self : Device, mode : ScriptMode) -> Unit raise CairoError

Select readable ASCII or byte-coded binary output for a script device.

The mode affects subsequently emitted script data. A non-script device raises CairoError(DeviceTypeMismatch, _), and output failures raise their checked device status.

#
Device::script_stream

fn Device::script_stream(writer : (Bytes) -> Status) -> Device raise CairoError

Create a script device that sends output chunks to writer.

Cairoon retains the closure until the native device is destroyed. Each callback receives a fresh MoonBit-owned Bytes copy, so it may safely keep the chunk after returning. The writer must return Success; a valid error status is reported by the Cairo operation that emits it, while LastStatus or any out-of-range callback result is normalized to WriteError. Call finish() to force all buffered output through the callback.

#
Device::script_write_comment

fn Device::script_write_comment(self : Device, comment : String) -> Unit raise CairoError

Emit comment verbatim into a script device's output.

The MoonBit string is encoded as UTF-8. Embedded NUL bytes raise CairoInvalidArgument(InvalidString, _) before the FFI call. Use flush() or finish() when the comment must already be visible to a file or stream. A non-script device raises CairoError(DeviceTypeMismatch, _).

#
Device::status

fn Device::status(self : Device) -> Status

Return the device's current sticky Cairo status without raising.

Success means no device error has been recorded. Once Cairo records an error, later status queries normally return the same value. An unknown raw status from the native boundary is represented as InvalidStatus.

#
Device::with_acquired

fn[T] Device::with_acquired(self : Device, f : () -> T raise CairoError) -> T raise CairoError

Run f while this thread owns the device, then release it exactly once.

Acquisition failure prevents f from running. On success, a release error is reported normally. If f raises, cairoon still performs a best-effort raw release and re-raises the original closure error, even if the device is already in a sticky error state. The closure must obey acquire()'s deadlock restrictions and avoid Cairo calls that may acquire devices.

#
Device::with_finished

fn[T] Device::with_finished(self : Device, f : () -> T raise CairoError) -> T raise CairoError

Run f, then finish this device on both success and error paths.

If f succeeds, a finish failure is raised and otherwise its value is returned. If f raises, cairoon still attempts the native finish but preserves and re-raises the original closure error even when cleanup also reports a sticky status. This is the deterministic-output counterpart to a pycairo device context manager.

#
DeviceType

pub(all) enum DeviceType {
DeviceTypeDrm
DeviceTypeGl
DeviceTypeScript
DeviceTypeXcb
DeviceTypeXlib
DeviceTypeXml
DeviceTypeCogl
DeviceTypeWin32
} derive(Eq,
Debug
)

Identifies the backend that owns a Cairo device.

#
Dither

pub(all) enum Dither {
DitherNone
DitherDefault
DitherFast
DitherGood
DitherBest
} derive(Eq,
Debug
)

Selects the quality/performance tradeoff for pattern dithering.

Dither state requires Cairo 1.18 or newer.

#
Extend

pub(all) enum Extend {
ExtendNone
Repeat
Reflect
Pad
} derive(Eq,
Debug
)

Controls how a pattern samples outside its natural bounds.

#
FillRule

pub(all) enum FillRule {
FillWinding
FillEvenOdd
} derive(Eq,
Debug
)

Selects the winding or even-odd rule used to fill a path.

#
Filter

pub(all) enum Filter {
Fast
Good
Best
Nearest
Bilinear
Gaussian
} derive(Eq,
Debug
)

Selects the sampling filter used when reading from a pattern.

#
FontExtents

pub struct FontExtents {
ascent : Double
descent : Double
height : Double
max_x_advance : Double
max_y_advance : Double
} derive(Eq, Hash,
Debug
)

User-space line metrics for a scaled font.

Ascent and descent extend above and below the baseline; height is the recommended baseline spacing; maximum advances bound glyph-origin motion.

#
FontExtents::component

fn FontExtents::component(self : FontExtents, index : Int) -> Double raise CairoError

Return metric 0..4 in pycairo tuple order.

Raises CairoInvalidArgument(InvalidIndex, _) for any other index.

#
FontExtents::components

fn FontExtents::components(self : FontExtents) -> (Double, Double, Double, Double, Double)

Return (ascent, descent, height, max_x_advance, max_y_advance).

#
FontExtents::new

fn FontExtents::new(ascent : Double, descent : Double, height : Double, max_x_advance : Double, max_y_advance : Double) -> FontExtents

Construct font extents from five explicit metric values.

This pure constructor performs no metric validation.

#
FontFace

type FontFace

An owning facade for a Cairo font face without size or transformation.

A FontFace holds one internal RawFontFace owner whose finalizer calls cairo_font_face_destroy; this facade adds no second finalizer. Font faces have native pointer identity and can be shared independently by contexts and scaled fonts through Cairo references.
impl Eq for FontFace
impl Hash for FontFace

#
FontFace::equal

fn FontFace::equal(self : FontFace, other : FontFace) -> Bool

Test whether two wrappers refer to the same native font face.

This is pointer identity, not equality of family, slant, or weight. It is consistent with the Eq implementation and hash(); independently constructed faces are not promised to compare equal.

#
FontFace::get_family

fn FontFace::get_family(self : FontFace) -> String raise CairoError

Return a MoonBit-owned copy of this toy face's family name.

For an empty constructor family, Cairo may return its platform-specific default. The native string is copied before loss-tolerant UTF-8 decoding, so the result remains valid after the face leaves scope. A non-toy face raises CairoError(FontTypeMismatch, _); other failures use its checked status.

#
FontFace::get_slant

fn FontFace::get_slant(self : FontFace) -> FontSlant raise CairoError

Return this toy face's slant as a typed FontSlant.

A non-toy face raises CairoError(FontTypeMismatch, _). If a future Cairo version returns an unknown raw value, this typed boundary raises CairoInvalidArgument(InvalidStatus, _) rather than guessing.

#
FontFace::get_slant_raw

fn FontFace::get_slant_raw(self : FontFace) -> Int raise CairoError

Return this toy face's slant as the underlying Cairo C integer.

This pycairo compatibility entry point preserves the raw value. Prefer get_slant() when exhaustive typed handling is desired. A non-toy face or errored object raises its checked CairoError.

#
FontFace::get_weight

fn FontFace::get_weight(self : FontFace) -> FontWeight raise CairoError

Return this toy face's weight as a typed FontWeight.

A non-toy face raises CairoError(FontTypeMismatch, _). An unknown future raw value raises CairoInvalidArgument(InvalidStatus, _) at this typed boundary.

#
FontFace::get_weight_raw

fn FontFace::get_weight_raw(self : FontFace) -> Int raise CairoError

Return this toy face's weight as the underlying Cairo C integer.

This pycairo compatibility entry point preserves the raw value. Prefer get_weight() for typed code. A non-toy face or errored object raises its checked CairoError.

#
FontFace::hash

fn FontFace::hash(self : FontFace) -> UInt64

Return a stable identity hash for this native font face.

Wrappers that compare equal produce the same hash. The value identifies the pointer only during its lifetime and is not a persistent font identifier.

#
FontFace::status

fn FontFace::status(self : FontFace) -> Status

Return the font face's current sticky Cairo status without raising.

Success means no error has been recorded. An unknown raw status at the native boundary is represented as InvalidStatus.

#
FontFace::toy

fn FontFace::toy(family : String, slant? : FontSlant, weight? : FontWeight) -> FontFace raise CairoError

Create a face through Cairo's simplified toy-font selector.

slant and weight default to their normal typed variants. An empty family asks Cairo for the platform-specific default. The family is UTF-8; an embedded NUL raises CairoInvalidArgument(InvalidString, _). This API is intended for simple text and demonstrations, not font discovery, shaping, kerning, fallback, or complex-script layout. Allocation and backend errors use the checked CairoError hierarchy.

#
FontFace::toy_raw

fn FontFace::toy_raw(family : String, slant? : Int, weight? : Int) -> FontFace raise CairoError

Create a toy face from pycairo-compatible raw C enum integers.

Prefer FontFace::toy() for typed code. Known values round-trip through the typed getters; unsupported values are passed to Cairo and raise CairoError(InvalidSlant, _) or CairoError(InvalidWeight, _). Family-name encoding, empty-family behavior, ownership, and other failures match FontFace::toy().

#
FontOptions

type FontOptions

Owned, mutable options that control how Cairo renders fonts.

Assigning this wrapper shares the same option object; use copy() for an independently mutable snapshot. MoonBit destroys the underlying Cairo object when its final wrapper becomes unreachable. Equality and hash() are content-based, but no generic Hash implementation is provided because setters and merge() can change that content.
impl Eq for FontOptions

#
FontOptions::copy

fn FontOptions::copy(self : FontOptions) -> FontOptions raise CairoError

Copy every current option into a new, independently mutable object.

Later mutations of either object do not affect the other. Raises the source status or CairoMemoryError(NoMemory, _) if copying fails.

#
FontOptions::equal

fn FontOptions::equal(self : FontOptions, other : FontOptions) -> Bool

Return whether every option field in two objects has the same value.

This is content equality rather than allocation identity. Cairo reports unequal if either object is in an error state.

#
FontOptions::get_antialias

fn FontOptions::get_antialias(self : FontOptions) -> Antialias raise CairoError

Return the typed antialiasing mode used for text rendering.

Raises the object's checked status, or CairoInvalidArgument(InvalidStatus, _) for an unknown raw enum value.

#
FontOptions::get_antialias_raw

fn FontOptions::get_antialias_raw(self : FontOptions) -> Int raise CairoError

Return the exact Cairo C integer for the antialiasing mode.

Unknown values remain observable for pycairo C-int compatibility. Raises the object's checked CairoError status before reading the value.

#
FontOptions::get_color_mode

fn FontOptions::get_color_mode(self : FontOptions) -> ColorMode raise CairoError

Return the typed policy for rendering color-font glyphs.

Requires Cairo 1.18 or newer; older versions raise CairoError(InvalidStatus, _). An unknown raw value raises CairoInvalidArgument(InvalidStatus, _).

#
FontOptions::get_color_mode_raw

fn FontOptions::get_color_mode_raw(self : FontOptions) -> Int raise CairoError

Return the exact Cairo C integer for the color-font mode.

Unknown values remain observable for pycairo C-int compatibility. Requires Cairo 1.18 or newer; older versions raise CairoError(InvalidStatus, _).

#
FontOptions::get_color_palette

fn FontOptions::get_color_palette(self : FontOptions) -> UInt raise CairoError

Return the selected unsigned OpenType CPAL palette index.

New objects return COLOR_PALETTE_DEFAULT. Requires Cairo 1.18 or newer; older versions raise CairoError(InvalidStatus, _).

#
FontOptions::get_custom_palette_color

fn FontOptions::get_custom_palette_color(self : FontOptions, index : UInt) -> (Double, Double, Double, Double) raise CairoError

Return the configured custom RGBA override for palette entry index.

This reads only explicit overrides, not a font's underlying palette. Raises CairoInvalidArgument(InvalidIndex, _) when no override exists. Requires Cairo 1.18 or newer; older versions instead raise CairoError(InvalidStatus, _).

#
FontOptions::get_hint_metrics

fn FontOptions::get_hint_metrics(self : FontOptions) -> HintMetrics raise CairoError

Return the typed font-metrics hinting mode.

Raises the object's checked status, or CairoInvalidArgument(InvalidStatus, _) for an unknown raw enum value.

#
FontOptions::get_hint_metrics_raw

fn FontOptions::get_hint_metrics_raw(self : FontOptions) -> Int raise CairoError

Return the exact Cairo C integer for the metrics hinting mode.

Unknown values remain observable for pycairo C-int compatibility. Raises the object's checked CairoError status before reading the value.

#
FontOptions::get_hint_style

fn FontOptions::get_hint_style(self : FontOptions) -> HintStyle raise CairoError

Return the typed strength of font-outline pixel-grid fitting.

Raises the object's checked status, or CairoInvalidArgument(InvalidStatus, _) for an unknown raw enum value.

#
FontOptions::get_hint_style_raw

fn FontOptions::get_hint_style_raw(self : FontOptions) -> Int raise CairoError

Return the exact Cairo C integer for the outline hint style.

Unknown values remain observable for pycairo C-int compatibility. Raises the object's checked CairoError status before reading the value.

#
FontOptions::get_subpixel_order

fn FontOptions::get_subpixel_order(self : FontOptions) -> SubpixelOrder raise CairoError

Return the typed color-element order used for subpixel antialiasing.

Raises the object's checked status, or CairoInvalidArgument(InvalidStatus, _) for an unknown raw enum value.

#
FontOptions::get_subpixel_order_raw

fn FontOptions::get_subpixel_order_raw(self : FontOptions) -> Int raise CairoError

Return the exact Cairo C integer for the subpixel order.

Unknown values remain observable for pycairo C-int compatibility. Raises the object's checked CairoError status before reading the value.

#
FontOptions::get_variations

fn FontOptions::get_variations(self : FontOptions) -> String? raise CairoError

Return a MoonBit copy of the OpenType variation settings, or None.

Requires Cairo 1.16 or newer; older versions raise CairoError(InvalidStatus, _). The returned string is independent of the options object's internal storage.

#
FontOptions::hash

fn FontOptions::hash(self : FontOptions) -> UInt64

Return Cairo's content hash for the current option fields.

Equal options produce matching hashes. Any setter or merge() may change this value, so do not persist it or use a mutable object as a hash-table key.

#
FontOptions::merge

fn FontOptions::merge(self : FontOptions, other : FontOptions) -> Unit raise CairoError

Merge non-default fields from other into this object in place.

A non-default value in other replaces this object's value; default fields leave the corresponding destination fields unchanged. other is neither retained nor mutated. Raises the checked status of either object or of the resulting destination.

#
FontOptions::new

Create an owned options object with every setting at its Cairo default.

Raises CairoMemoryError(NoMemory, _) if Cairo cannot allocate it.

#
FontOptions::set_antialias

fn FontOptions::set_antialias(self : FontOptions, antialias : Antialias) -> Unit raise CairoError

Set the typed antialiasing mode used when Cairo renders text.

Mutates this object and raises its checked CairoError status on failure.

#
FontOptions::set_antialias_raw

fn FontOptions::set_antialias_raw(self : FontOptions, antialias : Int) -> Unit raise CairoError

Set the antialiasing mode from an unvalidated Cairo C integer.

This pycairo compatibility entry point preserves unknown values; a later typed getter rejects them with CairoInvalidArgument(InvalidStatus, _). Raises the object's checked status on failure.

#
FontOptions::set_color_mode

fn FontOptions::set_color_mode(self : FontOptions, color_mode : ColorMode) -> Unit raise CairoError

Set the typed policy for rendering color glyphs or outline glyphs.

Requires Cairo 1.18 or newer; older versions raise CairoError(InvalidStatus, _) without mutating this object.

#
FontOptions::set_color_mode_raw

fn FontOptions::set_color_mode_raw(self : FontOptions, color_mode : Int) -> Unit raise CairoError

Set the color-font mode from an unvalidated Cairo C integer.

On Cairo 1.18 or newer, unknown values remain visible through the raw getter and are rejected by the typed getter. Older versions raise CairoError(InvalidStatus, _) without mutating this object.

#
FontOptions::set_color_palette

fn FontOptions::set_color_palette(self : FontOptions, palette_index : UInt) -> Unit raise CairoError

Select an unsigned OpenType CPAL palette index.

Cairo falls back to the default palette when the selected index is invalid; custom color overrides remain in effect across palette changes. Requires Cairo 1.18 or newer, otherwise raises CairoError(InvalidStatus, _).

#
FontOptions::set_custom_palette_color

fn FontOptions::set_custom_palette_color(self : FontOptions, index : UInt, red : Double, green : Double, blue : Double, alpha : Double) -> Unit raise CairoError

Configure an RGBA override for OpenType palette entry index.

Components are passed directly to Cairo. The override is independent of the selected palette and survives later set_color_palette calls. Requires Cairo 1.18 or newer, otherwise raises CairoError(InvalidStatus, _).

#
FontOptions::set_hint_metrics

fn FontOptions::set_hint_metrics(self : FontOptions, hint_metrics : HintMetrics) -> Unit raise CairoError

Set whether Cairo quantizes font metrics to integer device units.

Mutates this object and raises its checked CairoError status on failure.

#
FontOptions::set_hint_metrics_raw

fn FontOptions::set_hint_metrics_raw(self : FontOptions, hint_metrics : Int) -> Unit raise CairoError

Set the metrics hinting mode from an unvalidated Cairo C integer.

This pycairo compatibility entry point preserves unknown values; a later typed getter rejects them with CairoInvalidArgument(InvalidStatus, _). Raises the object's checked status on failure.

#
FontOptions::set_hint_style

fn FontOptions::set_hint_style(self : FontOptions, hint_style : HintStyle) -> Unit raise CairoError

Set how strongly Cairo fits font outlines to the device pixel grid.

Mutates this object and raises its checked CairoError status on failure.

#
FontOptions::set_hint_style_raw

fn FontOptions::set_hint_style_raw(self : FontOptions, hint_style : Int) -> Unit raise CairoError

Set the outline hint style from an unvalidated Cairo C integer.

This pycairo compatibility entry point preserves unknown values; a later typed getter rejects them with CairoInvalidArgument(InvalidStatus, _). Raises the object's checked status on failure.

#
FontOptions::set_subpixel_order

fn FontOptions::set_subpixel_order(self : FontOptions, subpixel_order : SubpixelOrder) -> Unit raise CairoError

Set the typed color-element order used with AntialiasSubpixel.

Mutates this object and raises its checked CairoError status on failure.

#
FontOptions::set_subpixel_order_raw

fn FontOptions::set_subpixel_order_raw(self : FontOptions, subpixel_order : Int) -> Unit raise CairoError

Set the subpixel order from an unvalidated Cairo C integer.

This pycairo compatibility entry point preserves unknown values; a later typed getter rejects them with CairoInvalidArgument(InvalidStatus, _). Raises the object's checked status on failure.

#
FontOptions::set_variations

fn FontOptions::set_variations(self : FontOptions, variations : String?) -> Unit raise CairoError

Set or clear OpenType variation-axis assignments.

Some accepts a comma-separated CSS-like string such as "wght=200,wdth=140.5"; None clears all assignments. Embedded NUL bytes raise CairoInvalidArgument(InvalidString, _) without mutation. Requires Cairo 1.16 or newer; older versions raise CairoError(InvalidStatus, _).

#
FontOptions::status

fn FontOptions::status(self : FontOptions) -> Status

Return the status stored in this options object without raising it.

Public constructors and mutators check their status before returning, so Success is expected for values obtained through the public API.

#
FontSlant

pub(all) enum FontSlant {
FontSlantNormal
FontSlantItalic
FontSlantOblique
} derive(Eq,
Debug
)

Selects the slant requested from Cairo's toy font API.

#
FontWeight

pub(all) enum FontWeight {
FontWeightNormal
FontWeightBold
} derive(Eq,
Debug
)

Selects the weight requested from Cairo's toy font API.

#
Format

pub(all) enum Format {
Argb32
Rgb24
A8
A1
Rgb16_565
Rgb30
Rgb96F
Rgba128F
} derive(Eq,
Debug
)

The memory layout of pixels in an image surface.

Float formats require a Cairo build that supports them. Use stride_for_width to obtain Cairo's required row stride.

#
Format::stride_for_width

fn Format::stride_for_width(self : Format, width : Int) -> Int

Return Cairo's required byte stride for rows of this format and width.

Cairo returns -1 when the format or width cannot produce a valid stride.

#
Format::stride_for_width_raw

fn Format::stride_for_width_raw(format : Int, width : Int) -> Int

Return Cairo's required row stride for a raw cairo_format_t integer.

This compatibility entry point preserves pycairo's C-integer boundary and returns -1 for invalid input.

#
HintMetrics

pub(all) enum HintMetrics {
HintMetricsDefault
HintMetricsOff
HintMetricsOn
} derive(Eq,
Debug
)

Controls whether font metrics are snapped to the device pixel grid.

#
HintStyle

pub(all) enum HintStyle {
HintStyleDefault
HintStyleNone
HintStyleSlight
HintStyleMedium
HintStyleFull
} derive(Eq,
Debug
)

Selects the amount of outline adjustment used when hinting fonts.

#
ImageData

type ImageData

A mutable byte view into an image surface's live pixel storage.

ImageData does not allocate or own a second pixel buffer. Its raw view retains either the source Surface or the active MappedImageSurface, so the storage remains alive while the view is valid. Finishing the source or unmapping the mapped image invalidates all derived views; every operation rechecks that owner before touching memory. Indices address bytes, including row padding, rather than logical pixels.

#
ImageData::copy

fn ImageData::copy(self : ImageData) -> Bytes raise CairoError

Copy the current view into independent MoonBit-owned bytes.

The result includes row padding and remains valid after the surface is finished or the mapped image is unmapped. This method does not create a second mutable view; later changes to either side are not shared. Owner errors are checked before copying.

#
ImageData::get

fn ImageData::get(self : ImageData, index : Int) -> Byte raise CairoError

Read one byte from the live image storage.

Valid indices are 0 <= index < length(). A negative or out-of-range index raises CairoInvalidArgument(InvalidIndex, _); an invalidated owner raises its checked surface error first.

#
ImageData::length

fn ImageData::length(self : ImageData) -> Int raise CairoError

Return the byte length of this live view.

The length is height * stride, so it includes row padding and can be zero for an empty image. The owner is checked before the stored length is returned; a finished surface or consumed mapping raises SurfaceFinished.

#
ImageData::set

fn ImageData::set(self : ImageData, index : Int, value : Byte) -> Unit raise CairoError

Replace one byte in the live image storage and mark the image dirty.

The write is immediately visible through other views of the same storage. Cairoon's native layer calls cairo_surface_mark_dirty() after the write so later Cairo drawing observes it. Invalid indices raise CairoInvalidArgument(InvalidIndex, _), and an invalidated owner raises its checked surface error without writing.

#
ImageData::status

fn ImageData::status(self : ImageData) -> Status

Return the view's current owner status without raising.

Success means the source surface or mapping is still live. A finished surface or consumed mapping reports SurfaceFinished; an unknown native status is represented as InvalidStatus.

#
LineCap

pub(all) enum LineCap {
LineCapButt
LineCapRound
LineCapSquare
} derive(Eq,
Debug
)

Selects the shape drawn at the end of an open stroked subpath.

#
LineJoin

pub(all) enum LineJoin {
LineJoinMiter
LineJoinRound
LineJoinBevel
} derive(Eq,
Debug
)

Selects the shape drawn where two stroked path segments meet.

#
MappedImageSurface

type MappedImageSurface

An owning, single-use image mapping of a Surface backing store.

The raw mapping retains its originating surface and is the only owner that may call cairo_surface_unmap_image. Explicit unmap consumes the mapping; the native finalizer also unmaps an abandoned live handle. Derived contexts and ImageData views retain this owner but become invalid after unmap. Prefer deterministic with_unmapped() scope for normal use.

#
MappedImageSurface::copy_data

fn MappedImageSurface::copy_data(self : MappedImageSurface) -> Bytes raise CairoError

Return an independent snapshot of the active mapped image bytes.

Pending mapped-image drawing is flushed first. The result contains height * stride bytes including row padding and remains valid after unmap; it does not itself upload or consume the mapping. Lifecycle, allocation, and native image errors use the checked CairoError hierarchy.

#
MappedImageSurface::flush

fn MappedImageSurface::flush(self : MappedImageSurface) -> Unit raise CairoError

Complete pending drawing to the mapped image without unmapping it.

The mapping remains active and changes are not uploaded as an unmap side effect. A consumed or errored mapping raises its checked CairoError.

#
MappedImageSurface::get_data

Return a mutable byte view of an active mapped image.

Pending drawing to the mapped image is flushed first. The returned view retains the mapped handle, but it becomes invalid as soon as either unmap() or Surface::unmap_image() completes. Access after unmapping raises CairoError(SurfaceFinished, _).

#
MappedImageSurface::get_format

fn MappedImageSurface::get_format(self : MappedImageSurface) -> Format raise CairoError

Return the active mapped image's pixel format as a typed Format.

Cairo guarantees a successful map has an image format other than FormatInvalid. A future value unknown to this build raises CairoInvalidArgument(InvalidStatus, _); mapping errors are also checked.

#
MappedImageSurface::get_format_raw

fn MappedImageSurface::get_format_raw(self : MappedImageSurface) -> Int raise CairoError

Return the active mapped image's format as the underlying C integer.

This pycairo compatibility form preserves future raw values. A consumed or errored mapping raises its checked CairoError.

#
MappedImageSurface::get_height

fn MappedImageSurface::get_height(self : MappedImageSurface) -> Int raise CairoError

Return the active mapped image's height in pixels.

For an extent-limited map this is the mapped region's height. A consumed or errored mapping raises its checked CairoError.

#
MappedImageSurface::get_stride

fn MappedImageSurface::get_stride(self : MappedImageSurface) -> Int raise CairoError

Return the active mapped image's row stride in bytes.

The stride includes any Cairo-required row padding and can exceed the logical pixel width. A consumed or errored mapping raises its checked CairoError.

#
MappedImageSurface::get_width

fn MappedImageSurface::get_width(self : MappedImageSurface) -> Int raise CairoError

Return the active mapped image's width in pixels.

For an extent-limited map this is the mapped region's width. A consumed or errored mapping raises its checked CairoError.

#
MappedImageSurface::status

Return the mapping's current sticky status without raising.

Success means the mapping is active and its image is usable. SurfaceFinished means it has already been consumed. An unknown native status is represented as InvalidStatus.

#
MappedImageSurface::unmap

fn MappedImageSurface::unmap(self : MappedImageSurface) -> Unit raise CairoError

Upload and consume this mapping through its retained base surface.

This is the owner-independent counterpart to Surface::unmap_image(). Native cleanup still runs if the base or mapped image has a sticky error, after which that status is raised. The operation is exact-once; later use raises CairoError(SurfaceFinished, _).

#
MappedImageSurface::with_unmapped

fn[T] MappedImageSurface::with_unmapped(self : MappedImageSurface, f : () -> T raise CairoError) -> T raise CairoError

Run f and deterministically unmap this image on every exit path.

On normal return, a checked unmap is performed and any cleanup error is raised. If f raises, cairoon attempts raw unmap but preserves and re-raises the original closure error even if cleanup also reports an error. Therefore f must not retain the mapping, a derived context, or an ImageData view for later use.

#
Matrix

pub struct Matrix {
xx : Double
yx : Double
xy : Double
yy : Double
x0 : Double
y0 : Double
} derive(Eq,
Debug
)

A pure affine transformation in Cairo component order.

Points are transformed as x' = xx*x + xy*y + x0 and y' = yx*x + yy*y + y0. All transformation methods return new values; they never mutate the receiver as pycairo's corresponding methods do.
impl Mul for Matrix

#
Matrix::at

#alias("_[_]")
fn Matrix::at(self : Matrix, index : Int) -> Double raise CairoError

Index the (xx, yx, xy, yy, x0, y0) component sequence.

Raises CairoInvalidArgument(InvalidIndex, _) outside 0..5.

#
Matrix::component

fn Matrix::component(self : Matrix, index : Int) -> Double raise CairoError

Return the component at index 0..5 in Cairo/pycairo order.

Raises CairoInvalidArgument(InvalidIndex, _) for any other index.

#
Matrix::components

fn Matrix::components(self : Matrix) -> (Double, Double, Double, Double, Double, Double)

Return (xx, yx, xy, yy, x0, y0).

#
Matrix::init_rotate

fn Matrix::init_rotate(radians : Double) -> Matrix

Construct a rotation by radians around the origin.

Positive angles rotate from the positive X axis toward positive Y, which appears clockwise with Cairo's default downward-pointing Y axis.

#
Matrix::invert

fn Matrix::invert(self : Matrix) -> Matrix raise CairoError

Return the inverse affine transformation without changing self.

Raises CairoInvalidArgument(InvalidMatrix, _) when the matrix is degenerate and has no inverse.

#
Matrix::multiply

fn Matrix::multiply(self : Matrix, other : Matrix) -> Matrix

Compose self with other, applying self to coordinates first.

The * operator delegates to this method. Neither operand is mutated.

#
Matrix::new

fn Matrix::new(xx? : Double, yx? : Double, xy? : Double, yy? : Double, x0? : Double, y0? : Double) -> Matrix

Construct a matrix from (xx, yx, xy, yy, x0, y0) components.

Omitted components produce the identity matrix.

#
Matrix::rotate

fn Matrix::rotate(self : Matrix, radians : Double) -> Matrix

Return a transform that first rotates by radians, then applies self.

The receiver is unchanged.

#
Matrix::scale

fn Matrix::scale(self : Matrix, sx : Double, sy : Double) -> Matrix

Return a transform that first scales by (sx, sy), then applies self.

The receiver is unchanged.

#
Matrix::transform_distance

fn Matrix::transform_distance(self : Matrix, dx : Double, dy : Double) -> (Double, Double)

Transform a distance vector while ignoring translation.

#
Matrix::transform_point

fn Matrix::transform_point(self : Matrix, x : Double, y : Double) -> (Double, Double)

Transform a point, including the matrix's translation components.

#
Matrix::translate

fn Matrix::translate(self : Matrix, tx : Double, ty : Double) -> Matrix

Return a transform that first translates by (tx, ty), then applies self.

The receiver is unchanged.

#
Operator

pub(all) enum Operator {
OperatorClear
OperatorSource
OperatorOver
OperatorIn
OperatorOut
OperatorAtop
OperatorDest
OperatorDestOver
OperatorDestIn
OperatorDestOut
OperatorDestAtop
OperatorXor
OperatorAdd
OperatorSaturate
OperatorMultiply
OperatorScreen
OperatorOverlay
OperatorDarken
OperatorLighten
OperatorColorDodge
OperatorColorBurn
OperatorHardLight
OperatorSoftLight
OperatorDifference
OperatorExclusion
OperatorHslHue
OperatorHslSaturation
OperatorHslColor
OperatorHslLuminosity
} derive(Eq,
Debug
)

Selects the Porter-Duff or blend operator used for compositing.

#
PDFMetadata

pub(all) enum PDFMetadata {
PdfMetadataTitle
PdfMetadataAuthor
PdfMetadataSubject
PdfMetadataKeywords
PdfMetadataCreator
PdfMetadataCreateDate
PdfMetadataModDate
} derive(Eq,
Debug
)

Selects a standard metadata field on a Cairo PDF surface.

#
PDFOutlineFlagSet

pub struct PDFOutlineFlagSet {
bits : Int
} derive(Eq,
Debug
)

An immutable PDF outline flag bitset.

Use none, of, combine, and add for the portable Open/Bold/Italic bits. from_bits preserves an exact pycairo-compatible integer for ported code; bits outside the known 0x07 mask have no portable Cairo semantics.

#
PDFOutlineFlagSet::add

Return a new set with flag added; the receiver is unchanged.

#
PDFOutlineFlagSet::bits

fn PDFOutlineFlagSet::bits(self : PDFOutlineFlagSet) -> Int

Return the exact stored C-compatible bitset.

#
PDFOutlineFlagSet::combine

Combine typed outline flags with bitwise OR.

The returned value is independent of flags; duplicate entries are idempotent and an empty view produces PDFOutlineFlagSet::none().

#
PDFOutlineFlagSet::contains

fn PDFOutlineFlagSet::contains(self : PDFOutlineFlagSet, flag : PDFOutlineFlags) -> Bool

Return whether this set contains the selected typed flag bit.

#
PDFOutlineFlagSet::from_bits

fn PDFOutlineFlagSet::from_bits(bits : Int) -> PDFOutlineFlagSet

Preserve an exact raw outline bitset for pycairo-compatible code.

Known portable bits occupy mask 0x07. Other bits are retained by bits() and passed unchanged by raw outline APIs, but their PDF rendering behavior is unsupported.

#
PDFOutlineFlagSet::none

Return an empty outline flag set with raw value zero.

#
PDFOutlineFlagSet::of

Create a set containing exactly one typed outline flag.

#
PDFOutlineFlags

pub(all) enum PDFOutlineFlags {
PdfOutlineOpen
PdfOutlineBold
PdfOutlineItalic
} derive(Eq,
Debug
)

A single PDF outline style flag.

Pass multiple flags with the array-based outline API; raw bitsets are also available for pycairo compatibility.

#
PDFOutlineFlags::bits

fn PDFOutlineFlags::bits(self : PDFOutlineFlags) -> Int

Return this flag's Cairo bit: Open=0x01, Bold=0x02, Italic=0x04.

#
PDFVersion

pub(all) enum PDFVersion {
PdfVersion1_4
PdfVersion1_5
PdfVersion1_6
PdfVersion1_7
} derive(Eq,
Debug
)

A PDF language version supported by a Cairo PDF surface.

#
PDFVersion::supported

fn PDFVersion::supported() -> Array[PDFVersion] raise CairoError

Return a fresh array of PDF versions supported by linked Cairo.

Query this list instead of assuming every PDFVersion constructor is available: PDF 1.6 and 1.7 output support arrived after 1.4 and 1.5. The result is copied from Cairo's static table and may be mutated by the caller. An unavailable PDF backend raises CairoError(InvalidStatus, _).

#
PDFVersion::to_string

fn PDFVersion::to_string(self : PDFVersion) -> String raise CairoError

Return a copied Cairo display string for this PDF version.

A typed constructor that linked Cairo does not support, such as PDF 1.7 on the 1.15.10 compatibility floor, raises CairoError(InvalidStatus, _). The returned string does not borrow Cairo storage.

#
PDFVersion::to_string_raw

fn PDFVersion::to_string_raw(version : Int) -> String raise CairoError

Convert a pycairo-compatible cairo_pdf_version_t integer to text.

Raw ids are 0 (1.4), 1 (1.5), 2 (1.6), and 3 (1.7), but an id is valid only when present in PDFVersion::supported(). Negative, unavailable, and other unknown values raise CairoError(InvalidStatus, _); the returned string is copied into MoonBit-owned storage.

#
PSLevel

pub(all) enum PSLevel {
PsLevel2
PsLevel3
} derive(Eq,
Debug
)

A PostScript language level supported by a Cairo PS surface.

#
PSLevel::supported

fn PSLevel::supported() -> Array[PSLevel] raise CairoError

Return a fresh array of PostScript levels supported by linked Cairo.

The result is copied from Cairo's static table and can be mutated by the caller. An unavailable PS backend raises CairoError(InvalidStatus, _).

#
PSLevel::to_string

fn PSLevel::to_string(self : PSLevel) -> String raise CairoError

Return a copied Cairo display string for this PostScript level.

The result does not borrow Cairo storage. Backend or conversion failures are reported as checked CairoError values.

#
PSLevel::to_string_raw

fn PSLevel::to_string_raw(level : Int) -> String raise CairoError

Convert a pycairo-compatible cairo_ps_level_t integer to text.

Portable values are 0 (Level 2) and 1 (Level 3). Negative and other unknown values raise CairoError(InvalidStatus, _); the returned string is copied into MoonBit-owned storage.

#
Path

type Path

An owned, opaque snapshot of Cairo path data.

Paths come from Context::copy_path, Context::copy_path_flat, or another Cairo producer and cannot be directly constructed. A path remains valid independently of the context or pattern that produced it.
impl Compare for Path
impl Eq for Path
impl Hash for Path

#
Path::equal

fn Path::equal(self : Path, other : Path) -> Bool

Test whether two wrappers own the same Cairo path allocation.

This is identity equality, not geometric or segment-content equality.

#
Path::hash

fn Path::hash(self : Path) -> UInt64

Return an identity hash for the underlying Cairo path allocation.

The value is process-local and must not be persisted.

#
Path::iter

fn Path::iter(self : Path) -> Iter[PathSegment] raise CairoError

Return an iterator over a copied, validated segment snapshot.

Constructing the iterator materializes the complete segments() array and can raise the same checked errors.

#
Path::length

fn Path::length(self : Path) -> Int raise CairoError

Return the number of independent path segments.

Cairo may insert an explicit move segment after close-path; it counts as a segment. Raises the path's checked CairoError status if it is invalid.

#
Path::segments

fn Path::segments(self : Path) -> Array[PathSegment] raise CairoError

Copy all path data into typed MoonBit segments.

Raises the path's checked CairoError status for invalid path data.

#
Path::status

fn Path::status(self : Path) -> Status

Return the status stored in this path without raising it.

#
Path::to_string

fn Path::to_string(self : Path) -> String raise CairoError

Format segments in pycairo's newline-separated debug representation.

This representation is for diagnostics, not stable serialization. Raises the path's checked CairoError status for invalid data or allocation errors.

#
PathDataType

pub(all) enum PathDataType {
PathMoveTo
PathLineTo
PathCurveTo
PathClosePath
} derive(Eq,
Debug
)

Identifies the command stored in a copied Cairo path segment.

#
PathSegment

pub(all) enum PathSegment {
PathSegmentMoveTo(Double, Double)
PathSegmentLineTo(Double, Double)
PathSegmentCurveTo(Double, Double, Double, Double, Double, Double)
PathSegmentClosePath
} derive(Eq,
Debug
)

A typed element of an owned Cairo path snapshot.

Move and line elements store their endpoint. Curve elements store the first control point, second control point, and endpoint in that order. Coordinates use the user space in effect when the path was copied.

#
PathSegment::components

fn PathSegment::components(self : PathSegment) -> (PathDataType, Array[Double])

Return the segment discriminator and a newly allocated coordinate array.

#
PathSegment::coordinates

fn PathSegment::coordinates(self : PathSegment) -> Array[Double]

Return this segment's coordinates in Cairo order.

The new array contains two values for move/line, six for curve, and none for close-path.

#
PathSegment::data_type

fn PathSegment::data_type(self : PathSegment) -> PathDataType

Return the Cairo path-data discriminator for this segment.

#
Pattern

type Pattern

An owned Cairo drawing source used by Context::set_source and masks.

A value owns one native pattern reference through its private raw handle; MoonBit finalization releases that reference. Solid, surface, gradient, mesh, and raster-source subtypes share this wrapper. Equality and hashing use native pointer identity, not rendered-value equality.
impl Eq for Pattern
impl Hash for Pattern

#
Pattern::add_color_stop_rgb

fn Pattern::add_color_stop_rgb(self : Pattern, offset : Double, red : Double, green : Double, blue : Double) -> Unit raise CairoError

Add an opaque color stop to a linear or radial gradient.

offset and RGB components are clamped to [0.0, 1.0]. Stops with equal offsets preserve insertion order, allowing sharp transitions. Raises PatternTypeMismatch on a non-gradient and makes the error sticky.

#
Pattern::add_color_stop_rgba

fn Pattern::add_color_stop_rgba(self : Pattern, offset : Double, red : Double, green : Double, blue : Double, alpha : Double) -> Unit raise CairoError

Add a color stop with alpha to a linear or radial gradient.

offset and all RGBA components are clamped to [0.0, 1.0]. Equal-offset stops preserve insertion order. Raises PatternTypeMismatch on any other pattern subtype and propagates a sticky pattern error.

#
Pattern::equal

fn Pattern::equal(self : Pattern, other : Pattern) -> Bool

Test whether two wrappers refer to the same native Cairo pattern.

This is pointer identity; independently created patterns with equal colors or geometry compare unequal.

#
Pattern::for_surface

fn Pattern::for_surface(surface : Surface) -> Pattern raise CairoError

Create a pattern that samples surface.

The new pattern retains the source surface, including MoonBit-managed image data backing it, so the pattern remains usable after surface leaves scope. Raises either the source or newly created pattern status.

#
Pattern::get_color_stop_count

fn Pattern::get_color_stop_count(self : Pattern) -> Int raise CairoError

Return the number of stops in a linear or radial gradient.

Raises PatternTypeMismatch for non-gradient patterns and propagates an existing sticky pattern error.

#
Pattern::get_color_stop_rgba

fn Pattern::get_color_stop_rgba(self : Pattern, index : Int) -> (Double, Double, Double, Double, Double) raise CairoError

Return one gradient stop as (offset, red, green, blue, alpha).

Colors are unpremultiplied and all values are in [0.0, 1.0]. Stop order follows offset and stable insertion order for ties. Raises InvalidIndex outside 0..<get_color_stop_count() or PatternTypeMismatch otherwise.

#
Pattern::get_color_stops_rgba

fn Pattern::get_color_stops_rgba(self : Pattern) -> Array[(Double, Double, Double, Double, Double)] raise CairoError

Copy every gradient stop into a new ordered array.

The returned tuples are independent value snapshots with unpremultiplied RGBA components. Raises the same PatternTypeMismatch, InvalidIndex, or sticky status as the underlying count and indexed getters.

#
Pattern::get_dither

fn Pattern::get_dither(self : Pattern) -> Dither raise CairoError

Return this pattern's dithering hint.

Dithering is available with Cairo 1.18 or newer and is currently honored by pixman-backed rendering. Older runtimes raise InvalidStatus; an unknown raw value also raises InvalidStatus during typed conversion.

#
Pattern::get_dither_raw

fn Pattern::get_dither_raw(self : Pattern) -> Int raise CairoError

Return Cairo's raw integer dithering hint.

Requires Cairo 1.18 or newer and otherwise raises InvalidStatus. Values outside the typed enum are returned unchanged.

#
Pattern::get_extend

fn Pattern::get_extend(self : Pattern) -> Extend raise CairoError

Return how sampling behaves outside this pattern's intrinsic bounds.

Surface patterns default to ExtendNone; gradient patterns default to Pad. Raises a sticky pattern error or InvalidStatus if a prior raw setter stored a value unknown to the typed Extend enum.

#
Pattern::get_extend_raw

fn Pattern::get_extend_raw(self : Pattern) -> Int raise CairoError

Return Cairo's integer extend value without typed-enum conversion.

Known values are 0 through 3; an arbitrary value previously supplied to set_extend_raw() is returned unchanged. Raises an existing pattern error.

#
Pattern::get_filter

fn Pattern::get_filter(self : Pattern) -> Filter raise CairoError

Return the sampling filter hint used when this pattern is rescaled.

New patterns normally use Good. Raises a sticky pattern error or InvalidStatus when a prior raw setter stored an unknown integer.

#
Pattern::get_filter_raw

fn Pattern::get_filter_raw(self : Pattern) -> Int raise CairoError

Return Cairo's integer filter hint without typed-enum conversion.

Known values are 0 through 5; arbitrary values set through the raw API are preserved. Raises an existing sticky pattern error.

#
Pattern::get_linear_points

fn Pattern::get_linear_points(self : Pattern) -> (Double, Double, Double, Double) raise CairoError

Return a linear gradient's endpoints (x0, y0, x1, y1).

Values are the original pattern-space coordinates and are not transformed by the current pattern matrix. Raises PatternTypeMismatch for any other subtype and propagates a sticky pattern error.

#
Pattern::get_matrix

fn Pattern::get_matrix(self : Pattern) -> Matrix raise CairoError

Return the affine transform from user space to pattern space.

New patterns start with identity. Because this direction is the inverse of the apparent pattern-to-user transform, scaling the matrix down makes the rendered pattern appear larger. Raises an existing sticky pattern error.

#
Pattern::get_radial_circles

fn Pattern::get_radial_circles(self : Pattern) -> (Double, Double, Double, Double, Double, Double) raise CairoError

Return a radial gradient's two circles.

The tuple is (cx0, cy0, radius0, cx1, cy1, radius1) in the original pattern space. Raises PatternTypeMismatch for any other subtype and propagates a sticky pattern error.

#
Pattern::get_rgba

fn Pattern::get_rgba(self : Pattern) -> (Double, Double, Double, Double) raise CairoError

Return a solid pattern's unpremultiplied RGBA components.

Components are in [0.0, 1.0]; an RGB pattern reports alpha 1.0. Raises PatternTypeMismatch for surface, gradient, mesh, or raster-source patterns and propagates any existing sticky pattern error.

#
Pattern::get_surface

fn Pattern::get_surface(self : Pattern) -> Surface raise CairoError

Return the surface sampled by a surface pattern.

The result owns an independent Cairo surface reference and remains valid after this pattern leaves scope. Raises PatternTypeMismatch for any other pattern subtype and propagates an existing sticky pattern or surface error.

#
Pattern::hash

fn Pattern::hash(self : Pattern) -> UInt64

Return a stable hash of this native pattern's pointer identity.

It is consistent with equal() for the lifetime of the pattern and does not describe its mutable drawing state.

#
Pattern::linear

fn Pattern::linear(x0 : Double, y0 : Double, x1 : Double, y1 : Double) -> Pattern raise CairoError

Create a linear gradient from (x0, y0) to (x1, y1).

Coordinates are in pattern space, which initially equals user space and can be changed with set_matrix(). Add at least one color stop before drawing. The returned value owns its native pattern and raises its creation status.

#
Pattern::mesh

fn Pattern::mesh() -> Pattern raise CairoError

Create an empty tensor-product mesh pattern.

Mesh patterns require Cairo 1.12 or newer. Define one or more complete patches before drawing; using a partially open patch produces InvalidMeshConstruction. The returned pattern is independently owned.

#
Pattern::mesh_begin_patch

fn Pattern::mesh_begin_patch(self : Pattern) -> Unit raise CairoError

Begin a new patch in this mesh pattern.

Follow with one initial point, up to four sides, optional control points and corner colors, then mesh_end_patch(). Raises PatternTypeMismatch on a non-mesh or InvalidMeshConstruction if a patch is already open.

#
Pattern::mesh_curve_to

fn Pattern::mesh_curve_to(self : Pattern, x1 : Double, y1 : Double, x2 : Double, y2 : Double, x3 : Double, y3 : Double) -> Unit raise CairoError

Add a cubic Bezier side to the open patch in pattern space.

(x1, y1) and (x2, y2) are controls and (x3, y3) becomes current. With no current point Cairo first moves to (x1, y1). Raises InvalidMeshConstruction without an open patch or after four sides.

#
Pattern::mesh_end_patch

fn Pattern::mesh_end_patch(self : Pattern) -> Unit raise CairoError

Complete the current mesh patch.

Cairo closes fewer than four sides back to the first point and fills any remaining sides degenerately there. Corners introduced by that closing copy corner 0; other unset colors stay transparent black. Unspecified internal controls use Coons-patch defaults. Raises InvalidMeshConstruction if no usable patch is open.

#
Pattern::mesh_get_control_point

fn Pattern::mesh_get_control_point(self : Pattern, patch_num : Int, point_num : Int) -> (Double, Double) raise CairoError

Return internal control point point_num of completed patch patch_num.

Both indices are zero-based and the control-point index must be 0..3. Coordinates are in pattern space. Raises InvalidIndex, PatternTypeMismatch, or an existing sticky error.

#
Pattern::mesh_get_corner_color_rgba

fn Pattern::mesh_get_corner_color_rgba(self : Pattern, patch_num : Int, corner_num : Int) -> (Double, Double, Double, Double) raise CairoError

Return one completed patch corner as unpremultiplied RGBA.

patch_num is zero-based and corner_num must be 0..3; components are in [0.0, 1.0]. Raises InvalidIndex, PatternTypeMismatch, or an existing sticky pattern error.

#
Pattern::mesh_get_patch_count

fn Pattern::mesh_get_patch_count(self : Pattern) -> Int raise CairoError

Return the number of completed patches in this mesh.

The currently open patch is not a drawable completed patch. Raises PatternTypeMismatch on another subtype and propagates sticky errors.

#
Pattern::mesh_get_path

fn Pattern::mesh_get_path(self : Pattern, patch_num : Int) -> Path raise CairoError

Copy the boundary path of completed patch patch_num.

The returned Path owns an independent native snapshot and remains usable after this pattern leaves scope. Raises InvalidIndex for an unknown patch, PatternTypeMismatch for a non-mesh, or a path/allocation status.

#
Pattern::mesh_line_to

fn Pattern::mesh_line_to(self : Pattern, x : Double, y : Double) -> Unit raise CairoError

Add a straight side to the open patch in pattern space.

With no current point this behaves like mesh_move_to(x, y); otherwise the endpoint becomes current. Raises InvalidMeshConstruction without an open patch or after four sides, and PatternTypeMismatch on a non-mesh.

#
Pattern::mesh_move_to

fn Pattern::mesh_move_to(self : Pattern, x : Double, y : Double) -> Unit raise CairoError

Define the first point of the open patch in pattern-space coordinates.

This point is corner 0 and becomes current. Raises PatternTypeMismatch on a non-mesh or InvalidMeshConstruction without an open patch or after a side has already been added.

#
Pattern::mesh_set_control_point

fn Pattern::mesh_set_control_point(self : Pattern, point_num : Int, x : Double, y : Double) -> Unit raise CairoError

Set one internal control point of the open tensor-product patch.

point_num must be 0..3; coordinates are in pattern space. Unspecified points retain their Coons-patch defaults. Raises InvalidIndex, InvalidMeshConstruction, PatternTypeMismatch, or another sticky status.

#
Pattern::mesh_set_corner_color_rgb

fn Pattern::mesh_set_corner_color_rgb(self : Pattern, corner_num : Int, red : Double, green : Double, blue : Double) -> Unit raise CairoError

Set an opaque color for one corner of the open patch.

corner_num must be 0..3; RGB components are clamped to [0.0, 1.0]. Unspecified corners default to transparent black before patch completion. Raises InvalidIndex, InvalidMeshConstruction, or PatternTypeMismatch.

#
Pattern::mesh_set_corner_color_rgba

fn Pattern::mesh_set_corner_color_rgba(self : Pattern, corner_num : Int, red : Double, green : Double, blue : Double, alpha : Double) -> Unit raise CairoError

Set an RGBA color for one corner of the open patch.

corner_num must be 0..3, and components are clamped to [0.0, 1.0]. Raises InvalidIndex, InvalidMeshConstruction, PatternTypeMismatch, or another sticky pattern status.

#
Pattern::radial

fn Pattern::radial(cx0 : Double, cy0 : Double, radius0 : Double, cx1 : Double, cy1 : Double, radius1 : Double) -> Pattern raise CairoError

Create a radial gradient between two circles.

Centers and radii are in pattern space; Cairo stores each radius as its absolute value. The result owns its native pattern and raises the checked creation status. Add color stops before drawing.

#
Pattern::raster_clear_acquire

fn Pattern::raster_clear_acquire(self : Pattern) -> Unit raise CairoError

Clear the raster acquire/release pair.

This is the pycairo-compatible name for raster_clear_callbacks(). It uses the same deferred, reentrant-safe cleanup and raises the same checked errors.

#
Pattern::raster_clear_callbacks

fn Pattern::raster_clear_callbacks(self : Pattern) -> Unit raise CairoError

Clear both raster callbacks and release their retained closures.

If called from acquire or release, clearing takes effect after every outstanding acquisition using the current pair has run internal cleanup. Raises PatternTypeMismatch on a non-raster pattern or a sticky error.

#
Pattern::raster_get_acquire

fn Pattern::raster_get_acquire(self : Pattern) -> ((Surface, RectangleInt) -> Surface, (Surface) -> Unit?)? raise CairoError

Return the acquire callback paired with its optional release callback.

Returns None when no acquire callback is effective, including release-only registration. The returned closures are strong references. Raises PatternTypeMismatch on a non-raster pattern or a sticky pattern error.

#
Pattern::raster_get_callbacks

fn Pattern::raster_get_callbacks(self : Pattern) -> ((Surface, RectangleInt) -> Surface?, (Surface) -> Unit?) raise CairoError

Return the currently effective acquire and release closures.

Returned closures are strong MoonBit references and may outlive a later replacement. During a callback-triggered deferred replacement, this reports the pair still serving outstanding acquisitions. Raises PatternTypeMismatch on a non-raster pattern or a sticky pattern error.

#
Pattern::raster_set_acquire

fn Pattern::raster_set_acquire(self : Pattern, acquire : (Surface, RectangleInt) -> Surface, release? : (Surface) -> Unit?) -> Unit raise CairoError

Install the mandatory raster acquire callback and optional release callback.

For each request, acquire receives the target and a pixel rectangle in sample space. Return a compatible surface covering that rectangle; use target.create_similar_image() and a device offset for a subregion. The binding retains the returned surface until Cairo releases the acquisition. Both closures are retained until replacement, clearing, or finalization.

#
Pattern::raster_set_callbacks

fn Pattern::raster_set_callbacks(self : Pattern, acquire? : (Surface, RectangleInt) -> Surface?, release? : (Surface) -> Unit?) -> Unit raise CairoError

Replace this raster pattern's callback registration.

Callback types are non-raising: recoverable MoonBit errors must be handled inside the closure and must never unwind through Cairo. A finished or error surface returned by acquire is rejected and the drawing operation reports a Cairo error. release, when present, receives each successfully acquired surface before the binding drops its retained owner; internal cleanup still runs when no user release is registered.

Passing both options as None clears the registration. Release-only state is queryable but cannot supply pixels. Replacement requested from inside a callback is deferred until all acquisitions using the old pair are released, preserving closure and surface lifetimes. Raises PatternTypeMismatch on a non-raster pattern or another checked registration status.

#
Pattern::raster_source

fn Pattern::raster_source(content : Content, width : Int, height : Int) -> Pattern raise CairoError

Create a callback-backed pixel source with typed content.

Raster-source patterns require Cairo 1.12 or newer. width and height are the non-negative maximum sample-area dimensions, not an allocated image. Register an acquire callback before drawing. Raises InvalidSize, InvalidContent, allocation failure, or another creation status.

#
Pattern::raster_source_raw

fn Pattern::raster_source_raw(content : Int, width : Int, height : Int) -> Pattern raise CairoError

Create a callback-backed pixel source from a Cairo content integer.

For pycairo compatibility, accepted values are exactly 0x1000 (color), 0x2000 (alpha), and 0x3000 (color plus alpha). Other values raise CairoInvalidArgument(InvalidContent, _) before C; dimensions and Cairo 1.12 requirements match raster_source().

#
Pattern::set_dither

fn Pattern::set_dither(self : Pattern, dither : Dither) -> Unit raise CairoError

Set this pattern's dithering hint for later rendering.

Requires Cairo 1.18 or newer; older runtimes raise InvalidStatus. The hint does not guarantee that every backend performs dithering.

#
Pattern::set_dither_raw

fn Pattern::set_dither_raw(self : Pattern, dither : Int) -> Unit raise CairoError

Pass a dithering integer directly to Cairo for pycairo compatibility.

No enum range check is performed. Requires Cairo 1.18 or newer; older runtimes raise InvalidStatus, and the typed getter rejects unknown values.

#
Pattern::set_extend

fn Pattern::set_extend(self : Pattern, extend_mode : Extend) -> Unit raise CairoError

Set how sampling behaves outside this pattern's intrinsic bounds.

The mode affects later uses of this mutable pattern. Raises the checked sticky pattern status.

#
Pattern::set_extend_raw

fn Pattern::set_extend_raw(self : Pattern, extend_mode : Int) -> Unit raise CairoError

Pass an integer extend value directly to Cairo for pycairo compatibility.

The value is intentionally not range-checked. Unknown values can be read by get_extend_raw(), while get_extend() raises InvalidStatus for them. Raises the checked sticky pattern status.

#
Pattern::set_filter

fn Pattern::set_filter(self : Pattern, filter : Filter) -> Unit raise CairoError

Set the quality/performance hint used to filter this pattern.

Cairo backends may choose an implementation compatible with the hint. Raises the checked sticky pattern status.

#
Pattern::set_filter_raw

fn Pattern::set_filter_raw(self : Pattern, filter : Int) -> Unit raise CairoError

Pass an integer filter hint directly to Cairo for pycairo compatibility.

The value is intentionally not range-checked. The typed getter later raises InvalidStatus if Cairo returns a value outside the Filter enum.

#
Pattern::set_matrix

fn Pattern::set_matrix(self : Pattern, matrix : Matrix) -> Unit raise CairoError

Set the affine transform from user space to pattern space.

matrix is copied; later changes to the value do not affect the pattern. A non-invertible matrix raises CairoInvalidArgument(InvalidMatrix, _) and leaves that error sticky on the pattern.

#
Pattern::solid_rgb

fn Pattern::solid_rgb(red : Double, green : Double, blue : Double) -> Pattern raise CairoError

Create an opaque solid-color pattern.

red, green, and blue are clamped to [0.0, 1.0]. The returned value owns its native pattern and raises the checked creation status, including allocation failure.

#
Pattern::solid_rgba

fn Pattern::solid_rgba(red : Double, green : Double, blue : Double, alpha : Double) -> Pattern raise CairoError

Create a solid-color pattern with explicit alpha.

All four components are clamped to [0.0, 1.0]. The returned value owns its native pattern and raises the checked creation status.

#
Pattern::status

fn Pattern::status(self : Pattern) -> Status

Return this pattern's sticky Cairo status without raising.

Once Cairo records an error, later checked operations keep reporting it. An unrecognized native status is conservatively returned as InvalidStatus.

#
Rectangle

pub struct Rectangle {
x : Double
y : Double
width : Double
height : Double
} derive(Eq, Hash,
Debug
)

A floating-point Cairo rectangle.

x and y locate the left and top edges; width and height give its size. The coordinate space is defined by the API that produces or consumes the rectangle.

#
Rectangle::at

#alias("_[_]")
fn Rectangle::at(self : Rectangle, index : Int) -> Double raise CairoError

Index the (x, y, width, height) component sequence.

Raises CairoInvalidArgument(InvalidIndex, _) outside 0..3.

#
Rectangle::component

fn Rectangle::component(self : Rectangle, index : Int) -> Double raise CairoError

Return component 0..3 from (x, y, width, height).

Raises CairoInvalidArgument(InvalidIndex, _) for any other index.

#
Rectangle::components

fn Rectangle::components(self : Rectangle) -> (Double, Double, Double, Double)

Return (x, y, width, height) in pycairo tuple order.

#
Rectangle::new

fn Rectangle::new(x : Double, y : Double, width : Double, height : Double) -> Rectangle

Construct a rectangle without validating its dimensions.

#
RectangleInt

pub struct RectangleInt {
x : Int
y : Int
width : Int
height : Int
} derive(Eq,
Debug
)

An integer Cairo rectangle, commonly used by regions and image mappings.

x and y locate the left and top edges; width and height give its size in the coordinate space of the consuming API.

#
RectangleInt::component

fn RectangleInt::component(self : RectangleInt, index : Int) -> Int raise CairoError

Return component 0..3 from (x, y, width, height).

Raises CairoInvalidArgument(InvalidIndex, _) for any other index.

#
RectangleInt::components

fn RectangleInt::components(self : RectangleInt) -> (Int, Int, Int, Int)

Return (x, y, width, height).

#
RectangleInt::new

fn RectangleInt::new(x? : Int, y? : Int, width? : Int, height? : Int) -> RectangleInt

Construct an integer rectangle; omitted components default to zero.

Construction does not validate dimensions.

#
Region

type Region

An owned, mutable Cairo region made from integer-aligned rectangles.

Assigning this wrapper shares the same underlying region. Use copy() for an independently mutable snapshot. MoonBit releases the Cairo handle when the final wrapper becomes unreachable. Unlike pycairo, boolean mutators return the receiver so operations can be chained.
impl Eq for Region

#
Region::contains_point

fn Region::contains_point(self : Region, x : Int, y : Int) -> Bool

Return whether the integer point (x, y) lies inside this region.

#
Region::contains_rectangle

fn Region::contains_rectangle(self : Region, rectangle : RectangleInt) -> RegionOverlap

Classify how this region covers rectangle.

Returns RegionOverlapIn for complete coverage, RegionOverlapOut for no overlap, and RegionOverlapPart for partial coverage.

#
Region::copy

fn Region::copy(self : Region) -> Region raise CairoError

Create an independently owned copy of this region's current coverage.

Later mutations of either region do not affect the other. Raises CairoMemoryError(NoMemory, _) if Cairo cannot allocate the copy.

#
Region::equal

fn Region::equal(self : Region, other : Region) -> Bool

Return whether two regions cover exactly the same area.

Equality is independent of wrapper identity, allocation identity, and the rectangle decomposition chosen by Cairo.

#
Region::from_rectangle

fn Region::from_rectangle(rectangle : RectangleInt) -> Region raise CairoError

Create a region containing rectangle.

The rectangle is copied into Cairo and is not retained. Raises CairoMemoryError(NoMemory, _) if Cairo cannot allocate the region.

#
Region::from_rectangles

fn Region::from_rectangles(rectangles : ArrayView[RectangleInt]) -> Region raise CairoError

Create a region containing the union of rectangles.

An empty view creates an empty region. Cairo copies and normalizes the input, so it may merge or split rectangles and does not preserve their count or order. Raises CairoMemoryError(NoMemory, _) on allocation failure.

#
Region::get_extents

fn Region::get_extents(self : Region) -> RectangleInt raise CairoError

Return the integer bounding rectangle of the entire region.

This is an extent, not one element of Cairo's normalized decomposition. Raises the region's checked CairoError status if the query fails.

#
Region::get_rectangle

fn Region::get_rectangle(self : Region, index : Int) -> RectangleInt raise CairoError

Return rectangle index from Cairo's normalized decomposition.

Decomposition order is Cairo-defined and must not be used as a stable serialization format. Raises CairoInvalidArgument(InvalidIndex, _) for a negative or out-of-range index, or the region's checked status on failure.

#
Region::intersect

fn Region::intersect(self : Region, other : Region) -> Region raise CairoError

Replace this region with its intersection with other.

other is neither retained nor mutated. Returns this same receiver for chaining. Raises CairoMemoryError(NoMemory, _) if Cairo cannot allocate the result.

#
Region::intersect_rectangle

fn Region::intersect_rectangle(self : Region, rectangle : RectangleInt) -> Region raise CairoError

Replace this region with its intersection with rectangle.

The rectangle is not retained. Returns this same receiver for chaining. Raises CairoMemoryError(NoMemory, _) if Cairo cannot allocate the result.

#
Region::is_empty

fn Region::is_empty(self : Region) -> Bool

Return whether this region covers no area.

#
Region::new

fn Region::new() -> Region raise CairoError

Create a new empty region.

Raises CairoMemoryError(NoMemory, _) if Cairo cannot allocate it.

#
Region::num_rectangles

fn Region::num_rectangles(self : Region) -> Int

Return the number of rectangles in Cairo's normalized decomposition.

The result need not equal the number passed to from_rectangles.

#
Region::status

fn Region::status(self : Region) -> Status

Return the status stored in this region without raising it.

Public constructors and mutators check their status before returning, so Success is expected for regions obtained through the public API.

#
Region::subtract

fn Region::subtract(self : Region, other : Region) -> Region raise CairoError

Remove every point covered by other from this region.

other is neither retained nor mutated. Returns this same receiver for chaining. Raises CairoMemoryError(NoMemory, _) if Cairo cannot allocate the result.

#
Region::subtract_rectangle

fn Region::subtract_rectangle(self : Region, rectangle : RectangleInt) -> Region raise CairoError

Remove every point covered by rectangle from this region.

The rectangle is not retained. Returns this same receiver for chaining. Raises CairoMemoryError(NoMemory, _) if Cairo cannot allocate the result.

#
Region::translate

fn Region::translate(self : Region, dx : Int, dy : Int) -> Unit raise CairoError

Translate this region in place by the integer offset (dx, dy).

This method returns Unit. Raises the checked CairoError status reported after the mutation.

#
Region::union

fn Region::union(self : Region, other : Region) -> Region raise CairoError

Replace this region with its union with other.

other is neither retained nor mutated. Returns this same receiver for chaining. Raises CairoMemoryError(NoMemory, _) if Cairo cannot allocate the result.

#
Region::union_rectangle

fn Region::union_rectangle(self : Region, rectangle : RectangleInt) -> Region raise CairoError

Replace this region with its union with rectangle.

The rectangle is not retained. Returns this same receiver for chaining. Raises CairoMemoryError(NoMemory, _) if Cairo cannot allocate the result.

#
Region::xor

fn Region::xor(self : Region, other : Region) -> Region raise CairoError

Replace this region with the symmetric difference from other.

The result covers points present in exactly one operand. other is neither retained nor mutated. Returns this same receiver for chaining. Raises CairoMemoryError(NoMemory, _) if Cairo cannot allocate the result.

#
Region::xor_rectangle

fn Region::xor_rectangle(self : Region, rectangle : RectangleInt) -> Region raise CairoError

Replace this region with the symmetric difference from rectangle.

The result covers points present in exactly one operand. The rectangle is not retained. Returns this same receiver for chaining. Raises CairoMemoryError(NoMemory, _) if Cairo cannot allocate the result.

#
RegionOverlap

pub(all) enum RegionOverlap {
RegionOverlapIn
RegionOverlapOut
RegionOverlapPart
} derive(Eq,
Debug
)

Describes whether a rectangle lies inside, outside, or partly in a region.

#
SVGUnit

pub(all) enum SVGUnit {
SvgUnitUser
SvgUnitEm
SvgUnitEx
SvgUnitPx
SvgUnitIn
SvgUnitCm
SvgUnitMm
SvgUnitPt
SvgUnitPc
SvgUnitPercent
} derive(Eq,
Debug
)

Selects the unit used for a Cairo SVG document's width and height.

#
SVGVersion

pub(all) enum SVGVersion {
SvgVersion1_1
SvgVersion1_2
} derive(Eq,
Debug
)

An SVG language version supported by a Cairo SVG surface.

#
SVGVersion::supported

fn SVGVersion::supported() -> Array[SVGVersion] raise CairoError

Return a fresh array of SVG versions supported by the linked Cairo build.

The result is copied from Cairo's static version table and can be mutated by the caller. An unavailable SVG backend raises CairoError(InvalidStatus, _).

#
SVGVersion::to_string

fn SVGVersion::to_string(self : SVGVersion) -> String raise CairoError

Return a copied Cairo display string for this SVG version.

The result does not borrow Cairo storage. Backend or conversion failures are reported as checked CairoError values.

#
SVGVersion::to_string_raw

fn SVGVersion::to_string_raw(version : Int) -> String raise CairoError

Convert a pycairo-compatible cairo_svg_version_t integer to text.

Portable values are 0 (SVG 1.1) and 1 (SVG 1.2). Unknown positive or negative integers raise CairoError(InvalidStatus, _); the returned string is copied into MoonBit-owned storage.

#
ScaledFont

type ScaledFont

An owning handle to a Cairo font fixed to a face, size, CTM, and options.

The internal RawScaledFont owns exactly one cairo_scaled_font_t reference and destroys it through its external-object finalizer. Cairo retains or copies the native face and options state it needs, so this value remains usable after the constructor arguments leave MoonBit scope.
impl Eq for ScaledFont
impl Hash for ScaledFont

#
ScaledFont::equal

fn ScaledFont::equal(self : ScaledFont, other : ScaledFont) -> Bool

Return whether two wrappers reference the same native scaled font.

Equality is pointer identity, not equality of face, matrices, options, or metrics. Separately created fonts may be internally cached by Cairo and can therefore share identity when all native creation parameters match.

#
ScaledFont::extents

fn ScaledFont::extents(self : ScaledFont) -> FontExtents raise CairoError

Return this font's aggregate metrics in user-space units.

The result contains ascent, descent, recommended line height, and maximum X/Y advances. Backend or scaled-font failures raise checked CairoError values.

#
ScaledFont::get_ctm

fn ScaledFont::get_ctm(self : ScaledFont) -> Matrix raise CairoError

Return the user-space to device-space CTM used to create this font.

Cairo ignores CTM translation for scaled fonts, so x0 and y0 are always zero in the returned matrix. Failed scaled fonts raise checked CairoError values.

#
ScaledFont::get_font_face

fn ScaledFont::get_font_face(self : ScaledFont) -> FontFace raise CairoError

Return an independently owned wrapper for this scaled font's face.

Cairo returns a borrowed face, so cairoon adds a native reference before wrapping it. The result remains valid after self leaves scope. Some font backends may return the face actually used rather than the original input; face and scaled-font failures raise checked CairoError values.

#
ScaledFont::get_font_matrix

fn ScaledFont::get_font_matrix(self : ScaledFont) -> Matrix raise CairoError

Return the font-space to user-space matrix used to create this font.

The matrix includes font sizing, shear, stretch, and any font-matrix translation exactly as stored by Cairo. Failed scaled fonts raise their checked CairoError status.

#
ScaledFont::get_font_options

fn ScaledFont::get_font_options(self : ScaledFont) -> FontOptions raise CairoError

Return an independent copy of this scaled font's rendering options.

Mutating the returned FontOptions does not alter self. Allocation and scaled-font or options failures raise the corresponding CairoError.

#
ScaledFont::get_scale_matrix

fn ScaledFont::get_scale_matrix(self : ScaledFont) -> Matrix raise CairoError

Return the matrix mapping font space directly to device space.

Cairo defines this as the product of the stored font matrix and CTM, with CTM translation omitted. Failed scaled fonts raise checked CairoError values.

#
ScaledFont::glyph_extents

Measure positioned glyphs in user-space coordinates.

Glyph indexes and positions are copied into a temporary native array for this call and are never retained. Empty input returns zero extents. UInt64 indexes that do not fit Cairo's native unsigned long raise CairoInvalidArgument(InvalidIndex, _); other backend failures use CairoError.

#
ScaledFont::hash

fn ScaledFont::hash(self : ScaledFont) -> UInt64

Return a process-local hash of the native scaled-font pointer.

Equal live scaled fonts have equal hashes. The value is suitable for identity collections in the current process but is not stable across runs.

#
ScaledFont::new

fn ScaledFont::new(font_face : FontFace, font_matrix : Matrix, ctm : Matrix, options : FontOptions) -> ScaledFont raise CairoError

Create a scaled font from a face and font-to-user/user-to-device matrices.

font_matrix controls font size, shear, and stretch. ctm describes the device transform; Cairo ignores its translation components. Degenerate matrices are valid, including a zero-size font, but non-finite determinants raise CairoInvalidArgument(InvalidMatrix, _). Face, option, allocation, and backend failures are raised through CairoError.

#
ScaledFont::status

fn ScaledFont::status(self : ScaledFont) -> Status

Return the current Cairo status without raising.

Safe methods check and raise this status themselves. This diagnostic is primarily useful when inspecting identity or values obtained through lower level integration code.

#
ScaledFont::text_extents

fn ScaledFont::text_extents(self : ScaledFont, text : String) -> TextExtents raise CairoError

Measure UTF-8 text as drawn at user-space origin (0, 0).

Ink bounds exclude whitespace itself, while advances still account for it. The input is encoded to UTF-8 and an embedded NUL raises CairoInvalidArgument(InvalidString, _). Conversion, backend, and sticky scaled-font failures are raised through CairoError.

#
ScaledFont::text_to_glyphs

fn ScaledFont::text_to_glyphs(self : ScaledFont, x : Double, y : Double, text : String) -> TextGlyphRun raise CairoError

Convert UTF-8 text to copied glyphs plus byte-to-glyph cluster mapping.

x and y position the first glyph in user space. Returned arrays are pure MoonBit values and remain valid after Cairo's temporary native arrays are released. Cluster byte counts refer to UTF-8 bytes, not Unicode scalars. The result must be rendered with the same scaled font for matching placement. Embedded NUL raises CairoInvalidArgument(InvalidString, _); conversion, allocation, and backend failures raise checked CairoError values.

#
ScaledFont::text_to_glyphs_only

fn ScaledFont::text_to_glyphs_only(self : ScaledFont, x : Double, y : Double, text : String) -> Array[
Glyph
] raise CairoError

Convert UTF-8 text to copied glyphs without computing cluster mapping.

This is the statically typed counterpart of pycairo's with_clusters=False: cairoon passes null cluster outputs to Cairo instead of allocating and discarding them. Coordinates, ownership, NUL validation, and checked errors match text_to_glyphs().

#
ScriptMode

pub(all) enum ScriptMode {
ScriptModeAscii
ScriptModeBinary
} derive(Eq,
Debug
)

Selects human-readable or compact binary Cairo script output.

#
Status

pub(all) enum Status {
Success
NoMemory
InvalidRestore
InvalidPopGroup
NoCurrentPoint
InvalidMatrix
InvalidStatus
NullPointer
InvalidString
InvalidPathData
ReadError
WriteError
SurfaceFinished
SurfaceTypeMismatch
PatternTypeMismatch
InvalidContent
InvalidFormat
InvalidVisual
FileNotFound
InvalidDash
InvalidDscComment
InvalidIndex
ClipNotRepresentable
TempFileError
InvalidStride
FontTypeMismatch
UserFontImmutable
UserFontError
NegativeCount
InvalidClusters
InvalidSlant
InvalidWeight
InvalidSize
UserFontNotImplemented
DeviceTypeMismatch
DeviceError
InvalidMeshConstruction
DeviceFinished
Jbig2GlobalMissing
PngError
FreetypeError
Win32GdiError
TagError
DwriteError
SvgFontError
LastStatus
} derive(Eq,
Debug
)

A status code reported by Cairo.

Success is the only successful value. The remaining constructors retain Cairo's numeric ABI so statuses can be classified without string matching.

#
Status::is_success

fn Status::is_success(self : Status) -> Bool

Return whether this status is Success.

#
Status::message

fn Status::message(self : Status) -> String

Return Cairo's diagnostic message for this status.

#
SubpixelOrder

pub(all) enum SubpixelOrder {
SubpixelDefault
SubpixelRgb
SubpixelBgr
SubpixelVrgb
SubpixelVbgr
} derive(Eq,
Debug
)

Describes the physical order of subpixels on a display.

#
Surface

type Surface

An owning handle to a Cairo drawing destination or source.

Every backend uses this same opaque wrapper. It holds one internal cairo_surface_t owner, releases it through the raw object's finalizer, and may retain a parent surface or caller pixel buffer when Cairo depends on it. Identity equality and hashing compare the underlying Cairo pointer.
impl Eq for Surface
impl Hash for Surface

#
Surface::copy_data

fn Surface::copy_data(self : Surface) -> Bytes raise CairoError

Return an independent snapshot of all image bytes.

Cairo is flushed before copying. The result has height * stride bytes, includes row padding, and no longer aliases the surface; an empty image returns empty bytes. Non-image, finished, allocation, and oversized-image failures use the checked CairoError hierarchy.

#
Surface::copy_page

fn Surface::copy_page(self : Surface) -> Unit raise CairoError

Emit the current page while retaining its contents for the next page.

This matters for multi-page PDF and PS output; unsupported single-page backends may do nothing. Output and finished-surface failures raise checked CairoError. Use show_page() when the next page should start empty.

#
Surface::create_for_rectangle

fn Surface::create_for_rectangle(self : Surface, x : Double, y : Double, width : Double, height : Double) -> Surface raise CairoError

Create a rectangular subsurface that redirects drawing into self.

The rectangle is expressed in this surface's device-space units. Drawing to the child is translated and clipped to that rectangle; drawing outside it is discarded. Cairoon retains the parent wrapper for the child's lifetime. Negative dimensions or an unusable parent raise checked CairoError.

#
Surface::create_similar

fn Surface::create_similar(self : Surface, content : Content, width : Int, height : Int) -> Surface raise CairoError

Create a surface compatible with this surface's backend.

content selects color and alpha channels; dimensions are backend device units and must be non-negative. The returned surface is an independent owner, although Cairo may choose a different backend internally. Invalid sizes and source-surface failures raise the corresponding CairoError.

#
Surface::create_similar_image

fn Surface::create_similar_image(self : Surface, format : Format, width : Int, height : Int) -> Surface raise CairoError

Create a compatible image surface with an explicit pixel format.

Unlike create_similar(), a successful result is always an image surface and owns storage independent of self. width and height are pixels and must be non-negative. Invalid formats, sizes, or source state raise their checked CairoError status.

#
Surface::create_similar_image_raw

fn Surface::create_similar_image_raw(self : Surface, format : Int, width : Int, height : Int) -> Surface raise CairoError

Create a compatible image surface from a raw cairo_format_t integer.

This entry point preserves pycairo C-int compatibility, including formats supported by the linked Cairo version. The result is still checked and owned exactly like create_similar_image(); unknown values raise CairoInvalidArgument(InvalidFormat, _).

#
Surface::create_similar_raw

fn Surface::create_similar_raw(self : Surface, content : Int, width : Int, height : Int) -> Surface raise CairoError

Create a compatible surface from a pycairo-style raw cairo_content_t.

Accepted values are 0x1000, 0x2000, and 0x3000, matching Cairo's color, alpha, and color-alpha constants. Unknown integers raise CairoInvalidArgument(InvalidContent, _); dimensions and source errors use the same checked behavior as create_similar().

#
Surface::equal

fn Surface::equal(self : Surface, other : Surface) -> Bool

Return whether two wrappers refer to the same cairo_surface_t.

This is pointer identity, not pixel or document-content equality. Borrowed surfaces returned by Context or Pattern bridges compare equal to the owner they reference.

#
Surface::finish

fn Surface::finish(self : Surface) -> Unit raise CairoError

Finish the surface and release backend resources deterministically.

Finishing is idempotent for a successful surface and leaves the wrapper available for status, identity, and final destruction only. Buffer-backed image storage retained by cairoon is released here. Even with a pre-existing sticky Cairo error, native cleanup still runs and that original error is then raised.

#
Surface::flush

fn Surface::flush(self : Surface) -> Unit raise CairoError

Complete pending Cairo drawing before direct backend or memory access.

Call this before reading or modifying image bytes outside Cairo. After a direct modification, call mark_dirty() or mark_dirty_rectangle() before drawing through Cairo again. Backends without direct access may treat this as a no-op. Sticky and finished statuses raise CairoError.

#
Surface::get_content

fn Surface::get_content(self : Surface) -> Content raise CairoError

Return the typed color/alpha content carried by this surface.

The value describes channels, not a concrete pixel layout. Finished or otherwise failed surfaces raise their checked CairoError status.

#
Surface::get_content_raw

fn Surface::get_content_raw(self : Surface) -> Int raise CairoError

Return the raw cairo_content_t integer for pycairo-compatible code.

Successful values are the exact Cairo ABI constants 0x1000, 0x2000, or 0x3000. Surface failures are checked before the integer is returned.

#
Surface::get_data

fn Surface::get_data(self : Surface) -> ImageData raise CairoError

Return a mutable view of this image surface's pixel bytes.

Pending Cairo drawing is flushed before the view is created. The view retains self and remains usable if the original MoonBit variable leaves scope, but Surface::finish() invalidates it. Calling this on a non-image surface raises CairoError(SurfaceTypeMismatch, _); a finished or errored surface raises its checked status.

#
Surface::get_device

fn Surface::get_device(self : Surface) -> Device? raise CairoError

Return this surface's backend device, when it has one.

Cairo returns a borrowed device; cairoon takes a native reference and wraps it as an independently owned Device, so the result remains valid after the surface wrapper leaves scope. Image and other device-less surfaces return None. Surface or device errors raise checked CairoError.

#
Surface::get_device_offset

fn Surface::get_device_offset(self : Surface) -> (Double, Double) raise CairoError

Return the hidden device-coordinate translation as (x, y).

Values are in device units and reflect the last set_device_offset() call or Cairo's default zero offset. Failed or finished surfaces raise their checked CairoError status.

#
Surface::get_device_scale

fn Surface::get_device_scale(self : Surface) -> (Double, Double) raise CairoError

Return the current hidden device scale as (x_scale, y_scale).

A newly created surface normally reports (1.0, 1.0). The query is checked, so finished or otherwise failed surfaces raise CairoError.

#
Surface::get_fallback_resolution

fn Surface::get_fallback_resolution(self : Surface) -> (Double, Double) raise CairoError

Return raster-fallback resolution as horizontal and vertical pixels/inch.

Cairo defaults both dimensions to 300 PPI until changed. The setting mainly matters for PDF, PS, SVG, and other vector output. Failed or finished surfaces raise checked CairoError.

#
Surface::get_font_options

fn Surface::get_font_options(self : Surface) -> FontOptions raise CairoError

Return an independent copy of this surface's default font options.

Display backends can report subpixel order while print backends can adjust hinting. The returned FontOptions owns its own Cairo options object and may be mutated without changing the surface. Failed or finished surfaces raise checked CairoError.

#
Surface::get_format

fn Surface::get_format(self : Surface) -> Format raise CairoError

Return this image surface's pixel format as a typed Format.

Prefer this method for exhaustive typed handling. A future native value not known to this cairoon build raises CairoInvalidArgument(InvalidStatus, _); subtype and lifecycle errors are also checked.

#
Surface::get_format_raw

fn Surface::get_format_raw(self : Surface) -> Int raise CairoError

Return this image surface's pixel format as the underlying C integer.

This compatibility entry point preserves values that a future Cairo may add. Calling it on a non-image or finished surface raises the corresponding checked CairoError.

#
Surface::get_height

fn Surface::get_height(self : Surface) -> Int raise CairoError

Return this image surface's height in pixels.

Calling the image-specific getter on another surface subtype raises CairoError(SurfaceTypeMismatch, _); a finished surface raises CairoError(SurfaceFinished, _).

#
Surface::get_mime_data

fn Surface::get_mime_data(self : Surface, mime_type : String) -> Bytes? raise CairoError

Copy attached bytes for mime_type, or return None when absent.

Each successful result is newly MoonBit-owned and remains valid after the surface changes or is destroyed. The MIME string must not contain embedded NUL. Invalid strings and failed or finished surfaces raise checked CairoError.

#
Surface::get_stride

fn Surface::get_stride(self : Surface) -> Int raise CairoError

Return the distance in bytes between consecutive image rows.

The stride can exceed width * bytes_per_pixel because Cairo requires row alignment. Non-image and finished surfaces raise SurfaceTypeMismatch and SurfaceFinished, respectively, through CairoError.

#
Surface::get_type

fn Surface::get_type(self : Surface) -> SurfaceType raise CairoError

Return the Cairo backend type of this surface.

This identifies image, PDF, PS, SVG, recording, tee, subsurface, and other Cairo backends; it does not transfer ownership. A failed or finished surface raises its current CairoError status.

#
Surface::get_width

fn Surface::get_width(self : Surface) -> Int raise CairoError

Return this image surface's width in pixels.

Calling the image-specific getter on another surface subtype raises CairoError(SurfaceTypeMismatch, _); a finished surface raises CairoError(SurfaceFinished, _).

#
Surface::has_show_text_glyphs

fn Surface::has_show_text_glyphs(self : Surface) -> Bool raise CairoError

Report whether this backend consumes text and cluster metadata.

false does not mean Context::show_text_glyphs() will fail; Cairo can still render glyphs while ignoring the UTF-8/cluster mapping. Use this to avoid computing metadata for a backend that cannot preserve it. Surface errors, including SurfaceFinished, are raised.

#
Surface::hash

fn Surface::hash(self : Surface) -> UInt64

Return a process-local hash of the underlying Cairo surface pointer.

Equal live surfaces have equal hashes. The value is meaningful only for identity-based collections in the current process and is not stable across runs.

#
Surface::image

fn Surface::image(format : Format, width : Int, height : Int) -> Surface raise CairoError

Create an in-memory image surface with zero-initialized pixel channels.

width and height are measured in pixels and may be zero but not negative. Cairo chooses a correctly aligned stride for format. Invalid dimensions, an unsupported format for the linked Cairo version, allocation failure, and other native errors use the checked CairoError hierarchy.

#
Surface::image_for_data

fn Surface::image_for_data(data : FixedArray[Byte], format : Format, width : Int, height : Int, stride? : Int) -> Surface raise CairoError

Create a zero-copy image surface backed by data.

Cairo uses the array's existing bytes as the initial pixels and rendering writes back into the same storage. Cairoon retains the array until the surface is finished or finalized, so the caller does not need to extend its lexical lifetime. If stride is omitted, Format::stride_for_width() is used. The stride must satisfy Cairo's alignment rules and data.length() must cover at least height * stride; extra bytes are not part of the image. Negative dimensions, an invalid stride, or a short buffer raise the corresponding CairoInvalidArgument suberror.

Direct writes through the original array bypass ImageData::set(); call mark_dirty() before asking Cairo to read such external changes. Call flush() before inspecting writes produced by Cairo.

#
Surface::image_for_data_raw

fn Surface::image_for_data_raw(data : FixedArray[Byte], format : Int, width : Int, height : Int, stride? : Int) -> Surface raise CairoError

Create a zero-copy image surface from a raw C format integer.

This is the pycairo compatibility form of image_for_data(). If stride is omitted, Cairo's raw format/width stride calculation is used; failure to calculate one raises CairoInvalidArgument(InvalidFormat, _). Buffer retention, shared-storage behavior, size validation, dirty/flush rules, and all other errors match the typed form.

#
Surface::image_from_png

fn Surface::image_from_png(path : String) -> Surface raise CairoError

Load an image surface from a PNG file path.

The path is UTF-8 encoded and embedded NUL raises CairoInvalidArgument(InvalidString, _). The returned surface independently owns decoded image storage. Missing files raise CairoError(FileNotFound, _). Cairo 1.18.2 and newer report malformed data as CairoIOError(PngError, _); Cairo 1.16 through 1.18.0 can instead report the upstream error-surface bug as CairoMemoryError(NoMemory, _). PNG support must be enabled in linked Cairo.

#
Surface::image_from_png_stream

fn Surface::image_from_png_stream(reader : (Int) -> Bytes) -> Surface raise CairoError

Decode a PNG by synchronously requesting exact-size byte chunks.

Cairo calls reader(length) until decoding completes; every returned Bytes value must contain exactly length bytes. The callback is borrowed only during construction and cannot raise. Short reads map to CairoIOError(ReadError, _). Cairo 1.18.2 and newer map malformed data to CairoIOError(PngError, _); Cairo 1.16 through 1.18.0 can surface the upstream error-surface bug as CairoMemoryError(NoMemory, _).

#
Surface::image_raw

fn Surface::image_raw(format : Int, width : Int, height : Int) -> Surface raise CairoError

Create an image surface from a pycairo-compatible raw C format integer.

Prefer Surface::image() for typed code. Known values have the same zero-initialization and dimension rules; an unknown or unavailable value raises CairoInvalidArgument(InvalidFormat, _).

#
Surface::map_to_image

fn Surface::map_to_image(self : Surface, extents? : RectangleInt?) -> MappedImageSurface raise CairoError

Map all or part of this surface to an efficiently writable image.

None maps the whole backing store; Some(rect) limits the mapping to that device-space rectangle. The returned handle retains self and must be unmapped exactly once. While it is active, using the original surface as a drawing source or target, mapping it again, or changing either device transform is undefined by Cairo. Mapping and source-surface errors are raised through CairoError.

#
Surface::mark_dirty

fn Surface::mark_dirty(self : Surface) -> Unit raise CairoError

Notify Cairo that external code modified this surface's entire contents.

Direct access must be bracketed by flush() before the modification and this call afterward; concurrent Cairo and external drawing is unsupported. The mutation invalidates cached snapshots and raises the checked surface status, including SurfaceFinished.

#
Surface::mark_dirty_rectangle

fn Surface::mark_dirty_rectangle(self : Surface, x : Int, y : Int, width : Int, height : Int) -> Unit raise CairoError

Notify Cairo that external code modified one device-space rectangle.

x and y locate the dirty region and width/height give its size in integer surface device units. Call flush() before the external write. Cairo may retain caches outside this rectangle and resets cached clipping; finished or failed surfaces raise CairoError.

#
Surface::pdf

fn Surface::pdf(width_in_points : Double, height_in_points : Double, path? : String?) -> Surface raise CairoError

Create an owning multi-page PDF surface measured in points.

One point is 1/72 inch. None creates a queryable/drawable no-output surface that can also be used as a source; Some(path) writes to that UTF-8 filename and rejects embedded NUL with CairoInvalidArgument(InvalidString, _). Use pdf_set_size between pages when page dimensions differ, and call finish to finalize output and report write errors. This requires Cairo's PDF backend (available since Cairo 1.2).

#
Surface::pdf_add_outline

fn Surface::pdf_add_outline(self : Surface, parent_id : Int, title : String, link_attributes : String, flags : PDFOutlineFlags) -> Int raise CairoError

Add one PDF outline item with a single typed display flag.

Use PDF_OUTLINE_ROOT for a top-level item or an id returned by an earlier outline call for a child. title is UTF-8. link_attributes uses Cairo's Link-tag key/value grammar without the rect key, for example "page=1 pos=[12 24]". The returned positive id can parent later items. String and attribute failures are checked; use pdf_add_outline_with_flags to combine display flags.

#
Surface::pdf_add_outline_raw

fn Surface::pdf_add_outline_raw(self : Surface, parent_id : Int, title : String, link_attributes : String, flags : Int) -> Int raise CairoError

Add a PDF outline item with an exact pycairo-compatible flag integer.

Portable values use only mask 0x07. Other bits cross the raw boundary unchanged but have no guaranteed PDF rendering semantics. Parent, title, Link-tag attributes, return value, availability, and checked receiver errors match pdf_add_outline_with_flags.

#
Surface::pdf_add_outline_with_flags

fn Surface::pdf_add_outline_with_flags(self : Surface, parent_id : Int, title : String, link_attributes : String, flags : PDFOutlineFlagSet) -> Int raise CairoError

Add a PDF outline item with a typed or combined flag set.

Parent, title, link, return-value, and error contracts match pdf_add_outline. The portable mask combines Open (0x01), Bold (0x02), and Italic (0x04). Cairoon supports the 1.15.10 development API; Cairo documents the stable API since 1.16.

#
Surface::pdf_restrict_to_version

fn Surface::pdf_restrict_to_version(self : Surface, version : PDFVersion) -> Unit raise CairoError

Restrict generated output to a PDF version supported by linked Cairo.

Call this immediately after construction and before any drawing. A typed version absent from PDFVersion::supported() raises CairoError(InvalidStatus, _) without calling Cairo's restriction function. Finished and non-PDF surfaces raise SurfaceFinished and SurfaceTypeMismatch respectively. The underlying Cairo API is available since 1.10.

#
Surface::pdf_restrict_to_version_raw

fn Surface::pdf_restrict_to_version_raw(self : Surface, version : Int) -> Unit raise CairoError

Restrict PDF output using a checked C-compatible version integer.

Only raw ids returned by PDFVersion::supported() are accepted. Negative, unavailable, and unknown values such as 99 raise CairoError(InvalidStatus, _) before Cairo can alter internal PDF state. Timing and receiver errors match pdf_restrict_to_version.

#
Surface::pdf_set_custom_metadata

fn Surface::pdf_set_custom_metadata(self : Surface, name : String, value : String?) -> Unit raise CairoError

Set, replace, or remove a custom PDF metadata entry.

name may not be empty or one of Title, Author, Subject, Keywords, Creator, Producer, CreationDate, ModDate, or Trapped. None and Some("") both remove the entry. Embedded NUL is rejected before FFI; reserved names set InvalidString. This requires Cairo 1.17.6 development or 1.18+, while older linked versions raise CairoError(InvalidStatus, _).

#
Surface::pdf_set_metadata

fn Surface::pdf_set_metadata(self : Surface, metadata : PDFMetadata, value : String) -> Unit raise CairoError

Set one standard PDF document metadata field.

Title, Author, Subject, Keywords, and Creator accept arbitrary MoonBit text. CreateDate and ModDate must follow YYYY-MM-DDThh:mm:ss with optional Z or [+/-]hh:mm. Embedded NUL raises CairoInvalidArgument(InvalidString, _). Cairoon supports this API at its 1.15.10 development floor; Cairo documents the stable API since 1.16.

#
Surface::pdf_set_metadata_raw

fn Surface::pdf_set_metadata_raw(self : Surface, metadata : Int, value : String) -> Unit raise CairoError

Set standard PDF metadata using a checked C-compatible field id.

Portable ids are 0=Title, 1=Author, 2=Subject, 3=Keywords, 4=Creator, 5=CreateDate, and 6=ModDate. Other integers raise CairoError(InvalidStatus, _) before calling Cairo's metadata setter. Value formatting, string validation, version availability, and receiver errors match pdf_set_metadata.

#
Surface::pdf_set_page_label

fn Surface::pdf_set_page_label(self : Surface, label : String) -> Unit raise CairoError

Set the label for the current PDF page.

The label is copied as UTF-8; embedded NUL raises CairoInvalidArgument(InvalidString, _). Call this separately for each page that needs a label. Cairoon supports the 1.15.10 development API; Cairo documents the stable API since 1.16.

#
Surface::pdf_set_size

fn Surface::pdf_set_size(self : Surface, width_in_points : Double, height_in_points : Double) -> Unit raise CairoError

Set the size, in points, of the current and subsequent PDF pages.

Call this before drawing on the current page: immediately after creation or after completing a page with show_page or copy_page. One point is 1/72 inch. Finished and non-PDF surfaces raise checked Surface errors. This Cairo API is available since 1.2.

#
Surface::pdf_set_thumbnail_size

fn Surface::pdf_set_thumbnail_size(self : Surface, width : Int, height : Int) -> Unit raise CairoError

Set thumbnail dimensions for the current and all subsequent PDF pages.

Setting either width or height to zero disables thumbnails until a later call supplies two positive dimensions. Cairoon supports the 1.15.10 development API; Cairo documents the stable API since 1.16. Finished and non-PDF surfaces raise checked Surface errors.

#
Surface::pdf_stream

fn Surface::pdf_stream(width_in_points : Double, height_in_points : Double, writer : (Bytes) -> Status) -> Surface raise CairoError

Create an owning PDF surface that sends encoded bytes to writer.

Width and height are points. Cairoon retains the writer until the Surface is collected and gives it independent Bytes chunks that remain valid after each callback. Return Success to continue; callback failures are raised by drawing or finish, and non-writer statuses such as LastStatus become CairoIOError(WriteError, _). Construction failures release the writer only after Cairo can no longer invoke it.

#
Surface::ps

fn Surface::ps(width_in_points : Double, height_in_points : Double, path? : String?) -> Surface raise CairoError

Create an owning multi-page PostScript surface measured in points.

One point is 1/72 inch. None creates a queryable/drawable no-output surface; Some(path) writes to that UTF-8 filename and rejects embedded NUL with CairoInvalidArgument(InvalidString, _). Individual page sizes may be changed with ps_set_size. Call finish to finalize output and report write errors. This requires Cairo's PS backend (available since Cairo 1.2).

#
Surface::ps_dsc_begin_page_setup

fn Surface::ps_dsc_begin_page_setup(self : Surface) -> Unit raise CairoError

Direct subsequent DSC comments to the current page's PageSetup section.

For the first page, call this after ps_dsc_begin_setup and before drawing. Later show_page or copy_page transitions already direct comments to the new page; repeating this call is harmless. Cairo does not rewind section state on out-of-order calls. Finished and non-PS surfaces raise checked Surface errors.

#
Surface::ps_dsc_begin_setup

fn Surface::ps_dsc_begin_setup(self : Surface) -> Unit raise CairoError

Direct subsequent DSC comments to the document-wide Setup section.

Call this at most once, after any Header comments and before page setup or drawing. Cairo does not rewind a later section when calls are out of order, so this method is a section transition rather than an ordering validator. Finished and non-PS surfaces raise checked Surface errors.

#
Surface::ps_dsc_comment

fn Surface::ps_dsc_comment(self : Surface, comment : String) -> Unit raise CairoError

Queue one PostScript Document Structuring Conventions comment.

comment must start with %, contain at most 255 UTF-8 bytes including the initial percent characters, and contain no newline. Do not emit Cairo-owned %!PS-Adobe-3.0, %%Creator, %%CreationDate, %%Pages, %%BoundingBox, %%DocumentData, %%LanguageLevel, %%EndComments, %%BeginSetup, %%EndSetup, %%BeginPageSetup, %%PageBoundingBox, %%EndPageSetup, %%BeginProlog, %%EndProlog, %%Page, %%Trailer, or %%EOF markers. Prefix/length failures set sticky InvalidDscComment; embedded NUL raises CairoInvalidArgument(InvalidString, _) before FFI. Comments target Header, Setup, or PageSetup according to the current DSC section. Finished and non-PS surfaces raise checked Surface errors.

#
Surface::ps_get_eps

fn Surface::ps_get_eps(self : Surface) -> Bool raise CairoError

Return whether this surface is configured for Encapsulated PostScript.

New Cairo PS surfaces default to ordinary PostScript. The returned value is current backend state; finished and non-PS surfaces raise checked Surface errors rather than returning a fallback false.

#
Surface::ps_restrict_to_level

fn Surface::ps_restrict_to_level(self : Surface, level : PSLevel) -> Unit raise CairoError

Restrict generated PostScript to level before performing any drawing.

Cairo otherwise chooses its backend default. Call this immediately after construction; changing the level after output begins is outside Cairo's contract. Finished and non-PS surfaces raise SurfaceFinished and SurfaceTypeMismatch respectively. The Cairo API is available since 1.6.

#
Surface::ps_restrict_to_level_raw

fn Surface::ps_restrict_to_level_raw(self : Surface, level : Int) -> Unit raise CairoError

Restrict PostScript output using an exact pycairo-compatible C integer.

Values 0 and 1 select Levels 2 and 3. The positive sentinel 99 crosses the raw ABI unchanged and is observed as a no-op on Cairo 1.15.10 and 1.18.4; other out-of-range values are unsupported. Prefer the typed method for portable code. Timing and checked receiver errors match ps_restrict_to_level.

#
Surface::ps_set_eps

fn Surface::ps_set_eps(self : Surface, eps : Bool) -> Unit raise CairoError

Enable or disable Encapsulated PostScript for the current document.

Set this before drawing on the current page, normally immediately after construction. A valid EPS document must contain no more than one page. Finished and non-PS surfaces raise checked Surface errors. This Cairo API is available since 1.6.

#
Surface::ps_set_size

fn Surface::ps_set_size(self : Surface, width_in_points : Double, height_in_points : Double) -> Unit raise CairoError

Set the size, in points, of the current and subsequent PostScript pages.

Call this before drawing on the current page: immediately after creation or after completing a page with show_page or copy_page. One point is 1/72 inch. Finished and non-PS surfaces raise checked Surface errors.

#
Surface::ps_stream

fn Surface::ps_stream(width_in_points : Double, height_in_points : Double, writer : (Bytes) -> Status) -> Surface raise CairoError

Create an owning PostScript surface that sends encoded bytes to writer.

Width and height are points. Cairoon retains the writer until the Surface is collected and gives it independent Bytes chunks that remain valid after each callback. Return Success to continue; callback failures are raised by drawing or finish, and non-writer statuses such as LastStatus become CairoIOError(WriteError, _). Construction failures release the writer only after Cairo can no longer invoke it.

#
Surface::recording

fn Surface::recording(content : Content, extents? : Rectangle?) -> Surface raise CairoError

Create an owning recording surface for replayable drawing operations.

Cairo snapshots the paths, patterns, and other native state needed by each recorded operation, so temporary drawing arguments need not outlive the call that records them. None creates an unbounded surface; Some(rect) supplies finite extents in Cairo recording-surface pixels. This requires Cairo recording-surface support (Cairo 1.10 or newer); an unavailable backend raises CairoError(InvalidStatus, _), while allocation and native failures raise their checked CairoError values.

#
Surface::recording_get_extents

fn Surface::recording_get_extents(self : Surface) -> Rectangle? raise CairoError

Return the finite extents supplied at construction, or None if unbounded.

A bounded result preserves the original floating-point rectangle rather than Cairo's internal integer analysis bounds. Matching pycairo, this read-only query remains available after finish; a different surface type or a sticky native error raises the corresponding checked CairoError.

#
Surface::recording_ink_extents

fn Surface::recording_ink_extents(self : Surface) -> Rectangle raise CairoError

Measure the bounding box of ink produced by the recorded operations.

The returned rectangle is (x0, y0, width, height) in recording-surface coordinates and can size a replay target. A non-recording receiver raises CairoError(SurfaceTypeMismatch, _); an explicitly finished receiver raises CairoError(SurfaceFinished, _) under cairoon's terminal-surface policy.

#
Surface::recording_raw

fn Surface::recording_raw(content : Int, extents? : Rectangle?) -> Surface raise CairoError

Create a recording surface from a pycairo-compatible cairo_content_t int.

This has the same ownership, snapshot, and optional pixel-extents contract as Surface::recording. Known Cairo values such as 0x1000, 0x2000, and 0x3000 are accepted; any other value raises CairoInvalidArgument(InvalidContent, _) before entering Cairo.

#
Surface::script

fn Surface::script(device : Device, content : Content, width : Double, height : Double) -> Surface raise CairoError

Create a surface whose rendering commands are emitted through device.

device must be a script device. content selects the typed color/alpha channels and width/height are measured in pixels. The returned Surface owns its native reference; Cairo retains the native device relationship it needs, so the MoonBit Device wrapper may leave scope independently. Constructor and object-status failures are raised as CairoError.

#
Surface::script_for_target

fn Surface::script_for_target(device : Device, target : Surface) -> Surface raise CairoError

Create a proxy that renders to target and records the same operations.

Drawing through the returned surface is forwarded to target while the script device records it for replay. Cairo retains the native target and device references needed by the proxy; the MoonBit wrappers may therefore leave scope independently. A non-script device, an errored target, or a constructor failure raises the corresponding checked CairoError.

#
Surface::script_raw

fn Surface::script_raw(device : Device, content : Int, width : Double, height : Double) -> Surface raise CairoError

Create a script surface from a pycairo-compatible raw content integer.

Prefer Surface::script() for typed code. Only Cairo's color, alpha, and color-alpha content values are accepted; another integer raises CairoInvalidArgument(InvalidContent, _) before native construction. Ownership, dimensions, backend checks, and error behavior otherwise match Surface::script().

#
Surface::set_device_offset

fn Surface::set_device_offset(self : Surface, x_offset : Double, y_offset : Double) -> Unit raise CairoError

Set a hidden device-coordinate translation for this surface.

Offsets are measured in device units and affect both drawing to the surface and using it as a source pattern, without appearing as a Context CTM transform. The operation mutates surface state and raises checked errors for failed or finished surfaces.

#
Surface::set_device_scale

fn Surface::set_device_scale(self : Surface, x_scale : Double, y_scale : Double) -> Unit raise CairoError

Set the hidden X and Y device scale applied after the Context CTM.

The scale affects both rendering targets and source-pattern sampling. Neither factor may be zero because Cairo requires an invertible transform; singular values raise CairoInvalidArgument(InvalidMatrix, _). Other surface failures are mapped through CairoError.

#
Surface::set_fallback_resolution

fn Surface::set_fallback_resolution(self : Surface, x_pixels_per_inch : Double, y_pixels_per_inch : Double) -> Unit raise CairoError

Set horizontal and vertical resolution for raster fallbacks.

Values are pixels per inch and must be positive. They affect unsupported operations emitted by vector backends at copy_page() or show_page(); raster backends use native resolution. Non-positive values raise CairoInvalidArgument(InvalidMatrix, _) and other failures raise CairoError.

#
Surface::set_mime_data

fn Surface::set_mime_data(self : Surface, mime_type : String, data : Bytes?) -> Unit raise CairoError

Attach or remove alternate encoded image data for a MIME type.

Some(data) copies every byte into Cairo-owned storage; later MoonBit mutation cannot change it. None removes the entry. The MIME string is UTF-8 encoded and embedded NUL raises CairoInvalidArgument(InvalidString, _). Replacement, allocation, and finished-surface failures use the checked CairoError hierarchy.

#
Surface::show_page

fn Surface::show_page(self : Surface) -> Unit raise CairoError

Emit the current page and clear it before the next page.

Multi-page backends finalize one page; unsupported backends may treat the call as a no-op. Stream/write and finished-surface failures raise checked CairoError. Use copy_page() to preserve current page contents.

#
Surface::status

fn Surface::status(self : Surface) -> Status

Return this surface's current Cairo status without raising.

This diagnostic also reports SurfaceFinished after cairoon has explicitly finished a successful surface. Safe operations check and raise statuses themselves, so callers do not need to poll this method after each call.

#
Surface::supports_mime_type

fn Surface::supports_mime_type(self : Surface, mime_type : String) -> Bool raise CairoError

Return whether this surface backend can consume mime_type directly.

Support is backend-specific, for example PDF may embed JPEG data while an image surface commonly reports no such output capability. The UTF-8 MIME string must not contain NUL. Invalid strings and surface failures raise checked CairoError.

#
Surface::svg

fn Surface::svg(width_in_points : Double, height_in_points : Double, path? : String?) -> Surface raise CairoError

Create an owning SVG surface with a page size measured in points.

One point is 1/72 inch. None creates a queryable/drawable no-output surface; Some(path) writes UTF-8 SVG to that file and rejects embedded NUL with CairoInvalidArgument(InvalidString, _). Call finish to finalize the document and surface any write error. This requires Cairo's SVG backend (CAIRO_HAS_SVG_SURFACE, available since Cairo 1.2).

#
Surface::svg_get_document_unit

fn Surface::svg_get_document_unit(self : Surface) -> SVGUnit raise CairoError

Return the unit used for the generated SVG root width and height.

This API is present at cairoon's Cairo 1.15.10 compatibility floor and in Cairo 1.16 or newer. Historical Cairo builds may default to SvgUnitUser or SvgUnitPt; call svg_set_document_unit for deterministic output. Finished and non-SVG receivers raise checked Surface errors.

#
Surface::svg_get_document_unit_raw

fn Surface::svg_get_document_unit_raw(self : Surface) -> Int raise CairoError

Return the exact cairo_svg_unit_t integer for this document.

Values 0 through 9 correspond to SvgUnitUser through SvgUnitPercent. The result follows the same version requirement and checked receiver behavior as svg_get_document_unit.

#
Surface::svg_restrict_to_version

fn Surface::svg_restrict_to_version(self : Surface, version : SVGVersion) -> Unit raise CairoError

Restrict this document to version before performing any drawing.

Cairo otherwise defaults to its backend version. Calling this after output has begun has backend-defined results, so set it immediately after construction. Finished and non-SVG surfaces raise SurfaceFinished and SurfaceTypeMismatch respectively.

#
Surface::svg_restrict_to_version_raw

fn Surface::svg_restrict_to_version_raw(self : Surface, version : Int) -> Unit raise CairoError

Restrict SVG output using an exact pycairo-compatible C integer.

Values 0 and 1 select SVG 1.1 and 1.2. The positive sentinel 99 crosses the raw ABI unchanged and is observed as a no-op on Cairo 1.15.10 and 1.18.4. Other out-of-range values are unsupported; use the typed method unless preserving tested C-int behavior is required. The same timing and checked receiver errors apply.

#
Surface::svg_set_document_unit

fn Surface::svg_set_document_unit(self : Surface, unit : SVGUnit) -> Unit raise CairoError

Set the unit written on the SVG root width and height attributes.

This does not rescale drawing coordinates. Cairo permits the call before it generates the document, but setting it immediately after construction keeps intent unambiguous. The API requires Cairo 1.15.10/1.16 or newer; finished and non-SVG receivers raise checked Surface errors.

#
Surface::svg_set_document_unit_raw

fn Surface::svg_set_document_unit_raw(self : Surface, unit : Int) -> Unit raise CairoError

Set the document unit from an exact pycairo-compatible C integer.

Portable values are 0 through 9. The positive sentinel 99 crosses the raw ABI unchanged and is observed as a no-op on Cairo 1.15.10 and 1.18.4; other out-of-range values are unsupported. Prefer the typed method for new code. Unit effects, version requirements, and checked receiver errors match svg_set_document_unit.

#
Surface::svg_stream

fn Surface::svg_stream(width_in_points : Double, height_in_points : Double, writer : (Bytes) -> Status) -> Surface raise CairoError

Create an owning SVG surface that sends encoded output to writer.

Width and height are points. Cairoon retains the writer until the Surface is collected and passes it independent Bytes chunks that remain valid after each callback. Return Success to continue; non-success statuses are raised by the drawing or finish operation, and invalid status integers become CairoIOError(WriteError, _). Construction failures release the writer only after Cairo can no longer invoke it.

#
Surface::tee

fn Surface::tee(primary : Surface) -> Surface raise CairoError

Create an owning tee surface whose index-zero target is primary.

Drawing through the result is forwarded to the primary and every added replica. The primary controls queried content, device, font options, and extents. Cairoon retains the primary MoonBit wrapper until the tee is collected. This requires CAIRO_HAS_TEE_SURFACE (Cairo 1.10 or newer); an unavailable backend, a finished/error primary, or construction failure raises a checked CairoError.

#
Surface::tee_add

fn Surface::tee_add(self : Surface, target : Surface) -> Unit raise CairoError

Append a drawing target to this tee surface.

A successful call creates both Cairo's native target reference and a retained MoonBit owner edge; each duplicate add is a distinct replica. tee_remove releases one matching edge. Finished or wrong-type receivers and erroneous targets raise checked errors. Adding the tee to itself raises CairoError(InvalidStatus, _) to prevent a permanent ownership cycle.

#
Surface::tee_index

fn Surface::tee_index(self : Surface, index : Int) -> Surface raise CairoError

Return an independently referenced surface at index.

Index zero is the primary; added replicas follow in insertion order. The result remains valid after a matching tee_remove or after the tee wrapper leaves scope. Negative indexes raise CairoInvalidArgument(InvalidIndex,_). Cairo maps a positive out-of-range index through its error-surface fallback to CairoMemoryError(NoMemory, _); finished and wrong-type receivers are checked before indexing.

#
Surface::tee_remove

fn Surface::tee_remove(self : Surface, target : Surface) -> Unit raise CairoError

Remove one matching added replica and release its retained wrapper edge.

The primary target at index zero cannot be removed. Removing the primary or a target that is not present gives the tee a sticky InvalidIndex status and raises CairoInvalidArgument(InvalidIndex, _). Finished/wrong-type receivers and self-removal raise their corresponding checked errors.

#
Surface::unmap_image

fn Surface::unmap_image(self : Surface, mapped : MappedImageSurface) -> Unit raise CairoError

Upload and consume a mapping created from this exact surface.

A mapping from another surface raises CairoError(SurfaceTypeMismatch, _) and remains active. A matching active mapping is always passed to Cairo for cleanup, even when the base or mapped image already has a sticky error; that earlier error is raised after cleanup. On completion the mapped handle and all derived data views are invalid, and a second unmap raises CairoError(SurfaceFinished, _).

#
Surface::with_finished

fn[T] Surface::with_finished(self : Surface, f : () -> T raise CairoError) -> T raise CairoError

Run f, then finish this surface on both success and error paths.

On success, a finish failure is raised and otherwise the closure value is returned. If f raises, cairoon performs best-effort raw cleanup and re-raises the original closure error even when finishing also reports a sticky status. This is the MoonBit counterpart to pycairo's surface context manager.

#
Surface::write_to_png

fn Surface::write_to_png(self : Surface, path : String) -> Unit raise CairoError

Encode this surface as PNG at path.

The path is UTF-8 encoded and may not contain embedded NUL. Cairo flushes the surface while encoding. Filesystem, PNG, allocation, and finished-surface failures raise checked CairoError; PNG support must be enabled in linked Cairo.

#
Surface::write_to_png_stream

fn Surface::write_to_png_stream(self : Surface, writer : (Bytes) -> Status) -> Unit raise CairoError

Encode this surface as PNG and deliver copied output chunks to writer.

Each chunk is MoonBit-owned and may be retained after the callback returns. Return Success to continue or a Cairo status to stop; out-of-range status values normalize to WriteError. The callback cannot raise through C. Writer, PNG, and surface failures are reported through CairoError.

#
SurfaceObserverMode

pub(all) enum SurfaceObserverMode {
SurfaceObserverNormal
SurfaceObserverRecordOperations
} derive(Eq,
Debug
)

The observer-surface mode values exposed by pycairo.

Cairoon's pycairo-compatibility surface currently exposes this enum only; Cairo's native observer-surface extension is outside the portable API.

#
SurfaceType

pub(all) enum SurfaceType {
SurfaceTypeImage
SurfaceTypePdf
SurfaceTypePs
SurfaceTypeXlib
SurfaceTypeXcb
SurfaceTypeGlitz
SurfaceTypeQuartz
SurfaceTypeWin32
SurfaceTypeBeos
SurfaceTypeDirectfb
SurfaceTypeSvg
SurfaceTypeOs2
SurfaceTypeWin32Printing
SurfaceTypeQuartzImage
SurfaceTypeScript
SurfaceTypeQt
SurfaceTypeRecording
SurfaceTypeVg
SurfaceTypeGl
SurfaceTypeDrm
SurfaceTypeTee
SurfaceTypeXml
SurfaceTypeSkia
SurfaceTypeSubsurface
SurfaceTypeCogl
} derive(Eq,
Debug
)

Identifies the backend that owns a Cairo surface.

Availability of a constructor for a backend depends on the linked Cairo build; this enum can still describe surfaces returned by Cairo.

#
TextCluster

pub struct TextCluster {
num_bytes : Int
num_glyphs : Int
} derive(Eq, Hash,
Debug
)

A mapping between a run of UTF-8 bytes and a run of glyphs.

Cairo requires both counts to be non-negative and at least one to be nonzero when the value is consumed by a text-cluster API. This pure value preserves the supplied counts; construction itself performs no validation.

#
TextCluster::at

#alias("_[_]")
fn TextCluster::at(self : TextCluster, index : Int) -> Int raise CairoError

Index the (num_bytes, num_glyphs) component sequence.

Raises CairoInvalidArgument(InvalidIndex, _) outside 0..1.

#
TextCluster::component

fn TextCluster::component(self : TextCluster, index : Int) -> Int raise CairoError

Return component 0..1 from (num_bytes, num_glyphs).

Raises CairoInvalidArgument(InvalidIndex, _) for any other index.

#
TextCluster::components

fn TextCluster::components(self : TextCluster) -> (Int, Int)

Return (num_bytes, num_glyphs) in pycairo tuple order.

#
TextCluster::new

fn TextCluster::new(num_bytes : Int, num_glyphs : Int) -> TextCluster

Construct a text cluster from its UTF-8 byte and glyph counts.

#
TextClusterFlags

pub(all) enum TextClusterFlags {
TextClusterNone
TextClusterBackward
} derive(Eq,
Debug
)

Describes the byte order represented by text-to-glyph clusters.

#
TextExtents

pub struct TextExtents {
x_bearing : Double
y_bearing : Double
width : Double
height : Double
x_advance : Double
y_advance : Double
} derive(Eq, Hash,
Debug
)

User-space ink bounds and advances for text or glyphs.

Bearings locate the ink rectangle relative to the origin; width and height describe that rectangle; advances locate the next text origin. Metrics can vary slightly with the current transform because of font hinting.

#
TextExtents::at

#alias("_[_]")
fn TextExtents::at(self : TextExtents, index : Int) -> Double raise CairoError

Index the six text-extents metrics in pycairo tuple order.

Raises CairoInvalidArgument(InvalidIndex, _) outside 0..5.

#
TextExtents::component

fn TextExtents::component(self : TextExtents, index : Int) -> Double raise CairoError

Return metric 0..5 in pycairo tuple order.

Raises CairoInvalidArgument(InvalidIndex, _) for any other index.

#
TextExtents::components

fn TextExtents::components(self : TextExtents) -> (Double, Double, Double, Double, Double, Double)

Return (x_bearing, y_bearing, width, height, x_advance, y_advance).

#
TextExtents::new

fn TextExtents::new(x_bearing : Double, y_bearing : Double, width : Double, height : Double, x_advance : Double, y_advance : Double) -> TextExtents

Construct text extents from six explicit metric values.

This pure constructor performs no metric validation.

#
TextGlyphRun

Glyphs plus their UTF-8 cluster mapping from text shaping.

flags describes glyph traversal order. The arrays are ordinary mutable MoonBit arrays, so callers should copy them before independent mutation.

#
TextGlyphRun::components

Return the same glyph and cluster arrays together with their flags.

The returned arrays alias the arrays stored in this run.

#
TextGlyphRun::new

Group glyph, cluster, and flag arrays without copying or validating them.

Cairo validates complete cluster coverage when a run is consumed by a text-cluster operation.

#
CAIRO_VERSION

let CAIRO_VERSION : Int

The release-source Cairo version encoded as major * 10000 + minor * 100 + micro.

#
CAIRO_VERSION_MAJOR

let CAIRO_VERSION_MAJOR : Int

The release-source Cairo major version.

#
CAIRO_VERSION_MICRO

let CAIRO_VERSION_MICRO : Int

The release-source Cairo micro version.

#
CAIRO_VERSION_MINOR

let CAIRO_VERSION_MINOR : Int

The release-source Cairo minor version.

#
CAIRO_VERSION_STRING

let CAIRO_VERSION_STRING : String

The release-source Cairo version in major.minor.micro form.

#
COLOR_PALETTE_DEFAULT

let COLOR_PALETTE_DEFAULT : UInt

The default color-palette identifier used by Cairo font options.

#
FORMAT_INVALID

let FORMAT_INVALID : Int

Cairo's raw sentinel for an invalid image format.

#
HAS_ATSUI_FONT

let HAS_ATSUI_FONT : Bool

Whether the release-source Cairo headers enable the legacy ATSUI font backend.

#
HAS_DWRITE_FONT

let HAS_DWRITE_FONT : Bool

Whether the release-source Cairo headers enable the DirectWrite font backend.

#
HAS_FT_FONT

let HAS_FT_FONT : Bool

Whether the release-source Cairo headers enable the FreeType font backend.

#
HAS_GLITZ_SURFACE

let HAS_GLITZ_SURFACE : Bool

Whether the release-source Cairo headers enable the legacy Glitz surface backend.

#
HAS_IMAGE_SURFACE

let HAS_IMAGE_SURFACE : Bool

Whether the release-source Cairo headers enable image surfaces.

#
HAS_MIME_SURFACE

let HAS_MIME_SURFACE : Bool

Whether the release-source Cairo headers enable MIME data on surfaces.

#
HAS_PDF_SURFACE

let HAS_PDF_SURFACE : Bool

Whether the release-source Cairo headers enable PDF surfaces.

#
HAS_PNG_FUNCTIONS

let HAS_PNG_FUNCTIONS : Bool

Whether the release-source Cairo headers enable PNG read and write helpers.

#
HAS_PS_SURFACE

let HAS_PS_SURFACE : Bool

Whether the release-source Cairo headers enable PostScript surfaces.

#
HAS_QUARTZ_SURFACE

let HAS_QUARTZ_SURFACE : Bool

Whether the release-source Cairo headers enable Quartz surfaces.

#
HAS_RECORDING_SURFACE

let HAS_RECORDING_SURFACE : Bool

Whether the release-source Cairo headers enable recording surfaces.

#
HAS_SCRIPT_SURFACE

let HAS_SCRIPT_SURFACE : Bool

Whether the release-source Cairo headers enable Cairo script surfaces.

#
HAS_SVG_SURFACE

let HAS_SVG_SURFACE : Bool

Whether the release-source Cairo headers enable SVG surfaces.

#
HAS_TEE_SURFACE

let HAS_TEE_SURFACE : Bool

Whether the release-source Cairo headers enable Tee surfaces.

#
HAS_USER_FONT

let HAS_USER_FONT : Bool

Whether the release-source Cairo headers enable user fonts.

#
HAS_WIN32_FONT

let HAS_WIN32_FONT : Bool

Whether the release-source Cairo headers enable the Win32 font backend.

#
HAS_WIN32_SURFACE

let HAS_WIN32_SURFACE : Bool

Whether the release-source Cairo headers enable Win32 surfaces.

#
HAS_XCB_SURFACE

let HAS_XCB_SURFACE : Bool

Whether the release-source Cairo headers enable XCB surfaces.

#
HAS_XLIB_SURFACE

let HAS_XLIB_SURFACE : Bool

Whether the release-source Cairo headers enable Xlib surfaces.

#
MIME_TYPE_CCITT_FAX

let MIME_TYPE_CCITT_FAX : String

The MIME key for CCITT Group 3 fax image data.

#
MIME_TYPE_CCITT_FAX_PARAMS

let MIME_TYPE_CCITT_FAX_PARAMS : String

The MIME key for parameters associated with CCITT fax image data.

#
MIME_TYPE_EPS

let MIME_TYPE_EPS : String

The MIME key for encapsulated PostScript data.

#
MIME_TYPE_EPS_PARAMS

let MIME_TYPE_EPS_PARAMS : String

The MIME key for parameters associated with encapsulated PostScript data.

#
MIME_TYPE_JBIG2

let MIME_TYPE_JBIG2 : String

The MIME key for JBIG2 image data.

#
MIME_TYPE_JBIG2_GLOBAL

let MIME_TYPE_JBIG2_GLOBAL : String

The MIME key for shared JBIG2 global data.

#
MIME_TYPE_JBIG2_GLOBAL_ID

let MIME_TYPE_JBIG2_GLOBAL_ID : String

The MIME key identifying the shared JBIG2 global-data object.

#
MIME_TYPE_JP2

let MIME_TYPE_JP2 : String

The MIME key for JPEG 2000 image data attached to a surface.

#
MIME_TYPE_JPEG

let MIME_TYPE_JPEG : String

The MIME key for JPEG image data attached to a surface.

#
MIME_TYPE_PNG

let MIME_TYPE_PNG : String

The MIME key for PNG image data attached to a surface.

#
MIME_TYPE_UNIQUE_ID

let MIME_TYPE_UNIQUE_ID : String

The MIME key for Cairo's unique surface identifier.

#
MIME_TYPE_URI

let MIME_TYPE_URI : String

The MIME key for a source URI attached to a surface.

#
PDF_OUTLINE_ROOT

let PDF_OUTLINE_ROOT : Int

The root outline identifier accepted by Cairo's PDF outline API.

#
TAG_CONTENT

let TAG_CONTENT : String

Cairo's tag name for content identifiers.

#
TAG_CONTENT_REF

let TAG_CONTENT_REF : String

Cairo's tag name for references to tagged content.

#
TAG_DEST

let TAG_DEST : String

Cairo's tag name for a named destination.
let TAG_LINK : String

Cairo's tag name for a hyperlink.

#
cairo_version

fn cairo_version() -> Int

Return the runtime Cairo library version in encoded integer form.

#
cairo_version_string

fn cairo_version_string() -> String

Return the runtime Cairo library version as major.minor.micro text.

#
check_status

fn check_status(status : Status) -> Unit raise CairoError

Raise the appropriate CairoError variant unless status is Success.

#
run_cairo

fn[T] run_cairo(f : () -> T raise CairoError) -> Result[T, CairoError]

Run a checked Cairo operation and capture its raised error as a Result.