Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Eternal Pixels

A UI suite and pixel art editor.

The editor is not built yet. What exists so far is the Bazel monorepo and the libraries it will be made of: ink-rs, Rust bindings to Google Ink; eternal-styler, a small CSS engine built on Servo’s cssparser and selectors crates; eternal-ui, a dense, keyboard-first UI toolkit styled with that CSS; and eternal-ui-skia, its Skia rendering backend.

Layout

crates/
  eternal-pixels/   the application            (AGPL-3.0)
  eternal-ui/       UI toolkit                 (MPL-2.0)
    themes/         the built-in stylesheet
  eternal-ui-skia/  Skia backend for the toolkit (MPL-2.0)
  eternal-styler/   CSS engine for the toolkit (MPL-2.0)
  ink-rs/           Google Ink bindings        (MPL-2.0)
    cc/             the C++ facade
    src/            the safe Rust API
patches/            Bazel module patches
third_party/        crate_universe lockfile for crates.io dependencies
tools/bindgen/      regenerates the FFI declarations
tools/ink/          builds an Ink prefix for the Cargo build
licenses/           licence texts, symlinked into each crate
docs/               this book

Building

Bazel is the development build. It fetches Ink and builds it from source, so nothing needs installing beyond Bazel.

bazel build //...
bazel test //...

The first build is long: it compiles Ink and Abseil.

API reference

The rustdoc for every crate is published next to this book at api/. To build it locally:

tools/docs/build-api.sh       # writes docs/book/api

This book

The book is built with mdBook. To work on it locally:

mdbook serve docs --open

Pages live under docs/src/, and docs/src/SUMMARY.md is the table of contents. Every push to main that touches docs/ rebuilds the book and publishes it to GitHub Pages.

The Ink bindings

crates/ink-rs is a Rust wrapper around Google Ink.

bazel run //crates/ink-rs:stroke_example draws a stroke frame by frame the way an app would and prints the resulting geometry as ASCII art.

Why there is a C++ facade in the middle

Ink’s public API is built on absl::StatusOr, absl::Span and templates, none of which cross an FFI boundary directly. Counted across Ink’s 72 public headers:

constructoccurrences
absl::Span<...>182
std::vector<...>144
std::string99
std::optional<...>72
absl::StatusOr<...>71
templates90

Brush::Create, StrokeInputBatch::Create, InProgressStroke::EnqueueInputs and most other entry points return absl::StatusOr or absl::Status and take spans. No binding generator turns that into usable Rust on its own.

So crates/ink-rs/cc/ink_ffi.h restates the parts of Ink we use as plain structs, scoped enums and pointers, with C linkage. The header includes nothing but <cstdint>, and no Ink type or standard library type appears in any signature. ink_ffi.cc is where the real Ink headers get included, and it is ordinary C++ with no constraints on it.

The layers

ink/...                        Google Ink, built from source by Bazel
  └─ //crates/ink-rs/cc:ink_ffi           the C++ facade (ink_ffi.h + .cc)
       └─ src/ffi/generated.rs            bindgen output, checked in
            └─ //crates/ink-rs            the safe Rust API

Nothing is generated during the build. src/ffi/generated.rs is produced by tools/bindgen/generate.sh and committed, so neither Bazel nor Cargo needs bindgen or libclang. It carries compile-time assertions on every struct size and field offset, so a header change that is not reflected in it fails to build rather than corrupting memory at run time.

Re-run the script after editing ink_ffi.h.

Conventions across the boundary

The facade follows a few rules so the Rust side can stay safe:

  • Ownership. Ink objects are handed out as one-word handle structs (BrushHandle, StrokeHandle, …). Every *Create/*Clone has a matching *Destroy. On the Rust side each handle lives in a type with a Drop impl, and nothing else touches it.
  • Errors. Fallible calls return a StatusCode mirroring absl::StatusCode, and record the message in thread-local storage that LastErrorMessage reads back. error::check turns the pair into a Result and must be called before anything else crosses the boundary on that thread.
  • Absent values. Ink uses sentinels: 0 for a missing physical length, -1 for missing pressure and stylus angles. The facade passes them through unchanged and input.rs converts to and from Option<f32>.
  • Null handles. Every entry point tolerates a null handle and returns a harmless default. This matters because several Ink methods CHECK-fail on a bad index; the facade range-checks first so a mistake in Rust cannot abort the process.
  • Geometry. Meshes are copied out into Vecs rather than borrowed. Ink rebuilds its meshes in place as a stroke grows, so any borrow would be invalidated by the next update_shape.
  • Floats. Ink stores times as f32 seconds and colours as linear floats, so neither round-trips exactly. Compare with a tolerance.

Adding to the bindings

To expose more of Ink, work outwards:

  1. Add the entry point to cc/ink_ffi.h, keeping to plain structs, scoped enums and pointers. Nothing from Ink or the standard library in a signature.
  2. Implement it in cc/ink_ffi.cc, converting at the edges. Add whatever Ink target it needs to the deps in cc/BUILD.bazel.
  3. Run tools/bindgen/generate.sh.
  4. Wrap it in the matching src/*.rs module. The generated declarations are only ever named from src/ffi/mod.rs, so anything new goes through there.
  5. Add a test to tests/strokes.rs.

What is bound so far

The core stroke pipeline: geometry and colour values, stock brush families, Brush, StrokeInput/StrokeInputBatch, InProgressStroke, Stroke, and mesh readback from both stroke types.

Not yet bound, and needing facade work when they are wanted:

  • Custom brush families. Only the stock brushes are exposed. BrushFamily::Create takes spans of BrushCoat, each a tree of BrushTip, BrushPaint, BrushBehavior and EasingFunction. It is the largest remaining piece.
  • Storage. ink/storage serialises strokes through protobuf. Worth doing as its own facade rather than bolting onto this one.
  • Rendering. ink/rendering targets Skia, Metal and android.graphics.Mesh directly. Reading meshes back and drawing them ourselves is likely to suit a pixel editor better.
  • Geometry algorithms. Intersection, convex hull, tessellation and affine transforms.
  • Vertex attributes beyond position. coat_mesh returns positions and indices. Brushes that vary colour or texture along the stroke also write other vertex attributes, which the facade does not read yet.

Two build paths

Bazel is the development build: it fetches Ink and builds it from source, so bazel test //... needs nothing installed beyond Bazel itself.

Cargo exists so the crate can be published. It cannot build Ink, which is a Bazel project with no install step, so it links against one you point it at with INK_ROOT. tools/ink/bundle.sh produces a suitable prefix from the Bazel build: Ink compiles to a couple of hundred separate static archives and no single libink.a, so the script merges them and lays the headers out beside the result.

./tools/ink/bundle.sh
INK_ROOT="$PWD/.ink-prefix" cargo test --manifest-path crates/ink-rs/Cargo.toml

Both paths compile the same facade and the same checked-in declarations, and both run the same tests.

Why not Crubit

The first version of these bindings used Crubit, and it did work: it generated 1916 lines covering all 63 facade functions, and the tests passed against them. It was removed anyway, for two reasons.

Its output cannot be published. The generated code calls ::ctor::MoveAndAssignViaCopy from Crubit’s own ctor crate, which is not on crates.io; the ctor name there belongs to an unrelated crate. ffi_11 and forward_declare are reserved placeholder versions. The generated code also requires nightly. So publishing would have meant a second, non-Crubit FFI layer alongside the first.

The facade makes it redundant. Crubit exists to bind rich C++ directly, but it does not handle absl::StatusOr or absl::Span, which is why the facade exists at all. Once the facade reduced the surface to plain C, Crubit was generating something bindgen generates too, without needing sixteen patches to its Bazel rules, a separately built 70 MB generator, a pinned LLVM 23, static Abseil and Protobuf builds, and a hand-written stub for a symbol missing from Homebrew’s clang.

Dropping it removed about 1500 lines of patches and tooling and let the Rust toolchain go back to stable. What was kept, the facade and the safe API, was always the real work.

Known risks

  • Replicated overrides. Bazel only honours module overrides from the root module, so every override Ink declares for itself is silently dropped here and //MODULE.bazel has to repeat it. That covers Ink’s git_override for Dawn; without it, resolution fails outright with “module dawn@v20260731.171941 not found in registries”. Repo rules called directly from a MODULE.bazel, which is how Ink pulls in Skia and libtess2, are not affected.
  • Ink patched to be depend-able. toolchains_llvm refuses to run its llvm extension for any module that is not the root, and Ink uses it. Ink is patched to drop it (patches/ink/), and the root module registers the Apple toolchain instead.
  • Pinned commits. Neither Ink nor Dawn is on the Bazel Central Registry, so both come in via git_override at a pinned commit. The Ink commit is also recorded in crates/ink-rs/Cargo.toml and in build.rs, since a Cargo build links against whatever Ink the user supplies and nothing checks the version for them.
  • No version check on the Cargo path. If INK_ROOT points at a different Ink than the facade was written against, the mismatch shows up as a link error at best and wrong behaviour at worst.

The styler

crates/eternal-styler is the CSS engine behind Eternal UI. It takes stylesheets and a tree of widgets and produces a computed style for each widget: dimensions, spacing, colours, borders and typography, resolved to numbers a layout and a renderer can use.

Why not Stylo itself

Stylo is the style system in Firefox and Servo. It is excellent and enormous: hundreds of properties, every at-rule, animations, transitions, shadow DOM, custom properties, and the machinery to restyle a document incrementally after any change. Pulling it into a UI toolkit means pulling in all of that, plus its build requirements, for a tree of a few hundred widgets that needs a dozen properties.

So instead of Stylo, the styler uses the two crates Stylo is built on, and stops there:

cssparser        tokenising and the rule/declaration grammar
  └─ selectors   selector parsing, specificity and matching
       └─ eternal-styler   properties, cascade, computed values

cssparser and selectors are maintained by Servo, are the same code Firefox ships, and are small. Everything above them is this crate’s own, and it is kept deliberately small: what a toolkit needs to style widgets and nothing a web page would.

The layers

Selectors. selectors is generic over a SelectorImpl that says which string types, pseudo-classes and pseudo-elements selectors are made of. selector.rs provides one with a PseudoClass enum for the interactive states (:hover, :disabled, :checked and so on) plus :state(name) for toolkit-defined states, and no pseudo-elements at all. Tree-structural pseudo-classes (:first-child, :nth-of-type(), :empty, :root, :has()) are handled entirely by selectors.

Elements. selectors matches against anything implementing its Element trait, which has thirty-odd methods, most of them about HTML and shadow DOM. element.rs defines this crate’s own smaller Element trait, the one a toolkit implements, and an adapter that answers the big trait from the small one. A toolkit provides identity, parent, siblings, first child, the element name, and optionally id, classes, attributes and an ElementState bitset.

Properties. properties.rs lists every longhand in one table (name, value type, whether it inherits, how to parse it) and a macro turns the table into LonghandId, PropertyDeclaration and the lookup functions. Shorthands (margin, border, border-radius, …) are expanded into longhands at parse time, so the cascade only ever sees longhands. specified.rs holds the value types as written, with units still attached.

Stylesheets. stylesheet.rs drives cssparser’s rule and declaration parsers. A stylesheet is a list of rules; a rule is a selector list and a declaration block; a declaration is a longhand, its specified value and an !important flag. Parse errors carry a line and column. parse fails on the first problem; parse_lenient skips bad declarations and rules the way a browser does and returns the problems alongside.

The cascade. styler.rs finds the rules matching an element, sorts them by specificity then source order (a later stylesheet counts as later source), and walks their declarations so that the last one for each longhand wins. Normal declarations go first, then !important ones, with inline styles above the stylesheets within each group. cascade.rs then turns the winners into a ComputedStyle: inherited properties start from the parent’s computed values, the rest from their initial values; font-size is resolved first so em has something to be relative to; color next so currentcolor does; then everything else.

Computed values. computed.rs is what the toolkit reads. Lengths are in pixels. Percentages remain percentages, since only layout knows what they are a percentage of. currentcolor is gone, replaced by the element’s colour. A border side’s width is zero if its style is none or hidden, as in CSS, so layout can add border widths without checking styles.

Using it from a toolkit

Walk the tree top-down, keeping each parent’s ComputedStyle for its children:

#![allow(unused)]
fn main() {
fn style_subtree(styler: &Styler, node: &Handle, parent: Option<&ComputedStyle>) {
    let style = styler.compute(node, parent);
    for child in node.children() {
        style_subtree(styler, &child, Some(&style));
    }
    node.set_style(style);
}
}

Styler::compute takes &self, so a styler can be shared across threads once its stylesheets are loaded. Recompute a subtree whenever an element’s state, classes or attributes change; there is no incremental restyling, and for a UI tree there does not need to be.

Styler::matching_rules returns the rules that matched an element in cascade order, which is what a style inspector wants.

Adding a property

  1. Add a specified value type to specified.rs if none of the existing ones fit, with a parse function.
  2. Add a line to the longhands! table in properties.rs. If the property has a shorthand, add it to ShorthandId.
  3. Add a field to ComputedStyle in computed.rs, set its initial value in initial(), and copy it in inherit_from if it inherits.
  4. Add an apply! line in cascade.rs that turns the specified value into the computed one.
  5. Mention it in the crate’s README and in lib.rs.

The compiler will point out anything missed: the table is the single source of truth for names, and LonghandId is matched exhaustively.

Trying a stylesheet

bazel run //crates/eternal-styler:inspect_example -- theme.css styles a small fixed widget tree with your stylesheet and prints, for every element, which rules matched and what each property computed to. Without an argument it uses a built-in example stylesheet.

Dependencies and Bazel

cssparser, cssparser-color, selectors, precomputed-hash and bitflags come from crates.io. Bazel fetches them with rules_rust’s crate_universe, configured in MODULE.bazel to read crates/eternal-styler/Cargo.toml and Cargo.lock, so the Cargo manifest is the single place dependencies are declared. The resolved graph is written to third_party/cargo-bazel-lock.json and must be regenerated whenever a Cargo.toml or Cargo.lock changes:

CARGO_BAZEL_REPIN=1 bazel build //...

selectors pins a particular minor version of cssparser, so this crate has to use the same one or there would be two copies of the parser in the build and the selector parser would not accept our Parser. Check selectors’ Cargo.toml before bumping cssparser.

What is left out

At-rules (@media, @import, @font-face), nesting, pseudo-elements, calc(), custom properties, transitions and animations, and every layout property (display, flex-*, position, …). Layout is Eternal UI’s job. border-radius takes one radius per corner; elliptical corners (a / b) are not parsed. Colours in lab(), lch(), oklab(), oklch() and color(display-p3 ...) are converted to sRGB and clipped to its gamut; the other color() spaces are rejected.

The UI toolkit

crates/eternal-ui is the toolkit Eternal Pixels is built with. It is made for tools: dense screens, strong hierarchy without decoration, keyboard and mouse as equals. The look is in the spirit of Aseprite and is nothing but a stylesheet.

The pieces

eternal-styler             CSS: parsing, selectors, cascade, computed styles
  └─ eternal-ui            elements, layout, focus, events, the ui! macro
       └─ eternal-ui-skia  draws it with Skia

The toolkit never draws anything itself. It measures text through the Fonts trait and paints through the Renderer trait, and a backend crate implements both for a particular graphics library. eternal-ui-skia does it for Skia, which is what the application uses. A Vello backend, or a tiny-skia one with its own text rasteriser, would implement the same two traits and nothing else. MonospaceFonts and RecordingRenderer in the toolkit itself are stand-ins for tests and for laying out without a window.

Windowing is not part of the toolkit either. The application feeds it Events from winit (or anything else), tells it the window size, and hands it a canvas to paint on.

A frame

#![allow(unused)]
fn main() {
// Events in, messages out.
for event in window_events {
    for message in ui.handle(&event, &fonts) {
        app.update(message, &mut ui);
    }
}
// Then layout and paint.
ui.layout(window_size, &fonts);
ui.paint(&mut renderer);
}

handle routes pointer events to the deepest element under the pointer and lets them bubble up; key events go first to window-wide shortcuts (Ui::bind), then to element shortcuts (the shortcut attribute), then to the focused element, and finally Tab and Shift+Tab move focus. Handlers produce messages of the application’s own type and handle returns them, so every decision about what happens lives in app.update, in one place.

layout recomputes styles if anything changed (an event, a class toggled, a widget edited), then sizes and places every element. paint walks the tree and for each element draws the background, the border, the widget’s own content, then the children.

Composition is declarative

The ui! macro is HTML inside Rust:

#![allow(unused)]
fn main() {
let root: Element<Msg> = ui! {
    <column class="panel">
        <row class="toolbar">
            <button id="save" shortcut="Ctrl+S" on:click={|| Msg::Save}>"Save"</button>
            <spacer/>
            <label class="dim">{format!("Editing {name}")}</label>
        </row>
        <input value={name} placeholder="File name" on:change={Msg::Rename}/>
        <checkbox checked="true" on:toggle={Msg::Wrap}>"Wrap around"</checkbox>
    </column>
};
ui.set_root(root);
}

A tag is one of the constructors in elements; Element::new makes an element from your own Widget, and {expr} children let you drop it in. Attributes are name="literal" or name={expr}; id, class, style, grow, align, disabled, shortcut and state are the framework’s, the rest go to the widget. on:click={...} attaches a handler; the name is a function in the on module and the closure has the matching signature. A closing tag that does not match its opening tag is a type error. The macro is macro_rules!, and each token costs one level of recursion, so a very large template may need #![recursion_limit = "512"].

Text inside a label is its text; text anywhere else becomes a child label, so <button>"Save"</button> is a button containing a label, and button label { ... } styles it.

Behaviour is imperative

Widgets are plain structs. Ui::widget_mut::<Label>(id) gives you the one behind an element and you call set_text on it. Ui::set_class, set_disabled, set_state, set_attr, set_inline_style, mount and remove change the tree in place. Nothing is diffed or re-rendered: change what you mean to change, and the next layout picks it up.

Styling is data

Everything an element looks like comes from CSS through eternal-styler: Ui::new starts with the built-in theme in crates/eternal-ui/themes/pixel-dark.css; Ui::set_theme replaces it and Ui::add_stylesheet layers on top; load_stylesheet reads a file. An element’s style attribute is inline CSS, and the Style builder writes inline CSS from Rust values for the computed cases.

Selectors match on the tag (button, input, panel), #id, .class, attributes, and pseudo-classes: :hover, :active, :focus, :focus-visible, :focus-within, :disabled, :enabled, :checked, :placeholder-shown, the tree-structural ones, and :state(name) for states the application sets with Ui::set_state. A checkbox’s box is a child element with the tag check, so checkbox:checked > check styles the checked look, and a disabled button is button:disabled. There is no styling API in Rust beyond that on purpose: a theme is a file anyone can edit.

Layout

Containers lay their children out along one axis, like a CSS flex row or column that never wraps. Sizes, margins, padding, borders and gaps come from the stylesheet. Structure comes from attributes: grow="1" on a child takes a share of the spare room along the axis (that is all a spacer is), align on a child places it across its parent’s axis and align_items on a container sets the default for all its children (start, center, end, stretch), and justify on a container spreads them along the axis when nothing grows (start, center, end, space-between).

width and height are border-box sizes. Percentages are of the parent’s content box. The root always fills the window. There is no wrapping, scrolling or overflow clipping yet; a text field clips its own content and that is all.

Adding a widget

Implement Widget<M> for a struct: measure for its natural size, event for what it does with input, paint for its own content, focusable if it takes focus, state for any state it owns that CSS should see, and set_attribute for the attributes it accepts. Backgrounds, borders, layout and children are the framework’s job. Then Element::new("my-tag", MyWidget::new()) puts it in a tree, and the tag is what the stylesheet matches.

The Skia backend

SkiaFonts looks typefaces up through the system font manager by the CSS family names in a style, with the generic families mapped to common system fonts. Fonts of your own, such as a pixel font shipped with the application, are loaded with SkiaFonts::load_font_file (or load_font from bytes, for include_bytes!), optionally under a family name of your choosing with the _as variants, and are then matched ahead of system fonts by font-family. SkiaRenderer draws onto any skia_safe::Canvas. Shapes are drawn without anti-aliasing and text without subpixel positioning so that 1px borders and pixel fonts stay crisp; SkiaFonts::set_smooth turns anti-aliasing on.

skia-safe fetches a prebuilt Skia for the target the first time it builds, which crate_universe runs inside Bazel’s sandbox; the sandbox allows network access on macOS, so this just works. The tests render to a raster surface and read pixels back, so they run headless.

Examples

  • bazel run //crates/eternal-ui:headless_example runs a whole application loop without a window: markup, a script of events, the messages they produce, and the draw calls of a frame.
  • bazel run //crates/eternal-ui:custom_widget_example adds a widget of its own, a colour swatch, styled by its tag.
  • bazel run //crates/eternal-ui-skia:render_png_example renders a showcase of the theme, with widgets hovered, pressed, focused, checked and disabled, to eternal-ui.png in the current directory. The quickest way to see what a theme change looks like. A second argument names a font file to set everything in.

The same files are cargo run --example <name> in each crate.

What is left out

Windowing, scrolling, wrapping, text selection and the clipboard, menus, tooltips, images and icons, animation, and any layout beyond one-axis containers. Each is meant to be built on what is here rather than to change it.